@blitznocode/blitz-orm 0.17.0 → 0.17.1

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,31 +1,31 @@
1
- import {enableMapSet,produce,isDraft,current}from'immer';import {isArray,isObject,clone,shake,tryit,parallel,mapEntries,listify,isDate,isSymbol,pick,isEqual}from'radash';import {TransactionType,TypeDBOptions,SessionType,TypeDB,TypeDBCredential}from'typedb-driver';import {RecordId,DateTime,Surreal,UnsupportedVersionError}from'surrealdb';import {customAlphabet,nanoid}from'nanoid';import qt,{z as z$1}from'zod/v4';import {traverse,getNodeByPath}from'object-traversal';import'acorn';import {isSet}from'util/types';import {v4}from'uuid';var Is=Object.defineProperty;var Cs=(e,t)=>{for(var n in t)Is(e,n,{get:t[n],enumerable:true});};var $n=new Set((process.env.BORM_LOG_TAGS||"").split(",").map(e=>e.trim()).filter(e=>!!e)),V=(e,...t)=>{($n.has("*")||(Array.isArray(e)?e.some(r=>$n.has(r)||r==="*"):$n.has(e)||e==="*"))&&console.log(...t.map(_s));},ce=(...e)=>V("debug",...e);var _s=e=>{if(Array.isArray(e)||js(e))try{return JSON.stringify(e)}catch{return e}return e},js=e=>{if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null};var Xe="SurrealClient",xs={enabled:true,attempts:-1,retryDelayMultiplier:1.2,retryDelayJitter:0},_t=class{#e=new Surreal;#s;#a;#l;#n=null;#c=false;#r=false;#t="disconnected";#i=null;#o="";constructor(t,n={}){this.#s=t,this.#a={...xs,...n.reconnect},this.#l=n.versionCheck??false;}async connect(){if(this.#r)throw new Error("Client has been closed");if(this.#t==="connected")return;if(this.#n)return this.#n;let{url:t,namespace:n,database:r,username:i,password:o}=this.#s;return V([Xe,"info"],`Opening connection to ${t}`),this.#d(),this.#t="connecting",this.#n=this.#e.connect(t,{namespace:n,database:r,versionCheck:this.#l,reconnect:this.#a,authentication:async()=>({username:i,password:o})}).then(async()=>{await this.#u(),this.#t="connected",this.#o="",V([Xe,"info"],"Connection established");}).catch(s=>{throw this.#o=s.message,s instanceof UnsupportedVersionError&&V([Xe,"error"],"Unsupported SurrealDB version",{version:s.version,minimum:s.minimum,maximum:s.maximum}),s}).finally(()=>{this.#n=null;}),this.#n}async close(){this.#r||(this.#r=true,await this.#e.close().catch(()=>{}),this.#t="disconnected",this.#i=null);}async query(t,n){if(this.#r)throw new Error("Client has been closed");return typeof t=="string"?this.#e.query(t,n):this.#e.query(t)}async beginTransaction(){if(this.#r)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="",V([Xe,"info"],"Connection re-established");}),this.#e.subscribe("disconnected",()=>{this.#t="disconnected",this.#i=null;}),this.#e.subscribe("error",t=>{this.#o=t.message,V([Xe,"error"],"Connection error",{error:t.message});}));}async#u(){try{let t=await this.#e.version();this.#i=t.version.replace(/^surrealdb-/,""),V([Xe,"info"],`Database version ${this.#i}`);}catch{V([Xe,"info"],"Database version unknown");}}};var yn={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var Y=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 Rr=(e,t)=>gn(e,t),gn=(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(r=>gn(r,t)).join(", ")}]`;if(typeof e=="object"){let n=zs(e,t);return n?`${Y(n.thing)}:\u27E8${n.id.replaceAll("\u27E9","\\\u27E9")}\u27E9`:`{${Object.entries(e).map(([o,s])=>`${JSON.stringify(o)}: ${gn(s,t)}`).join(", ")}}`}return JSON.stringify(e)},zs=(e,t)=>{let n=Object.keys(e);if(n.length!==1||n[0]!=="$ref")return null;let r=e.$ref;if(typeof r!="string")return null;let i=r.indexOf(":");if(i===-1)return null;let o=r.slice(0,i),s=r.slice(i+1);return !o||!s||!t.entities[o]&&!t.relations[o]?null:{thing:o,id:s}},jt=e=>{if(e==null)return e;if(Array.isArray(e))return e.map(jt);if(e instanceof RecordId)return e.id;if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=jt(r);return t}return e};var Tr=e=>{if(typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return `<datetime>"${e}"`;if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return JSON.stringify(e);if(["number","boolean"].includes(typeof e))return e;if(typeof e=="object"&&e!==null)return JSON.stringify(e);throw new Error(`Unsupported type ${typeof e}`)};var wr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},pt=(e,t,n)=>{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(n&&typeof e=="string")try{let r=JSON.parse(e);return Rr(r,n)}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 Tr(e);default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var vs=" ",Ge=e=>vs.repeat(e),Hs=(e,t)=>e.split(`
2
- `).map(n=>n.trim()?`${Ge(t)}${n}`:n).join(`
3
- `),Ys=e=>{let t=`USE NS test;
1
+ import {enableMapSet,produce,isDraft,current}from'immer';import {isArray,isObject,clone,shake,tryit,parallel,mapEntries,listify,isDate,isSymbol,pick,isEqual}from'radash';import {TransactionType,TypeDBOptions,SessionType,TypeDB,TypeDBCredential}from'typedb-driver';import {RecordId,DateTime,Surreal,UnsupportedVersionError}from'surrealdb';import {customAlphabet,nanoid}from'nanoid';import xt,{z as z$1}from'zod/v4';import {traverse,getNodeByPath}from'object-traversal';import'acorn';import {isSet}from'util/types';import {v4}from'uuid';var Cs=Object.defineProperty;var _s=(e,t)=>{for(var n in t)Cs(e,n,{get:t[n],enumerable:true});};var yn=new Set((process.env.BORM_LOG_TAGS||"").split(",").map(e=>e.trim()).filter(e=>!!e)),x=(e,...t)=>{(yn.has("*")||(Array.isArray(e)?e.some(r=>yn.has(r)||r==="*"):yn.has(e)||e==="*"))&&console.log(...t.map(js));},ce=(...e)=>x("debug",...e);var js=e=>{if(Array.isArray(e)||Ps(e))try{return JSON.stringify(e)}catch{return e}return e},Ps=e=>{if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null};var Ge="SurrealClient",Vs={enabled:true,attempts:-1,retryDelayMultiplier:1.2,retryDelayJitter:0},jt=class{#e=new Surreal;#s;#a;#l;#n=null;#c=false;#r=false;#t="disconnected";#i=null;#o="";constructor(t,n={}){this.#s=t,this.#a={...Vs,...n.reconnect},this.#l=n.versionCheck??false;}async connect(){if(this.#r)throw new Error("Client has been closed");if(this.#t==="connected")return;if(this.#n)return this.#n;let{url:t,namespace:n,database:r,username:i,password:o}=this.#s;return x([Ge,"info"],`Opening connection to ${t}`),this.#d(),this.#t="connecting",this.#n=this.#e.connect(t,{namespace:n,database:r,versionCheck:this.#l,reconnect:this.#a,authentication:async()=>({username:i,password:o})}).then(async()=>{await this.#u(),this.#t="connected",this.#o="",x([Ge,"info"],"Connection established");}).catch(s=>{throw this.#o=s.message,s instanceof UnsupportedVersionError&&x([Ge,"error"],"Unsupported SurrealDB version",{version:s.version,minimum:s.minimum,maximum:s.maximum}),s}).finally(()=>{this.#n=null;}),this.#n}async close(){this.#r||(this.#r=true,await this.#e.close().catch(()=>{}),this.#t="disconnected",this.#i=null);}async query(t,n){if(this.#r)throw new Error("Client has been closed");return typeof t=="string"?this.#e.query(t,n):this.#e.query(t)}async beginTransaction(){if(this.#r)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="",x([Ge,"info"],"Connection re-established");}),this.#e.subscribe("disconnected",()=>{this.#t="disconnected",this.#i=null;}),this.#e.subscribe("error",t=>{this.#o=t.message,x([Ge,"error"],"Connection error",{error:t.message});}));}async#u(){try{let t=await this.#e.version();this.#i=t.version.replace(/^surrealdb-/,""),x([Ge,"info"],`Database version ${this.#i}`);}catch{x([Ge,"info"],"Database version unknown");}}};var gn={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var Y=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 Tr=(e,t)=>En(e,t),En=(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(r=>En(r,t)).join(", ")}]`;if(typeof e=="object"){let n=Ws(e,t);return n?`${Y(n.thing)}:\u27E8${n.id.replaceAll("\u27E9","\\\u27E9")}\u27E9`:`{${Object.entries(e).map(([o,s])=>`${JSON.stringify(o)}: ${En(s,t)}`).join(", ")}}`}return JSON.stringify(e)},Ws=(e,t)=>{let n=Object.keys(e);if(n.length!==1||n[0]!=="$ref")return null;let r=e.$ref;if(typeof r!="string")return null;let i=r.indexOf(":");if(i===-1)return null;let o=r.slice(0,i),s=r.slice(i+1);return !o||!s||!t.entities[o]&&!t.relations[o]?null:{thing:o,id:s}},Pt=e=>{if(e==null)return e;if(Array.isArray(e))return e.map(Pt);if(e instanceof RecordId)return e.id;if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Pt(r);return t}return e};var wr=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 Sr={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"},pt=(e,t,n)=>{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(n&&typeof e=="string")try{let r=JSON.parse(e);return Tr(r,n)}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 wr(e);default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var Hs=" ",et=e=>Hs.repeat(e),Ys=(e,t)=>e.split(`
2
+ `).map(n=>n.trim()?`${et(t)}${n}`:n).join(`
3
+ `),Ks=e=>{let t=`USE NS test;
4
4
  USE DB test;
5
5
 
6
6
  BEGIN TRANSACTION;
7
7
  `,n=Object.entries(e).filter(([,a])=>a.type==="entity"),r=Object.entries(e).filter(([,a])=>a.type==="relation"),i=`-- ENTITIES
8
- ${Sr(n,e)}`,o=`
8
+ ${Mr(n,e)}`,o=`
9
9
 
10
10
  -- RELATIONS
11
- ${Sr(r,e)}`,s=`
11
+ ${Mr(r,e)}`,s=`
12
12
 
13
13
  -- INTERNAL
14
- ${Ge(1)}DEFINE TABLE Delta SCHEMALESS PERMISSIONS FULL;
14
+ ${et(1)}DEFINE TABLE Delta SCHEMALESS PERMISSIONS FULL;
15
15
  `;return `${t}${i}${o}${s}COMMIT TRANSACTION;
16
- `},Sr=(e,t)=>e.map(([n,r])=>Js(Y(n),r,1,t)).join(`
16
+ `},Mr=(e,t)=>e.map(([n,r])=>Zs(Y(n),r,1,t)).join(`
17
17
 
18
- `),Ks=(e,t)=>{let n=new Map,r=(i,o,s)=>{let a=n.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}"`);n.set(i,{originalName:o,fieldType:s});};for(let i of Object.values(t.fields))if(i.type==="data"){if(i.name==="id")continue;r(Y(i.name),i.name,"data");}else i.type==="link"?r(be(i.name),i.name,"link"):i.type==="role"?r(Y(i.name),i.name,"role"):i.type==="ref"&&r(Y(i.name),i.name,"ref");},Js=(e,t,n,r)=>{Ks(e,t);let i=`${Ge(n)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${t.extends?` //EXTENDS ${t.extends};`:""}`,o=Object.values(t.fields).filter(m=>m.type==="data"),s=Zs(o,e,n),a=Object.values(t.fields).filter(m=>m.type==="link"),l=Xs(a,e,n,r),d="";if(t.type==="relation"){let m=Object.entries(t.fields).filter(h=>h[1].type==="role");m.length>0&&(d=ea(m,e,n,r));}let c=Object.values(t.fields).filter(m=>m.type==="ref"),p=c.length>0?ta(c,e,n):"",u=[];s&&u.push(`-- DATA FIELDS
18
+ `),Js=(e,t)=>{let n=new Map,r=(i,o,s)=>{let a=n.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}"`);n.set(i,{originalName:o,fieldType:s});};for(let i of Object.values(t.fields))if(i.type==="data"){if(i.name==="id")continue;r(Y(i.name),i.name,"data");}else i.type==="link"?r(be(i.name),i.name,"link"):i.type==="role"?r(Y(i.name),i.name,"role"):i.type==="ref"&&r(Y(i.name),i.name,"ref");},Zs=(e,t,n,r)=>{Js(e,t);let i=`${et(n)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${t.extends?` //EXTENDS ${t.extends};`:""}`,o=Object.values(t.fields).filter(m=>m.type==="data"),s=Xs(o,e,n),a=Object.values(t.fields).filter(m=>m.type==="link"),l=Gs(a,e,n,r),d="";if(t.type==="relation"){let m=Object.entries(t.fields).filter(h=>h[1].type==="role");m.length>0&&(d=ta(m,e,n,r));}let c=Object.values(t.fields).filter(m=>m.type==="ref"),p=c.length>0?na(c,e,n):"",u=[];s&&u.push(`-- DATA FIELDS
19
19
  ${s}`),l?u.push(`-- LINK FIELDS
20
20
  ${l}`):s&&!d&&!p&&u.push("-- LINK FIELDS"),d&&u.push(`-- ROLES
21
21
  ${d}`),p&&u.push(`-- REF FIELDS
22
- ${p}`);let f=u.map(m=>Hs(m,n+1)).join(`
22
+ ${p}`);let f=u.map(m=>Ys(m,n+1)).join(`
23
23
  `);return `${i}
24
- ${f}`},Zs=(e,t,n)=>e.map(r=>{if(r.name==="id")return "";let i=Y(r.name),o=`${Ge(n)}DEFINE FIELD ${i} ON TABLE ${t}`;if(r.isVirtual){let a=r.dbValue?.surrealDB;return a?`${o} ${a};`:""}if(["FLEX","JSON"].includes(r.contentType))return `${o} TYPE any;`;let s=na(r.contentType,r.validations,r.cardinality);return `${o} TYPE ${s};`}).filter(Boolean).join(`
25
- `),Xs=(e,t,n,r)=>e.map(i=>{let o=be(i.name),s=`${Ge(n)}DEFINE FIELD ${o} ON TABLE ${t}`;if(i.isVirtual){let u=i.dbValue?.surrealDB;return u?`${s} ${u};`:""}let a=i.plays,l=i.target==="relation"?i.opposite.thing:i.relation,d=Gs(l,a,r),c=i.target==="role"?`.${Y(i.targetRole)}`:"",p;if(d.length===1){let u=`<~(${d[0]})${c}`;i.target==="relation"?p=i.cardinality==="ONE"?`array::first(${u} ?? [])`:u:i.cardinality==="ONE"?p=`array::first(${u} ?? [])`:i.targetRoleCardinality==="MANY"?p=`array::distinct(array::flatten(${u} ?? []))`:p=`array::distinct(${u})`;}else if(i.target==="relation"){let f=`array::concat(${d.map(m=>`<~(${m}) ?? []`).join(", ")})`;p=i.cardinality==="ONE"?`array::first(${f} ?? [])`:`array::distinct(${f})`;}else {let f=`array::flatten([${d.map(m=>`(<~(${m}) ?? [])${c}`).join(", ")}])`;i.cardinality==="ONE"?p=`array::first(${f} ?? [])`:i.targetRoleCardinality==="MANY"?p=`array::distinct(array::flatten(${f}))`:p=`array::distinct(${f})`;}return `${s} COMPUTED ${p};`}).join(`
26
- `),Gs=(e,t,n)=>{let r=n[e];return r?[e,...r.subTypes].map(o=>`${Y(o)} FIELD ${Y(t)}`):[`${Y(e)} FIELD ${Y(t)}`]},ea=(e,t,n,r)=>e.map(([,i])=>{let o=Y(i.name),s=i.opposite.thing,a=r[s],d=(a?[s,...a.subTypes]:[s]).map(Y).join("|"),c=i.cardinality==="MANY"?`array<record<${d}>>`:`record<${d}>`,p=i.onDelete??"UNSET";return `${Ge(n)}DEFINE FIELD ${o} ON TABLE ${t} TYPE option<${c}> REFERENCE ON DELETE ${p};`}).join(`
27
- `),ta=(e,t,n)=>e.map(r=>{let i=Y(r.name),o;return r.contentType==="REF"?o=r.cardinality==="MANY"?"option<array<record>>":"option<record>":o="any",`${Ge(n)}DEFINE FIELD ${i} ON TABLE ${t} TYPE ${o};`}).join(`
28
- `),na=(e,t,n)=>{let r=t?.enum?`${t.enum.map(o=>pt(o,e)).join("|")}`:wr[e];if(!r)throw new Error(`Unknown content type: ${e}`);let i=n==="MANY"?`array<${r}>`:r;return t?.required?i:`option<${i}>`},Mr=e=>Ys(e);var oa=e=>{let t=[],n=new Map;for(let r of e){let{dbPath:i,contentType:o}=r,s=`${i}-${o}`;n.has(s)||(n.set(s,true),t.push(r));}return t},sa=(e,t)=>{let n="",r=[];n+=`
24
+ ${f}`},Xs=(e,t,n)=>e.map(r=>{if(r.name==="id")return "";let i=Y(r.name),o=`${et(n)}DEFINE FIELD ${i} ON TABLE ${t}`;if(r.isVirtual){let a=r.dbValue?.surrealDB;return a?`${o} ${a};`:""}if(["FLEX","JSON"].includes(r.contentType))return `${o} TYPE any;`;let s=ra(r.contentType,r.validations,r.cardinality);return `${o} TYPE ${s};`}).filter(Boolean).join(`
25
+ `),Gs=(e,t,n,r)=>e.map(i=>{let o=be(i.name),s=`${et(n)}DEFINE FIELD ${o} ON TABLE ${t}`;if(i.isVirtual){let u=i.dbValue?.surrealDB;return u?`${s} ${u};`:""}let a=i.plays,l=i.target==="relation"?i.opposite.thing:i.relation,d=ea(l,a,r),c=i.target==="role"?`.${Y(i.targetRole)}`:"",p;if(d.length===1){let u=`<~(${d[0]})${c}`;i.target==="relation"?p=i.cardinality==="ONE"?`array::first(${u} ?? [])`:u:i.cardinality==="ONE"?p=`array::first(${u} ?? [])`:i.targetRoleCardinality==="MANY"?p=`array::distinct(array::flatten(${u} ?? []))`:p=`array::distinct(${u})`;}else if(i.target==="relation"){let f=`array::concat(${d.map(m=>`<~(${m}) ?? []`).join(", ")})`;p=i.cardinality==="ONE"?`array::first(${f} ?? [])`:`array::distinct(${f})`;}else {let f=`array::flatten([${d.map(m=>`(<~(${m}) ?? [])${c}`).join(", ")}])`;i.cardinality==="ONE"?p=`array::first(${f} ?? [])`:i.targetRoleCardinality==="MANY"?p=`array::distinct(array::flatten(${f}))`:p=`array::distinct(${f})`;}return `${s} COMPUTED ${p};`}).join(`
26
+ `),ea=(e,t,n)=>{let r=n[e];return r?[e,...r.subTypes].map(o=>`${Y(o)} FIELD ${Y(t)}`):[`${Y(e)} FIELD ${Y(t)}`]},ta=(e,t,n,r)=>e.map(([,i])=>{let o=Y(i.name),s=i.opposite.thing,a=r[s],d=(a?[s,...a.subTypes]:[s]).map(Y).join("|"),c=i.cardinality==="MANY"?`array<record<${d}>>`:`record<${d}>`,p=i.onDelete??"UNSET";return `${et(n)}DEFINE FIELD ${o} ON TABLE ${t} TYPE option<${c}> REFERENCE ON DELETE ${p};`}).join(`
27
+ `),na=(e,t,n)=>e.map(r=>{let i=Y(r.name),o;return r.contentType==="REF"?o=r.cardinality==="MANY"?"option<array<record>>":"option<record>":o="any",`${et(n)}DEFINE FIELD ${i} ON TABLE ${t} TYPE ${o};`}).join(`
28
+ `),ra=(e,t,n)=>{let r=t?.enum?`${t.enum.map(o=>pt(o,e)).join("|")}`:Sr[e];if(!r)throw new Error(`Unknown content type: ${e}`);let i=n==="MANY"?`array<${r}>`:r;return t?.required?i:`option<${i}>`},Ar=e=>Ks(e);var sa=e=>{let t=[],n=new Map;for(let r of e){let{dbPath:i,contentType:o}=r,s=`${i}-${o}`;n.has(s)||(n.set(s,true),t.push(r));}return t},aa=(e,t)=>{let n="",r=[];n+=`
29
29
  `;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:p}=l;if(n+=`${p} sub ${"extends"in l?l.extends:"entity"},
30
30
  `,d&&d.length>0)for(let u of d)u.contentType!=="REF"&&(u.inherited||(u.isIdField?n+=` owns ${u.dbPath} @key,
31
31
  `:n+=` owns ${u.dbPath},
@@ -41,7 +41,7 @@ ${f}`},Zs=(e,t,n)=>e.map(r=>{if(r.name==="id")return "";let i=Y(r.name),o=`${Ge(
41
41
  `),n+=`
42
42
  `;}let i=`define
43
43
 
44
- `,o=oa(r);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
44
+ `,o=sa(r);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
45
45
  `;else if(a.contentType==="EMAIL")i+=`${a.dbPath} sub attribute, value string,
46
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,})$';
47
47
  `;else if(a.contentType==="DATE")i+=`${a.dbPath} sub attribute, value datetime;
@@ -64,27 +64,28 @@ flexAttribute sub attribute, abstract, value string,
64
64
  owns doubleAttribute,
65
65
  owns booleanAttribute,
66
66
  owns datetimeAttribute;
67
- `},Ar=async(e,t,n,r)=>{if(!r.typeDB)throw new Error("No TypeDB handles found");let i=sa(e,n),o=r.typeDB.get(e)?.session,s=r.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 Lr=async(e,t,n,r)=>await(async()=>{let s=(await Promise.all([...r.typeDB||[]].map(async([d])=>[d,await Ar(d,e,t,r)]))).map(d=>[d[0],d[1]]),l=(await Promise.all([...r.surrealDB||[]].map(async([d])=>[d,Mr(n)]))).map(d=>[d[0],d[1]]);return {typeDB:Object.fromEntries(s),surrealDB:Object.fromEntries(l)}})();var Dr={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var Oe=Symbol.for("queryPath"),Pt=Symbol.for("stepPrint"),et=Symbol.for("edgeType"),Ne=Symbol.for("edgeSchema");var ft=Symbol.for("dbNode"),En=Symbol.for("isTransformed"),ht=Symbol.for("parent"),ze=Symbol.for("fieldSchema"),Z=Symbol.for("sharedMetadata"),wt=Symbol.for("flexDataValue"),tt=Symbol.for("suqlMetadata");var Nr=(e,t)=>{let n=kr(e.entities),r=kr(e.relations),i=la(e),o={entities:{},relations:{}};return n.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&&Fn(o,l.name,s);let d=Qr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i});o.entities[s]={...d,defaultDBConnector:a.defaultDBConnector,thingType:"entity"};}),r.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&&Fn(o,l.name,s);let d=Qr({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(([p,u])=>[p,Or({role:u,roleName:p,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in a&&l&&Object.entries(l?.roles??{}).forEach(([p,u])=>{let f=Or({role:u,roleName:p,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i});c.roles[p]={...f,inherited:true,[Z]:{...u[Z],inheritanceOrigin:u[Z]?.inheritanceOrigin||a.extends}};}),o.relations[s]=c;}),Object.values(o.entities).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Bn(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Bn(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Bn(o,a.$things);});}),o},kr=e=>{let t=[],n=new Set,r=new Set;for(let i of Object.keys(e))Ir({thingMap:e,name:i,inProcess:r,seen:n,ordered:t});return t},Ir=e=>{let{thingMap:t,name:n,inProcess:r,seen:i,ordered:o}=e;if(i.has(n))return;if(r.has(n))throw new Error(`A list of thing extends each other that creates circular dependencies: ${[...r]}`);r.add(n);let s=t[n];if(!s)throw new Error(`Entity/relation "${n}" does not exist`);"extends"in s&&Ir({...e,name:s.extends}),r.delete(n),i.add(n),o.push(n);},aa=(e,t)=>{let n=t,r=[];for(;n;){let i=e.entities[n]||e.relations[n];if(!i)throw new Error(`Entity/relation "${n}" does not exist`);r.push(n),n="extends"in i?i.extends:void 0;}return r.length!==0?r:void 0},Fn=(e,t,n)=>{let r=e.entities[t]??e.relations[t];if(!r)throw new Error(`Entity/relation "${t}" does not exist`);r.subTypes=r.subTypes??[],r.subTypes.push(n),r.extends&&Fn(e,r.extends,n);},Qr=e=>{let{schema:t,enrichedSchema:n,name:r,thing:i,dbHandles:o,extendedThing:s,allLinkFields:a}=e,[l]=Object.entries(o).find(([m,h])=>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(`"${r}" does not have an id field`);let c={...i.hooks},p=i.dataFields?.map(m=>ca(m,r,d))??[],u=i.linkFields?.map(m=>ua({linkField:m,thingName:r,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([m,h])=>[m,da(h,m)]));return "extends"in i&&s&&(s.hooks?.pre&&(c.pre=[...s.hooks.pre||[],...i.hooks?.pre||[]]),s.dataFields?.forEach(m=>{p.push({...m,inherited:true,[Z]:{...m[Z],inheritanceOrigin:m[Z]?.inheritanceOrigin||i.extends}});}),s.linkFields?.forEach(m=>{u.push({...m,inherited:true,[Z]:{...m[Z],inheritanceOrigin:m[Z]?.inheritanceOrigin||i.extends}});}),Object.entries(s.refFields??{}).forEach(([m,h])=>{f[m]={...h,inherited:true,[Z]:{...h[Z],inheritanceOrigin:h[Z]?.inheritanceOrigin||i.extends}};})),{...i,name:r,db:l,dbContext:Dr[l],idFields:d,hooks:c,dataFields:p,linkFields:u,refFields:f,enumFields:p?.filter(m=>m.validations?.enum).map(m=>m.path)??[],fnValidatedFields:p?.filter(m=>m.validations?.fn).map(m=>m.path)??[],virtualFields:p?.filter(m=>m.isVirtual).map(m=>m.path)??[],computedFields:p?.filter(m=>m.default&&!m.isVirtual).map(m=>m.path)??[],requiredFields:p?.filter(m=>m.validations?.required).map(m=>m.path)??[],allExtends:"extends"in i?aa(n,i.extends):void 0}},la=e=>{let t=[];return Object.entries(e.entities).forEach(([n,r])=>{r.linkFields?.forEach(i=>{t.push({...i,thing:n,thingType:"entity",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),Object.entries(e.relations).forEach(([n,r])=>{r.linkFields?.forEach(i=>{t.push({...i,thing:n,thingType:"relation",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),t},ca=(e,t,n)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:pa(t,e.path,e.shared),isIdField:!!n?.includes(e.path),inherited:false,[Z]:{fieldType:"dataField"},[tt]:{dbPath:e.path}}),da=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[Z]:{fieldType:"refField"}}),ua=e=>{let{linkField:t,thing:n,thingName:r,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(!Cr(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: "${r}" LinkField: "${t.path}."`);return {...t,$things:[t.relation],oppositeLinkFieldsPlayedBy:[{plays:t.path,thing:t.relation,thingType:"relation"}],fieldType:"linkField",inherited:false,[Z]:{fieldType:"linkField"},[tt]:{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: "${r}" LinkField: "${t.path}."`);return l.length>1&&console.warn(`[Schema] LinkField ${t.path} in ${r} 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:n.linkFields?.find(d=>d.target==="relation"&&d.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(d=>d.thing),oppositeLinkFieldsPlayedBy:l,[Z]:{fieldType:"linkField"},[tt]:{queryPath:a}}},Or=e=>{let{role:t,roleName:n,relationName:r,relation:i,allExtends:o,allLinkFields:s}=e;if(i.dataFields?.find(d=>d.path===n)||i.linkFields?.find(d=>d.path===n))throw new Error(`[Schema] The path ${n} is already in use by a dataField or linkField in ${r}.`);let a=s.filter(d=>d.relation===r&&d.plays===n),l=s.filter(d=>d.target==="relation"&&d.plays===n&&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===n&&c.plays===n)?.path??d.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:n,$things:[...new Set(a.map(d=>d.thing))],[Z]:{fieldType:"roleField"},[tt]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${n}\`]`:`$parent.\`${n}\``}}},pa=(e,t,n)=>n?t:`${e}\xB7${t}`,Cr=(e,t,n)=>{let r=e.relations[t];if(!r)throw new Error(`Relation "${t}" does not exist`);return r.roles?.[n]?true:"extends"in r?Cr(e,r.extends,n):false},Bn=(e,t)=>t.flatMap(n=>[n,...(e.entities[n]??e.relations[n])?.subTypes??[]]);var Pr=e=>{let t=ba(e),n={},r=Ea(t);for(let i in t.entities)bn("entity",i,n,t,r);for(let i in t.relations)bn("relation",i,n,t,r);return n},bn=(e,t,n,r,i)=>{let o=n[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"?r.entities[t]:r.relations[t];if(!s)throw new Error(`${e==="entity"?"Entity":"Relation"} "${t}" not found`);let a="extends"in s&&s.extends?bn(e,s.extends,n,r,i):void 0;a&&ha(a.name,t,n);let l={},d=a?a.idFields:Fa(t,s);ma(l,s.dataFields??[],t),$a(l,s.refFields??{},t),ya(l,s.linkFields??[],t,r,i);let c=s.hooks;if(e==="entity"){_r(t,l);let u={type:"entity",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],hooks:c,fields:l};return n[t]=u,u}"roles"in s&&s.roles&&ga(l,s.roles??{},t,i),_r(t,l);let p={type:"relation",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],hooks:c,fields:l};return n[t]=p,p},ha=(e,t,n)=>{let r=e;for(;r;){let i=n[r];if(!i)throw new Error(`Thing "${r}" not found`);i.subTypes.push(t),r=i.extends;}},ma=(e,t,n)=>{for(let r of t??[]){let i=e[r.path];if(r.isVirtual){if(r.default?.type==="fn"&&typeof r.default.fn=="function"){let s={type:"computed",name:r.path,contentType:r.contentType,cardinality:r.cardinality??"ONE",fn:r.default.fn};nt(n,s,i),e[r.path]=s;continue}if(r.default?.type==="value"){let s={type:"constant",name:r.path,contentType:r.contentType,cardinality:r.cardinality??"ONE",value:r.default.value};nt(n,s,i),e[r.path]=s;continue}}let o={type:"data",name:r.path,contentType:r.contentType,cardinality:r.cardinality??"ONE",unique:r.validations?.unique??false,default:r.default,validations:r.validations,isVirtual:r.isVirtual,dbValue:r.dbValue};nt(n,o,i),e[r.path]=o;}},$a=(e,t,n)=>{for(let[r,i]of Object.entries(t??{})){let o=e[r],s={type:"ref",name:r,contentType:i.contentType,cardinality:i.cardinality??"ONE"};nt(n,s,o),e[r]=s;}},ya=(e,t,n,r,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 "${n}": only alphanumeric characters, underscores, dashes, and spaces are allowed`);let s=r.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 m={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};nt(n,m,l),e[o.path]=m;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 p=s.roles?.[o.targetRole];if(!p)throw new Error(`Target role ${o.targetRole} not found in relation ${o.relation}`);let u=p.cardinality;if(o.cardinality==="ONE"&&u==="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:u,opposite:c,isVirtual:o.isVirtual,dbValue:o.dbValue};nt(n,f,l),e[o.path]=f;}},ga=(e,t,n,r)=>{for(let[i,o]of Object.entries(t)){let s=r[n]?.[i]?.targetingRelation??r[n]?.[i]?.targetingRole;if(!s)throw new Error(`Role ${i} in relation ${n} 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};nt(n,l,a),e[i]=l;}},nt=(e,t,n)=>{if(n&&!isEqual(t,n))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},_r=(e,t)=>{let n=new Map,r=(i,o,s)=>{let a=n.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}"`);n.set(i,{originalName:o,fieldType:s});};for(let i of Object.values(t))if(i.type==="link"){r(i.name,i.name,i.type);let o=be(i.name);o!==i.name&&r(o,i.name,i.type);}else r(i.name,i.name,i.type);},Ea=e=>{let t={};for(let[n,r]of [...Object.entries(e.relations),...Object.entries(e.entities)])for(let i of r.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===n||jr(n,a.thing,e))continue;if(!jr(a.thing,n,e))throw new Error(`Found multiple players for role ${i.plays} in relation ${i.relation}`)}i.target==="relation"?s.targetingRelation={thing:n,path:i.path,cardinality:i.cardinality}:s.targetingRole={thing:n,path:i.path,cardinality:i.cardinality};}return t},jr=(e,t,n)=>Ba(e,n).includes(t),Ba=(e,t)=>{let n=[],r=e;for(;r;){let i=t.entities[r]??t.relations[r];if(!i)throw new Error(`Thing "${r}" not found`);if(!("extends"in i)||!i.extends)break;n.push(i.extends),r=i.extends;}return n.reverse()},Fa=(e,t)=>{if(t.idFields&&t.idFields.length>0)return [t.idFields[0],...t.idFields.slice(1)];let n=t.dataFields?.find(r=>r.contentType==="ID");if(n)return [n.path];throw new Error(`No id field found for entity "${e}"`)},ba=e=>{let t={entities:{},relations:{}};for(let n in e.entities)qr(n,e,t);for(let n in e.relations)xr(n,e,t);return t},qr=(e,t,n)=>{let r=t.entities[e];if(!r)throw new Error(`Entity "${e}" not found`);if("extends"in r&&r.extends){let i=qr(r.extends,t,n),o={...r,idFields:r.idFields??i.idFields,dataFields:Vr(i,r),linkFields:zr(i,r),refFields:Wr(i,r),hooks:Ur(i.hooks,r.hooks)};return n.entities[e]=o,o}return n.entities[e]=r,r},xr=(e,t,n)=>{let r=t.relations[e];if(!r)throw new Error(`Relation "${e}" not found`);if("extends"in r&&r.extends){let i=xr(r.extends,t,n),o={...r,idFields:r.idFields??i.idFields,dataFields:Vr(i,r),linkFields:zr(i,r),refFields:Wr(i,r),roles:Ra(i,r),hooks:Ur(i.hooks,r.hooks)};return n.relations[e]=o,o}return n.relations[e]=r,r},Vr=(e,t)=>{let n=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!n.has(i.path))??[],...t.dataFields??[]]},zr=(e,t)=>{let n=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!n.has(i.path))??[],...t.linkFields??[]]},Wr=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([r])=>!t.refFields?.[r])),...t.refFields??{}}),Ra=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([r])=>!t.roles?.[r])),...t.roles??{}}),Ur=(e,t)=>{if(!(!e&&!t))return e?t?{pre:[...e.pre??[],...t.pre??[]]}:e:t};var pe=z$1.json(),we=z$1.array(pe),vr=z$1.strictObject({$exists:z$1.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:we.optional(),$nin:we.optional(),$containsAll:we.optional(),$containsAny:we.optional(),$containsNone:we.optional()}),Me=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>Me)).optional(),$not:z$1.lazy(()=>Me).optional()}).catchall(z$1.union([pe,we,z$1.lazy(()=>z$1.union([rt,z$1.array(rt)]))]))),rt=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>Me)).optional(),$not:z$1.lazy(()=>Me).optional(),$exists:z$1.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:we.optional(),$nin:we.optional(),$containsAll:we.optional(),$containsAny:we.optional(),$containsNone:we.optional()}).catchall(z$1.union([pe,we,z$1.lazy(()=>z$1.union([rt,z$1.array(rt)]))]))),Hr=z$1.object({$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([Me,z$1.array(Me)]).optional(),$fields:z$1.array(z$1.union([z$1.string(),z$1.lazy(()=>Ta)])).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()}),Ta=Hr.extend({$path:z$1.string(),$as:z$1.string().optional()}),Yr=Hr.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:n,$relation:r,...i}=e;return {...i,$thing:t??n??r}});var Kr=(e,t,n)=>{let r=t[e.$thing],i=Jr({fields:e.$fields,thing:r,schema:t,metadata:n}),o=e.$filter?Pe(e.$filter,r,t):void 0,s=Array.isArray(e.$id)?e.$id:e.$id?[e.$id]:[],a=s.length===1||Tn(r,o)?"ONE":"MANY";return {source:s.length>0?{type:"record_pointer",thing:[r.name,...r.subTypes],ids:s}:{type:"table_scan",thing:[r.name,...r.subTypes]},projection:i,filter:o,limit:ei(e.$limit),offset:ti(e.$offset),sort:ni(i,Xr(e.$sort)),cardinality:a}},Jr=e=>{let{fields:t,thing:n,schema:r,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(n.fields)){let a=Rn(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 p=n.fields[s];if(!p)throw new Error(`Field ${s} not found in ${n.name}`);let u=Rn(p);u&&o.push(u);continue}if(s.$path==="$id"||s.$path==="$thing"){o.push({type:"metadata",path:s.$path,alias:s.$as});continue}let a=n.fields[s.$path];if(!a)throw new Error(`Field ${s} not found in ${n.name}`);if(a.type==="constant"||a.type==="computed")continue;if(a.type==="data"||a.type==="ref"){let p=Rn(a,s.$as);p&&o.push(p);continue}let l=r[a.opposite.thing],d=Jr({fields:s.$fields,thing:l,schema:r,metadata:i}),c="$filter"in s&&s.$filter?Pe(s.$filter,l,r):void 0;o.push({type:a.type==="role"?"nested_ref":"nested_computed_ref",path:s.$path,projection:d,resultCardinality:typeof s.$id=="string"||Tn(l,c)?"ONE":a.cardinality,fieldCardinality:a.cardinality,alias:s.$as,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:c,limit:ei(s.$limit),offset:ti(s.$offset),sort:ni(d,Xr(s.$sort))});}return {fields:o}},Rn=(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}},Pe=(e,t,n)=>Array.isArray(e)?{type:"or",filters:e.map(o=>Pe(o,t,n)).filter(o=>!!o)}:{type:"and",filters:wa(e,t,n)},wa=(e,t,n)=>Object.entries(e).map(([r,i])=>{if(r==="$not"&&e.$not)return Sa(e.$not,t,n);if(r==="$or"&&e.$or)return Ma(e.$or,t,n);let o=t.fields[r];if(!o)throw new Error(`Field ${r} not found in ${t.name}`);if(o.type==="constant"||o.type==="computed")throw new Error(`Filtering on constant or computed field ${r} is not supported`);if(i!==void 0)return o.type==="data"?Aa(o,i):o.type==="ref"?La(o,i):Zr(o,i,n)}).filter(r=>r!==void 0),Sa=(e,t,n)=>{let r=Pe(e,t,n);return r?{type:"not",filter:r}:void 0},Ma=(e,t,n)=>Pe(e,t,n),Aa=(e,t)=>{let n=vr.safeParse(t);if(n.success){let r=[];for(let[i,o]of Object.entries(n.data)){if(i==="$exists"){r.push({type:"null",op:o?"IS NOT":"IS",left:e.name,emptyIsArray:false});continue}if((i==="$eq"||i==="$ne")&&o===null){r.push({type:"null",op:i==="$eq"?"IS":"IS NOT",left:e.name,emptyIsArray:false});continue}let s=Da[i];if(s){r.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=Gr[i];if(a){r.push({type:"list",op:a,left:e.name,right:o});continue}throw new Error(`Invalid filter operation: ${i}`)}return {type:"and",filters:r}}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}},La=(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(xt.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(xt.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")},Zr=(e,t,n)=>{let r=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:r};if(typeof t=="string")return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],cardinality:s,oppositeCardinality:a};if(xt.safeParse(t).success)return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,cardinality:s,oppositeCardinality:a};let l=qt.union([rt,qt.array(rt)]).safeParse(t);if(l.error)throw new Error(`Invalid nested filter: ${l.error.message}`);let d=n[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(D=>Zr(e,D,n))};let{$eq:p,$ne:u,$contains:f,$containsNot:m,$in:h,$nin:y,$containsAll:$,$containsAny:g,$containsNone:B,...E}=l.data;for(let R of ["$gt","$lt","$gte","$lte"])if(E[R])throw new Error(`Filtering ${e.type} field with ${R} operator is not supported`);let T=[];for(let R of ["$exists","$eq","$ne","$contains","$containsNot"]){let D=l.data[R];if(D!==void 0){if(R==="$exists"){T.push({type:"null",op:D?"IS NOT":"IS",left:e.name,emptyIsArray:r});continue}if((R==="$eq"||R==="$ne")&&D===null){T.push({type:"null",op:R==="$eq"?"IS":"IS NOT",left:e.name,emptyIsArray:r});continue}if(typeof D!="string")throw new Error(`Filter value for ${e.type} field with operator ${R} must be a string`);T.push({type:i,op:R==="$eq"||R==="$contains"?"IN":"NOT IN",left:e.name,right:[D],thing:c,cardinality:s,oppositeCardinality:a});}}for(let R of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let D=l.data[R];if(D===void 0)continue;let I=xt.safeParse(D);if(!I.success)throw new Error(`Filter value for ${e.type} field with operator ${R} must be a string array`);let q=Gr[R];if(!q)throw new Error(`Invalid list operator: ${R}`);T.push({type:i,op:q,left:e.name,right:I.data,thing:c,cardinality:s,oppositeCardinality:a});}let A=n[e.opposite.thing];if(!A)throw new Error(`Unknown thing: ${e.opposite.thing}`);let k=Pe(E,A,n);return k&&T.push({type:o,path:e.name,filter:k,cardinality:s,oppositeCardinality:a}),{type:"and",filters:T}},Tn=(e,t)=>{if(!t)return false;if(t.type==="scalar"){if(t.op!=="=")return false;let n=e.fields[t.left];if(!n)throw new Error(`Field ${t.left} not found in ${e.name}`);return n.type==="data"&&n.unique}if(t.type==="list"){if(t.op!=="IN"||t.right.length>1)return false;let n=e.fields[t.left];if(!n)throw new Error(`Field ${t.left} not found in ${e.name}`);return n.type==="data"&&n.unique}return t.type==="and"?t.filters.some(n=>Tn(e,n)):false},Xr=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},Da={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},Gr={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},xt=qt.array(qt.string()),ei=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},ti=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},ni=(e,t)=>{if(!t||t.length===0)return;let n=new Set(e.fields.map(r=>r.type==="metadata"?r.path:r.alias??r.path));for(let r of t)if(!n.has(r.field))throw new Error(`Missing sorter field in the selected fields: ${r.field}`);return t};var li=(e,t)=>{let n={schema:t,mutation:{matches:[],subMatches:[],creates:[],updates:[],deletes:[]},nameCounters:{},tempIdMap:new Map},r=Array.isArray(e)?e:[e];for(let i of r)An(i,n);for(let i of r)Oa(i,null,null,n);return va(n.mutation),n.mutation},Qa=e=>e.replace(/[\s-]/g,"_").replace(/[^a-zA-Z0-9_]/g,""),Fe=(e,t)=>{let n=Qa(e),r=t.nameCounters[n]??0;return t.nameCounters[n]=r+1,`${n}_${r}`},On=customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",16),An=(e,t)=>{if(e.$tempId){let n=e.$tempId.replace(/^_:/,"");if(e.$op==="create"){if(t.tempIdMap.has(e.$tempId))throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${n}". Existing: create. Current: create`);if(e.$thing&&t.schema[e.$thing]){let r=t.schema[e.$thing],i=mt(r),o=e.$id??e[i]??On();t.tempIdMap.set(e.$tempId,{thing:r.name,id:o}),e[i]===void 0&&e.$id===void 0&&(e[i]=o);}}}for(let[n,r]of Object.entries(e))if(!n.startsWith("$")&&r!=null)if(Array.isArray(r))for(let i of r)ai(i)&&An(i,t);else ai(r)&&An(r,t);},Oa=(e,t,n,r)=>{let i=e.$op,o=Nn(e,r);switch(i){case "create":ot(e,o,t,n,r);break;case "update":Wt(e,o,t,n,r);break;case "delete":St(e,o,t,n,r);break;}},ot=(e,t,n,r,i)=>{let o=mt(t),s=e.$tempId?i.tempIdMap.get(e.$tempId):void 0,a=s?s.id:e.$id??e[o]??On();e.$tempId&&!i.tempIdMap.has(e.$tempId)&&i.tempIdMap.set(e.$tempId,{thing:t.name,id:a}),Xa(e,t);let l=Fe(t.name,i),d={name:l,thing:t.name,id:a,tempId:e.$tempId,op:"create",values:{}};i.mutation.creates.push(d);for(let[c,p]of Object.entries(e)){if(c.startsWith("$")||c===o||p===void 0)continue;let u=di(c,p,t,e,l,i);u&&(d.values[c]=u);}return l},Wt=(e,t,n,r,i,o,s)=>{let a=mt(t);Za(a,t.name,e);let l=ci(e,t,n,r,i,o,s),d={},c=false;for(let[p,u]of Object.entries(e)){if(p.startsWith("$")||u===void 0)continue;let f=di(p,u,t,e,l,i);f&&(d[p]=f,c=true);}if(c){let p={name:Fe(t.name,i),match:l,op:"update",values:d};i.mutation.updates.push(p);}},St=(e,t,n,r,i,o,s)=>{let a=ci(e,t,n,r,i,o,s);for(let[d,c]of Object.entries(e)){if(d.startsWith("$")||c==null)continue;let p=t.fields[d];if(p)if(p.type==="role"){let u=Array.isArray(c)?c:[c];for(let f of u)if(Be(f)){let m=f,h=m.$thing?i.schema[m.$thing]:i.schema[p.opposite.thing];h&&(m.$thing||(m.$thing=h.name),m.$op==="delete"&&St(m,h,a,d,i,p.cardinality));}}else p.type==="link"&&kn(d,c,p,t,e,a,i);}let l={name:Fe(t.name,i),match:a,op:"delete"};i.mutation.deletes.push(l);},ci=(e,t,n,r,i,o,s)=>{let a=mt(t),{ids:l,remainingFilter:d}=Na(e.$filter,a),p=[...e.$id?Array.isArray(e.$id)?e.$id:[e.$id]:[],...l];if(n&&r){let h=Fe(t.name,i),y={name:h,parent:n,path:r,cardinality:o??"MANY",isComputed:s,ids:p.length>0?p:void 0,filter:d?Pe(d,t,i.schema):void 0};return i.mutation.subMatches.push(y),h}let u=Fe(t.name,i),f=[t.name,...t.subTypes],m=d?Pe(d,t,i.schema):void 0;if(p.length>0){let h={name:u,source:{type:"record_pointer",thing:f,ids:p},filter:m};i.mutation.matches.push(h);}else if(m){let h={name:u,source:{type:"table_scan",thing:f},filter:m};i.mutation.matches.push(h);}else {let h={name:u,source:{type:"table_scan",thing:f}};i.mutation.matches.push(h);}return u},Na=(e,t)=>{if(!e||Array.isArray(e))return {ids:[],remainingFilter:e};let n=e[t];if(n===void 0)return {ids:[],remainingFilter:e};let r={...e};delete r[t];let o=Object.keys(r).filter(s=>!s.startsWith("$")).length>0||r.$not!==void 0||r.$or!==void 0?r:void 0;return typeof n=="string"?{ids:[n],remainingFilter:o}:Array.isArray(n)&&n.every(s=>typeof s=="string")?{ids:n,remainingFilter:o}:{ids:[],remainingFilter:e}},di=(e,t,n,r,i,o)=>{if(e.startsWith("%"))return;let s=n.fields[e];if(!s)throw new Error(`Unknown field '${e}' on '${n.name}'`);if(s.type==="constant")throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(s.type==="computed")throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(s.type==="data"&&s.isVirtual)throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(s.type==="link"&&s.isVirtual)throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(t===null){if(s.type==="link"){kn(e,[{$op:"unlink"}],s,n,r,i,o);return}return (s.type==="role"||s.type==="ref")&&s.cardinality==="MANY"?{type:"empty",path:e}:{type:"null",path:e}}switch(s.type){case "data":return Ia(e,t,s);case "ref":return Ca(e,t,s,r,i,o);case "role":return ja(e,t,s,r,i,o);case "link":kn(e,t,s,n,r,i,o);return;default:throw new Error(`Unsupported field type for '${e}' on '${n.name}'`)}},Ia=(e,t,n)=>{let r=n.contentType==="JSON"?Ln(t):t;return n.cardinality==="MANY"?{type:"data_field",cardinality:"MANY",path:e,value:Array.isArray(r)?r:[r]}:{type:"data_field",cardinality:"ONE",path:e,value:r}},Ln=e=>{if(e==null)return e;if(Array.isArray(e))return e.map(Ln);if(Be(e)){let t=e;if(Object.keys(t).length===1&&typeof t.$ref=="string"){let i=at(t.$ref);if(i)return new RecordId(i.thing,i.id)}let r={};for(let[i,o]of Object.entries(t))r[i]=Ln(o);return r}return e},Ca=(e,t,n,r,i,o)=>{if(n.contentType==="FLEX")return _a(e,t,n,o,i);if(n.cardinality==="ONE"){if(Be(t)&&t.$op==="create"){let u=t;if(!u.$thing)throw new Error(`Nested create in ref field '${e}' must have $thing`);let f=o.schema[u.$thing];if(!f)throw new Error(`Thing '${u.$thing}' not found in schema`);let m=ot(u,f,i,null,o),h=o.mutation.creates.find(y=>y.name===m);return {type:"ref_field",cardinality:"ONE",path:e,value:`${h.thing}:${h.id}`}}if(Be(t)&&t.$op==="link"){let u=wn(t,o);if(!u)return;let f=Array.isArray(u)?u[0]:u;return {type:"ref_field",cardinality:"ONE",path:e,value:`${f.thing}:${f.id}`}}let p=ri(t,r,i,o);return p?{type:"ref_field",cardinality:"ONE",path:e,value:`${p.thing}:${p.id}`}:void 0}let s=Array.isArray(t)?t:[t],a=[],l=[],d=[],c=false;for(let p of s)if(Be(p)&&p.$op==="create"){let u=p;if(!u.$thing)throw new Error(`Nested create in ref field '${e}' must have $thing`);let f=o.schema[u.$thing];if(!f)throw new Error(`Thing '${u.$thing}' not found in schema`);let m=ot(u,f,i,null,o),h=o.mutation.creates.find(y=>y.name===m);a.push(`${h.thing}:${h.id}`),c=true;}else if(Be(p)&&p.$op==="link"){let f=wn(p,o);f&&(Array.isArray(f)?l.push(...f):l.push(f));}else if(Be(p)&&p.$op==="unlink"){let f=wn(p,o);f&&(Array.isArray(f)?d.push(...f):d.push(f));}else {let u=ri(p,r,i,o);u&&a.push(`${u.thing}:${u.id}`);}if(l.length>0||d.length>0||c){let p=[...a,...l.map(u=>`${u.thing}:${u.id}`)];return {type:"ref_field",cardinality:"MANY",path:e,value:p}}return {type:"ref_field",cardinality:"MANY",path:e,value:a}},ri=(e,t,n,r)=>{if(typeof e=="string"){let i=at(e);if(i)return i;if(e.startsWith("_:")){let o=e,s=r.tempIdMap.get(o);if(!s)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${o.replace(/^_:/,"")}`);return s}throw new Error(`Invalid ref value: ${e}. Expected 'Type:id' format.`)}if(Be(e)){let i=e;if(i.$thing&&i.$id)return {thing:i.$thing,id:i.$id};if(i.$tempId){let o=r.tempIdMap.get(i.$tempId);if(!o)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(i.$tempId).replace(/^_:/,"")}`);return o}}},wn=(e,t)=>{if(e.$id){let n=Array.isArray(e.$id)?e.$id:[e.$id];if(e.$thing){let r=n.map(i=>({thing:e.$thing,id:i}));return r.length===1?r[0]:r}}if(e.$tempId){let n=t.tempIdMap.get(e.$tempId);if(!n)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(e.$tempId).replace(/^_:/,"")}`);return n}},_a=(e,t,n,r,i)=>{if(n.cardinality==="ONE")return {type:"flex_field",cardinality:"ONE",path:e,value:ii(t,r,i)};let o=Array.isArray(t)?t:[t];return {type:"flex_field",cardinality:"MANY",path:e,value:o.map(s=>ii(s,r,i))}},ii=(e,t,n)=>{if(Be(e)){let r=e;if(r.$op==="create"&&r.$thing){let i=t.schema[r.$thing];if(!i)throw new Error(`Thing '${r.$thing}' not found in schema`);let o=ot(r,i,n??null,null,t),s=t.mutation.creates.find(a=>a.name===o);return new RecordId(s.thing,s.id)}}return Dn(e,t)},Dn=(e,t)=>{if(e==null)return null;if(typeof e=="string"){let n=/^([^:]+):(_:.+)$/.exec(e);if(n){let[,i,o]=n,s=t.tempIdMap.get(o);if(s)return new RecordId(i,s.id)}let r=at(e);return r&&t.schema[r.thing]?new RecordId(r.thing,r.id):e}if(typeof e=="number"||typeof e=="boolean"||e instanceof Date||e instanceof RecordId)return e;if(Be(e)){let n=e;if(n.$op&&n.$op!=="link"&&n.$op!=="create")throw new Error(`Flex fields do not support '$op: ${n.$op}' operations. Use link operations instead.`);let r=Object.keys(n);if(r.length===2&&n.$thing&&n.$id||r.length===3&&n.$thing&&n.$id&&n.$op==="link")return new RecordId(n.$thing,n.$id);if(r.length===1&&n.$ref&&typeof n.$ref=="string"){let o=at(n.$ref);if(o)return new RecordId(o.thing,o.id)}let i={};for(let[o,s]of Object.entries(n))i[o]=Dn(s,t);return i}return Array.isArray(e)?e.map(n=>Dn(n,t)):e},ja=(e,t,n,r,i,o)=>{if(n.cardinality==="ONE"&&r.$op==="update"&&Be(t)&&!Array.isArray(t)&&!t.$op&&!t.$id&&!t.$tempId&&zt(t))throw new Error(`Please specify if it is a create or an update. Path: $root.0.${e}`);let s=o.schema[n.opposite.thing],a=s?.subTypes?.length?s.subTypes:void 0;if(typeof t=="string"){let m=Mn(t,n,a,o);return n.cardinality==="ONE"?{type:"role_field",cardinality:"ONE",path:e,ref:m}:{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:[m]}}if(Array.isArray(t)&&t.length>0&&t.every(m=>typeof m=="string")){let m=t.map(h=>Mn(h,n,a,o));return {type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:m}}let l=Array.isArray(t)?t:[t],d=[],c=[],p=[],u=false,f=false;for(let m of l){if(!Be(m)){d.push(Mn(m,n,a,o));continue}let h=m,y=h.$op;if(y==="create"||!y&&zt(h)){let $=h.$thing?o.schema[h.$thing]:o.schema[n.opposite.thing];if(!$)throw new Error(`Thing '${n.opposite.thing}' not found in schema`);h.$thing||(h.$thing=$.name),h.$op||(h.$op="create");let g=ot(h,$,i,null,o),B=o.mutation.creates.find(E=>E.name===g);d.push({thing:B.thing,id:B.id});}else if(y==="link"){if(u=true,h.$id){let $=Array.isArray(h.$id)?h.$id:[h.$id];for(let g of $)c.push(Sn(g,h,n,o));}else if(h.$tempId){let $=o.tempIdMap.get(h.$tempId);if(!$)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(h.$tempId).replace(/^_:/,"")}`);c.push($);}}else if(y==="unlink")if(u=true,h.$id){let $=Array.isArray(h.$id)?h.$id:[h.$id];for(let g of $)p.push(Sn(g,h,n,o));}else f=true;else if(y==="update"){let $=h.$thing?o.schema[h.$thing]:o.schema[n.opposite.thing];if(!$)throw new Error(`Thing '${n.opposite.thing}' not found`);h.$thing||(h.$thing=$.name),Wt(h,$,i,e,o,n.cardinality);}else if(y==="delete"){let $=h.$thing?o.schema[h.$thing]:o.schema[n.opposite.thing];if(!$)throw new Error(`Thing '${n.opposite.thing}' not found`);h.$thing||(h.$thing=$.name),St(h,$,i,e,o,n.cardinality);}else if(!y&&!zt(h)){if(h.$tempId){let $=o.tempIdMap.get(h.$tempId);if(!$)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(h.$tempId).replace(/^_:/,"")}`);d.push($);}else if(h.$id){let $=Array.isArray(h.$id)?h.$id:[h.$id];for(let g of $)d.push(Sn(g,h,n,o));}}}if(n.cardinality==="ONE")return d.length>0?{type:"role_field",cardinality:"ONE",path:e,ref:d[0]}:c.length>0?{type:"role_field",cardinality:"ONE",path:e,ref:c[0]}:void 0;if(u)return f&&c.length>0?{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:c}:f?{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:[]}:{type:"role_field",cardinality:"MANY",op:"patch",path:e,links:[...c],unlinks:[...p]};if(d.length>0)return r.$op==="update"?{type:"role_field",cardinality:"MANY",op:"patch",path:e,links:d,unlinks:[]}:{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:d}},Sn=(e,t,n,r)=>{let i=t.$thing??n.opposite.thing,o=r.schema[i],s=o?.subTypes?.length?o.subTypes:void 0;if(e.startsWith("_:")){let a=r.tempIdMap.get(e);if(!a)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${e.replace(/^_:/,"")}`);return a}return {thing:i,subTypes:s,id:e}},Mn=(e,t,n,r)=>{if(e.startsWith("_:")){let i=r.tempIdMap.get(e);if(!i)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${e.replace(/^_:/,"")}`);return i}return {thing:t.opposite.thing,subTypes:n,id:e}},kn=(e,t,n,r,i,o,s)=>{n.target==="relation"?Pa(e,t,n,r,i,o,s):qa(e,t,n,r,i,o,s);},Pa=(e,t,n,r,i,o,s)=>{if(!s.schema[n.relation])throw new Error(`Relation '${n.relation}' not found`);let l=Nn(i,s),d=mt(l),c=fi(i,d,s),p=i.$id&&Array.isArray(i.$id)?i.$id:[c],u=Array.isArray(t)?t:[t];for(let f of u){if(typeof f=="string"){let y=at(f);oi(n,c,l.name,y?.id??f,s);continue}if(!Be(f))continue;let m=f,h=m.$op;if(h==="link"){let y=m.$id?Array.isArray(m.$id)?m.$id:[m.$id]:[];if(m.$tempId){let $=s.tempIdMap.get(m.$tempId);if(!$)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(m.$tempId).replace(/^_:/,"")}`);y.push($.id);}for(let $ of y)for(let g of p)oi(n,g,l.name,$,s);}else if(h==="unlink")if(m.$id){let y=Array.isArray(m.$id)?m.$id:[m.$id];for(let $ of y)for(let g of p)xa(n,g,l.name,$,s);}else Va(n,c,l.name,o,s);else if(h==="update"){m.$thing||(m.$thing=n.relation);let y=s.schema[m.$thing];if(!y)throw new Error(`Thing '${m.$thing}' not found`);Wt(m,y,o,e,s,n.cardinality,true);}else if(h==="delete"){m.$thing||(m.$thing=n.relation);let y=s.schema[m.$thing];if(!y)throw new Error(`Thing '${m.$thing}' not found`);St(m,y,o,e,s,n.cardinality,true);}else {m.$thing||(m.$thing=n.relation),m.$op=m.$op??"create";let y=s.schema[m.$thing];if(!y)throw new Error(`Thing '${m.$thing}' not found`);{let $=s.schema[n.relation],g=$?.type==="relation"?$.fields[n.plays]:void 0;if(g?.type==="role"&&g.cardinality==="ONE")m[n.plays]=c;else if(m[n.plays]===void 0)m[n.plays]=[c];else {let B=Array.isArray(m[n.plays])?m[n.plays]:[m[n.plays]];B.push(c),m[n.plays]=B;}}ot(m,y,o,null,s);}}},qa=(e,t,n,r,i,o,s)=>{if(n.cardinality==="ONE"&&i.$op==="update"&&Be(t)&&!Array.isArray(t)&&!t.$op&&!t.$id&&!t.$tempId&&zt(t))throw new Error(`Please specify if it is a create or an update. Path: $root.0.${e}`);if(!s.schema[n.relation])throw new Error(`Relation '${n.relation}' not found`);let l=Nn(i,s),d=mt(l),c=fi(i,d,s),p=Array.isArray(t)?t:[t];for(let u of p){if(typeof u=="string"){let h=/^([^:]+):(_:.+)$/.exec(u);if(h){let[,$,g]=h,B=s.tempIdMap.get(g);if(B)Qn(n,c,l.name,$,B.id,s);else throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${g.replace(/^_:/,"")}`);continue}let y=at(u);if(y)Qn(n,c,l.name,y.thing,y.id,s);else if(u.startsWith("_:")){let $=s.tempIdMap.get(u);if($)Vt(n,c,l.name,$.id,s);else throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${u.replace(/^_:/,"")}`)}else Vt(n,c,l.name,u,s);continue}if(!Be(u))continue;let f=u,m=f.$op;if(m==="link"){let h=f.$id?Array.isArray(f.$id)?f.$id:[f.$id]:[];if(f.$tempId){let y=s.tempIdMap.get(f.$tempId);if(!y)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(f.$tempId).replace(/^_:/,"")}`);h.push(y.id);}if(h.length===0&&!f.$tempId){if(i.$op==="update"&&n.cardinality==="ONE")throw new Error("The query was not executed due to a failed transaction");let y=[n.opposite.thing,...s.schema[n.opposite.thing]?.subTypes??[]],$=s.schema[n.relation],g=$?.type==="relation"?$.fields[n.plays]:void 0,B=$?.type==="relation"?$.fields[n.targetRole]:void 0,E=g?.type==="role"?g.cardinality:"MANY",T=B?.type==="role"?B.cardinality:"MANY";s.mutation.linkAlls||(s.mutation.linkAlls=[]),s.mutation.linkAlls.push({oppositeThings:y,relation:n.relation,playsField:n.plays,targetRoleField:n.targetRole,playsCardinality:E,targetCardinality:T,parentThing:l.name,parentId:c});}else for(let y of h)Vt(n,c,l.name,y,s);}else if(m==="unlink")if(f.$id){let h=Array.isArray(f.$id)?f.$id:[f.$id];for(let y of h)Wa(n,c,l.name,y,o,s);}else Ua(n,c,l.name,o,s);else if(m==="update"){let h=f.$thing?s.schema[f.$thing]:s.schema[n.opposite.thing];if(!h)throw new Error(`Thing '${n.opposite.thing}' not found`);f.$thing||(f.$thing=h.name),Wt(f,h,o,e,s,n.cardinality,true);}else if(m==="delete"){let h=f.$thing?s.schema[f.$thing]:s.schema[n.opposite.thing];if(!h)throw new Error(`Thing '${n.opposite.thing}' not found`);f.$thing||(f.$thing=h.name),St(f,h,o,e,s,n.cardinality,true);}else {let h=f.$thing??n.opposite.thing,y=s.schema[h];if(!y)throw new Error(`Thing '${h}' not found`);f.$thing||(f.$thing=y.name),f.$op=f.$op??"create";let $=ot(f,y,o,null,s),g=s.mutation.creates.find(B=>B.name===$);Vt(n,c,l.name,g.id,s);}}},oi=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l={name:o,source:{type:"record_pointer",thing:a,ids:[r]}};i.mutation.matches.push(l);let c={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:{type:"role_field",cardinality:"MANY",op:"patch",path:e.plays,links:[{thing:n,subTypes:i.schema[n]?.subTypes?.length?i.schema[n].subTypes:void 0,id:t}],unlinks:[]}}};i.mutation.updates.push(c);},xa=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l={name:o,source:{type:"record_pointer",thing:a,ids:[r]}};i.mutation.matches.push(l);let c={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:Ut(e.plays,n,t,st(e.relation,e.plays,i))}};i.mutation.updates.push(c);},st=(e,t,n)=>{let r=n.schema[e];if(r?.type==="relation"){let i=r.fields[t];if(i?.type==="role")return i.cardinality}return "MANY"},Ut=(e,t,n,r)=>r==="ONE"?{type:"null",path:e}:{type:"role_field",cardinality:"MANY",op:"patch",path:e,links:[],unlinks:[{thing:t,id:n}]},ui=(e,t,n)=>{for(let r of Object.values(e.fields))if(r.type==="link"&&r.target==="relation"&&r.relation===t&&r.plays===n)return r},Va=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l=i.schema[n],d=l?ui(l,e.relation,e.plays):void 0;if(d){let f={name:o,parent:r,path:d.name,cardinality:d.cardinality,isComputed:true};i.mutation.subMatches.push(f);}else za(o,e,t,n,a,i);let c=st(e.relation,e.plays,i),u={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:Ut(e.plays,n,t,c)}};i.mutation.updates.push(u);},za=(e,t,n,r,i,o)=>{let a=st(t.relation,t.plays,o)==="ONE"?{type:"ref",op:"IN",left:t.plays,right:[n],thing:[r],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:t.plays,right:[n],thing:[r],cardinality:"MANY"},l={name:e,source:{type:"table_scan",thing:i},filter:a};o.mutation.matches.push(l);},Qn=(e,t,n,r,i,o)=>{let s=On(),a=Fe(e.relation,o),l=o.schema[e.relation];if(!l||l.type!=="relation")throw new Error(`Relation '${e.relation}' not found`);let d=l.fields[e.plays],c=d?.type==="role"?d.cardinality:"MANY",p=o.schema[n],u=p?.subTypes?.length?p.subTypes:void 0,f=o.schema[r],m=f?.subTypes?.length?f.subTypes:void 0,h={thing:n,subTypes:u,id:t},y={thing:r,subTypes:m,id:i},$={name:a,thing:e.relation,id:s,op:"create",values:{[e.plays]:c==="ONE"?{type:"role_field",cardinality:"ONE",path:e.plays,ref:h}:{type:"role_field",cardinality:"MANY",op:"replace",path:e.plays,refs:[h]},[e.targetRole]:e.targetRoleCardinality==="ONE"?{type:"role_field",cardinality:"ONE",path:e.targetRole,ref:y}:{type:"role_field",cardinality:"MANY",op:"replace",path:e.targetRole,refs:[y]}}};$.isIntermediary=true,o.mutation.creates.push($);},Vt=(e,t,n,r,i)=>{let o=i.schema[e.relation];if(!o||o.type!=="relation")throw new Error(`Relation '${e.relation}' not found`);let s=o.fields[e.targetRole];if(!s||s.type!=="role")throw new Error(`Role '${e.targetRole}' not found in relation '${e.relation}'`);let a=s.opposite.thing;Qn(e,t,n,a,r,i);},Wa=(e,t,n,r,i,o)=>{let s=Fe(e.relation,o),a=o.schema[e.relation];if(!a)throw new Error(`Relation '${e.relation}' not found`);let l=[e.relation,...a.subTypes],d=a.type==="relation"?a.fields[e.targetRole]:void 0,c=d?.type==="role"?d.opposite.thing:e.opposite.thing,u=st(e.relation,e.plays,o)==="ONE"?{type:"ref",op:"IN",left:e.plays,right:[t],thing:[n],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:e.plays,right:[t],thing:[n],cardinality:"MANY"},m=(d?.type==="role"?d.cardinality:"MANY")==="ONE"?{type:"ref",op:"IN",left:e.targetRole,right:[r],thing:[c],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:e.targetRole,right:[r],thing:[c],cardinality:"MANY"},h={name:s,source:{type:"table_scan",thing:l},filter:{type:"and",filters:[u,m]}};o.mutation.matches.push(h);let y=st(e.relation,e.plays,o),g={name:Fe(e.relation,o),match:s,op:"update",values:{[e.plays]:Ut(e.plays,n,t,y)}};o.mutation.updates.push(g);},Ua=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l=i.schema[n],d=l?ui(l,e.relation,e.plays):void 0;if(d){let u={name:o,parent:r,path:d.name,cardinality:d.cardinality,isComputed:true};i.mutation.subMatches.push(u);}else {let f=st(e.relation,e.plays,i)==="ONE"?{type:"ref",op:"IN",left:e.plays,right:[t],thing:[n],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:e.plays,right:[t],thing:[n],cardinality:"MANY"},m={name:o,source:{type:"table_scan",thing:a},filter:f};i.mutation.matches.push(m);}let p={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:Ut(e.plays,n,t,st(e.relation,e.plays,i))}};i.mutation.updates.push(p);},pi=(e,t)=>{for(let n of e.creates){let r=t[n.thing];r&&si(n.values,r,"create");}for(let n of e.updates){let r=e.matches.find(s=>s.name===n.match)??e.subMatches.find(s=>s.name===n.match);if(!r)continue;let i;if("source"in r){let s=r.source;s.type!=="subquery"&&(i=s.thing[0]);}if(!i)continue;let o=t[i];o&&si(n.values,o,"update");}},si=(e,t,n)=>{let r=t.idFields[0];for(let i of Object.values(t.fields)){if(i.type!=="data"||i.isVirtual||!i.validations)continue;let o=e[i.name];if(n==="create"&&i.validations.required&&i.name!==r&&o===void 0)throw new Error(`[Validations] Required field "${i.name}" is missing.`);if(!o||o.type!=="data_field")continue;let s=o.cardinality==="MANY"?o.value:[o.value];for(let a of s)if(a!==null){if(i.validations.enum&&!i.validations.enum.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${i.name}".`);if(i.validations.fn)try{if(!i.validations.fn(a))throw new Error(`[Validations:attribute:${i.name}] Failed validation function.`)}catch(l){if(l instanceof Error&&l.message.startsWith("[Validations:attribute:"))throw l;let d=l instanceof Error?l.message:String(l);throw new Error(`[Validations:attribute:${i.name}] ${d}`)}}}},va=e=>{let t=new Map;for(let a of e.creates)t.set(a.name,a);let n=new Map;for(let a of e.creates){let l=new Set;for(let d of Object.values(a.values))Ha(d,t,l);n.set(a.name,l);}let r=[],i=new Set,o=new Set,s=a=>{if(i.has(a))return;if(o.has(a)){Ya(a,n,e);return}o.add(a);let l=n.get(a);if(l)for(let c of l)t.has(c)&&s(c);o.delete(a),i.add(a);let d=t.get(a);d&&r.push(d);};for(let a of e.creates)s(a.name);e.creates=r;},Ha=(e,t,n)=>{if(e.type==="role_field"){if(e.cardinality==="ONE"){`${e.ref.thing}:${e.ref.id}`;for(let[i,o]of t)o.thing===e.ref.thing&&o.id===e.ref.id&&n.add(i);}else if("refs"in e)for(let r of e.refs)for(let[i,o]of t)o.thing===r.thing&&o.id===r.id&&n.add(i);else if("links"in e)for(let r of e.links)for(let[i,o]of t)o.thing===r.thing&&o.id===r.id&&n.add(i);}else if(e.type==="ref_field"){let r=e.cardinality==="ONE"?[e.value]:e.value;for(let i of r){let o=at(i);if(o)for(let[s,a]of t)a.thing===o.thing&&a.id===o.id&&n.add(s);}}},Ya=(e,t,n)=>{let r=t.get(e);if(r){for(let i of r)if(t.get(i)?.has(e)){let s=n.creates.find(a=>a.name===e);if(!s)return;for(let[a,l]of Object.entries(s.values))if(Ka(l,i,n)){let d={name:Ja(e),match:e,op:"update",values:{[a]:l}};n.updates.push(d),delete s.values[a],r.delete(i);return}}}},Ka=(e,t,n)=>{let r=n.creates.find(i=>i.name===t);if(!r)return false;if(e.type==="role_field"){if(e.cardinality==="ONE")return e.ref.thing===r.thing&&e.ref.id===r.id;if("refs"in e)return e.refs.some(i=>i.thing===r.thing&&i.id===r.id);if("links"in e)return e.links.some(i=>i.thing===r.thing&&i.id===r.id)}return false},Ja=e=>`${e}_deferred`,Nn=(e,t)=>{let n=t.schema[e.$thing];if(!n)throw new Error(`Thing '${e.$thing}' not found in schema`);return n},mt=e=>{if(e.idFields.length>1)throw new Error(`Composite id fields are not supported for '${e.name}'`);return e.idFields[0]},fi=(e,t,n)=>{if(e.$id)return Array.isArray(e.$id)?e.$id[0]:e.$id;if(e[t])return e[t];if(e.$tempId){let r=n.tempIdMap.get(e.$tempId);if(r)return r.id}if(e.$thing){let r=[...n.mutation.creates].reverse().find(i=>i.thing===e.$thing);if(r)return r.id}return ""},Za=(e,t,n)=>{if(n[e]!==void 0){let r=Array.isArray(n.$id)?n.$id[0]:n.$id;if(r!==void 0&&n[e]===r){delete n[e];return}throw new Error(`Cannot mutate id field '${e}' on '${t}'. Use '$id' to identify the record instead.`)}},zt=e=>Object.keys(e).some(t=>!t.startsWith("$")),Be=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date),ai=e=>Be(e)&&Object.keys(e).some(t=>t.startsWith("$")),at=e=>{if(/\s/.test(e))return;let t=/^([^:]+):([^:]+)$/.exec(e);if(!t)return;let[,n,r]=t;if(!(!n||!r)&&n!=="_")return {thing:n,id:r}},Xa=(e,t)=>{let n=new Map;for(let[r,i]of Object.entries(e)){if(r.startsWith("$")||i===null||i===void 0)continue;let o=t.fields[r];if(o?.type==="link"){let s=n.get(o.relation);if(s&&s!==o.target)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");n.set(o.relation,o.target);}}};var $i=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,r])=>t(n,r))))[0],me=(e,t)=>{let n=Reflect.ownKeys(e).map(r=>[r,e[r]]);return Object.fromEntries(n.filter(([r,i])=>{let[o,s]=tryit(()=>t(r,i))();return o?false:s}))},oe=(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)}`)},vt=(e,t)=>{let n=e.dataFields?.find(o=>o.path===t);if(e.idFields?.includes(t)){if(!n)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",n]}if(n)return ["dataField",n];let r=e.linkFields?.find(o=>o.path===t);if(r)return ["linkField",r];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`)},Ht=(e,t)=>{let n=z(e,t);if(n?.idFields?.length&&n?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${n?.idFields}`);let[r]=n.idFields;return r},yi=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},Cn=(e,t,n)=>{let r=z(e,t),i=r.linkFields?.find(l=>l.path===n);if(i)return i;let o=r.dataFields?.find(l=>l.path===n);if(o)return o;let s="roles"in r?r.roles?.[n]:void 0;if(s)return s;let a="refFields"in r?r.refFields?.[n]:void 0;if(a)return a;throw new Error(`Field ${n} not found in schema`)},_n=(e,t,n)=>Cn(e,t,n)?.cardinality,$e=(e,t)=>{let n=e.dataFields?.map(h=>h.path)||[],r=e.linkFields?.map(h=>h.path)||[],i="refFields"in e?listify(e.refFields,h=>h):[],o="roles"in e?listify(e.roles,h=>h):[],s=[...n||[],...r||[],...o||[],...i||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...s];if(!t)return {fields:s,dataFields:n,roleFields:o,linkFields:r};let d=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!s.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!s.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),c=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&n?.includes(h)):[],p=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...r||[]].includes(h)):[],u=[...d,...c].filter(h=>!h?.startsWith("%")).filter(h=>!l.includes(h)).filter(h=>h),f=t.$filter?me(t.$filter,(h,y)=>c.includes(h)):{},m=t.$filter?me(t.$filter,(h,y)=>p.includes(h)):{};return {fields:s,dataFields:n,roleFields:o,linkFields:r,refFields:i,usedFields:d,usedLinkFields:r.filter(h=>d.includes(h)),usedRoleFields:o.filter(h=>d.includes(h)),usedDataFields:n.filter(h=>d.includes(h)),usedRefFields:i.filter(h=>d.includes(h)),unidentifiedFields:u,...c.length?{localFilters:f}:{},...p.length?{nestedFilters:m}:{}}};var gi=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Ei=(e,t,n)=>{let i=(n.nodePath||"").split("."),o=isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?getNodeByPath(e,o):{}},We=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var Yt=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,n={};for(let[r,i]of Object.entries(t))n[r]=isDraft(i)?current(i):i;return n}return e},Ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},N=(e,t)=>{let n="";for(let r=0;r<t;r++)n+=" ";return `${n}${e}`},Ue=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),$t=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)();var Bi=(e,t)=>{let n=[],r=e.cardinality==="MANY"?0:1;e.cardinality==="ONE"&&n.push("array::first("),n.push(Fi(e.projection,r,t)),n.push(At(e.source,r,t));let i=e.filter&&Le(e.filter,t);return i&&n.push(J(`WHERE ${i}`,r)),e.sort&&e.sort.length>0&&n.push(bi(e.sort,r)),e.limit!==void 0&&n.push(J(`LIMIT ${e.limit}`,r)),e.offset!==void 0&&n.push(J(`START ${e.offset}`,r)),e.cardinality==="ONE"&&n.push(")"),n.join(`
68
- `)},Fi=(e,t,n)=>{let r=[],i=t+1;for(let s of e.fields)s.type==="metadata"?r.push(rl(s,i)):s.type==="data"?r.push(il(s,i)):s.type==="ref"||s.type==="computed_ref"?r.push(ol(s,i)):s.type==="nested_ref"||s.type==="nested_computed_ref"?r.push(sl(s,i,n)):s.type==="flex"&&r.push(al(s,i));let o=[];return o.push(J("SELECT",t)),o.push(r.join(`,
67
+ `},Lr=async(e,t,n,r)=>{if(!r.typeDB)throw new Error("No TypeDB handles found");let i=aa(e,n),o=r.typeDB.get(e)?.session,s=r.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 Dr=async(e,t,n,r)=>await(async()=>{let s=(await Promise.all([...r.typeDB||[]].map(async([d])=>[d,await Lr(d,e,t,r)]))).map(d=>[d[0],d[1]]),l=(await Promise.all([...r.surrealDB||[]].map(async([d])=>[d,Ar(n)]))).map(d=>[d[0],d[1]]);return {typeDB:Object.fromEntries(s),surrealDB:Object.fromEntries(l)}})();var kr={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var Oe=Symbol.for("queryPath"),qt=Symbol.for("stepPrint"),tt=Symbol.for("edgeType"),Ne=Symbol.for("edgeSchema");var ft=Symbol.for("dbNode"),Bn=Symbol.for("isTransformed"),ht=Symbol.for("parent"),ze=Symbol.for("fieldSchema"),Z=Symbol.for("sharedMetadata"),St=Symbol.for("flexDataValue"),nt=Symbol.for("suqlMetadata");var Ir=(e,t)=>{let n=Qr(e.entities),r=Qr(e.relations),i=ca(e),o={entities:{},relations:{}};return n.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&&bn(o,l.name,s);let d=Or({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i});o.entities[s]={...d,defaultDBConnector:a.defaultDBConnector,thingType:"entity"};}),r.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&&bn(o,l.name,s);let d=Or({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(([p,u])=>[p,Nr({role:u,roleName:p,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in a&&l&&Object.entries(l?.roles??{}).forEach(([p,u])=>{let f=Nr({role:u,roleName:p,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i});c.roles[p]={...f,inherited:true,[Z]:{...u[Z],inheritanceOrigin:u[Z]?.inheritanceOrigin||a.extends}};}),o.relations[s]=c;}),Object.values(o.entities).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Fn(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Fn(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Fn(o,a.$things);});}),o},Qr=e=>{let t=[],n=new Set,r=new Set;for(let i of Object.keys(e))Cr({thingMap:e,name:i,inProcess:r,seen:n,ordered:t});return t},Cr=e=>{let{thingMap:t,name:n,inProcess:r,seen:i,ordered:o}=e;if(i.has(n))return;if(r.has(n))throw new Error(`A list of thing extends each other that creates circular dependencies: ${[...r]}`);r.add(n);let s=t[n];if(!s)throw new Error(`Entity/relation "${n}" does not exist`);"extends"in s&&Cr({...e,name:s.extends}),r.delete(n),i.add(n),o.push(n);},la=(e,t)=>{let n=t,r=[];for(;n;){let i=e.entities[n]||e.relations[n];if(!i)throw new Error(`Entity/relation "${n}" does not exist`);r.push(n),n="extends"in i?i.extends:void 0;}return r.length!==0?r:void 0},bn=(e,t,n)=>{let r=e.entities[t]??e.relations[t];if(!r)throw new Error(`Entity/relation "${t}" does not exist`);r.subTypes=r.subTypes??[],r.subTypes.push(n),r.extends&&bn(e,r.extends,n);},Or=e=>{let{schema:t,enrichedSchema:n,name:r,thing:i,dbHandles:o,extendedThing:s,allLinkFields:a}=e,[l]=Object.entries(o).find(([m,h])=>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(`"${r}" does not have an id field`);let c={...i.hooks},p=i.dataFields?.map(m=>da(m,r,d))??[],u=i.linkFields?.map(m=>pa({linkField:m,thingName:r,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([m,h])=>[m,ua(h,m)]));return "extends"in i&&s&&(s.hooks?.pre&&(c.pre=[...s.hooks.pre||[],...i.hooks?.pre||[]]),s.dataFields?.forEach(m=>{p.push({...m,inherited:true,[Z]:{...m[Z],inheritanceOrigin:m[Z]?.inheritanceOrigin||i.extends}});}),s.linkFields?.forEach(m=>{u.push({...m,inherited:true,[Z]:{...m[Z],inheritanceOrigin:m[Z]?.inheritanceOrigin||i.extends}});}),Object.entries(s.refFields??{}).forEach(([m,h])=>{f[m]={...h,inherited:true,[Z]:{...h[Z],inheritanceOrigin:h[Z]?.inheritanceOrigin||i.extends}};})),{...i,name:r,db:l,dbContext:kr[l],idFields:d,hooks:c,dataFields:p,linkFields:u,refFields:f,enumFields:p?.filter(m=>m.validations?.enum).map(m=>m.path)??[],fnValidatedFields:p?.filter(m=>m.validations?.fn).map(m=>m.path)??[],virtualFields:p?.filter(m=>m.isVirtual).map(m=>m.path)??[],computedFields:p?.filter(m=>m.default&&!m.isVirtual).map(m=>m.path)??[],requiredFields:p?.filter(m=>m.validations?.required).map(m=>m.path)??[],allExtends:"extends"in i?la(n,i.extends):void 0}},ca=e=>{let t=[];return Object.entries(e.entities).forEach(([n,r])=>{r.linkFields?.forEach(i=>{t.push({...i,thing:n,thingType:"entity",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),Object.entries(e.relations).forEach(([n,r])=>{r.linkFields?.forEach(i=>{t.push({...i,thing:n,thingType:"relation",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),t},da=(e,t,n)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:fa(t,e.path,e.shared),isIdField:!!n?.includes(e.path),inherited:false,[Z]:{fieldType:"dataField"},[nt]:{dbPath:e.path}}),ua=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[Z]:{fieldType:"refField"}}),pa=e=>{let{linkField:t,thing:n,thingName:r,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(!_r(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: "${r}" LinkField: "${t.path}."`);return {...t,$things:[t.relation],oppositeLinkFieldsPlayedBy:[{plays:t.path,thing:t.relation,thingType:"relation"}],fieldType:"linkField",inherited:false,[Z]:{fieldType:"linkField"},[nt]:{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: "${r}" LinkField: "${t.path}."`);return l.length>1&&console.warn(`[Schema] LinkField ${t.path} in ${r} 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:n.linkFields?.find(d=>d.target==="relation"&&d.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(d=>d.thing),oppositeLinkFieldsPlayedBy:l,[Z]:{fieldType:"linkField"},[nt]:{queryPath:a}}},Nr=e=>{let{role:t,roleName:n,relationName:r,relation:i,allExtends:o,allLinkFields:s}=e;if(i.dataFields?.find(d=>d.path===n)||i.linkFields?.find(d=>d.path===n))throw new Error(`[Schema] The path ${n} is already in use by a dataField or linkField in ${r}.`);let a=s.filter(d=>d.relation===r&&d.plays===n),l=s.filter(d=>d.target==="relation"&&d.plays===n&&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===n&&c.plays===n)?.path??d.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:n,$things:[...new Set(a.map(d=>d.thing))],[Z]:{fieldType:"roleField"},[nt]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${n}\`]`:`$parent.\`${n}\``}}},fa=(e,t,n)=>n?t:`${e}\xB7${t}`,_r=(e,t,n)=>{let r=e.relations[t];if(!r)throw new Error(`Relation "${t}" does not exist`);return r.roles?.[n]?true:"extends"in r?_r(e,r.extends,n):false},Fn=(e,t)=>t.flatMap(n=>[n,...(e.entities[n]??e.relations[n])?.subTypes??[]]);var qr=e=>{let t=Ra(e),n={},r=Ba(t);for(let i in t.entities)Rn("entity",i,n,t,r);for(let i in t.relations)Rn("relation",i,n,t,r);return n},Rn=(e,t,n,r,i)=>{let o=n[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"?r.entities[t]:r.relations[t];if(!s)throw new Error(`${e==="entity"?"Entity":"Relation"} "${t}" not found`);let a="extends"in s&&s.extends?Rn(e,s.extends,n,r,i):void 0;a&&ma(a.name,t,n);let l={},d=a?a.idFields:ba(t,s);$a(l,s.dataFields??[],t),ya(l,s.refFields??{},t),ga(l,s.linkFields??[],t,r,i);let c=s.hooks;if(e==="entity"){jr(t,l);let u={type:"entity",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],hooks:c,fields:l};return n[t]=u,u}"roles"in s&&s.roles&&Ea(l,s.roles??{},t,i),jr(t,l);let p={type:"relation",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],hooks:c,fields:l};return n[t]=p,p},ma=(e,t,n)=>{let r=e;for(;r;){let i=n[r];if(!i)throw new Error(`Thing "${r}" not found`);i.subTypes.push(t),r=i.extends;}},$a=(e,t,n)=>{for(let r of t??[]){let i=e[r.path];if(r.isVirtual){if(r.default?.type==="fn"&&typeof r.default.fn=="function"){let s={type:"computed",name:r.path,contentType:r.contentType,cardinality:r.cardinality??"ONE",fn:r.default.fn};rt(n,s,i),e[r.path]=s;continue}if(r.default?.type==="value"){let s={type:"constant",name:r.path,contentType:r.contentType,cardinality:r.cardinality??"ONE",value:r.default.value};rt(n,s,i),e[r.path]=s;continue}}let o={type:"data",name:r.path,contentType:r.contentType,cardinality:r.cardinality??"ONE",unique:r.validations?.unique??false,default:r.default,validations:r.validations,isVirtual:r.isVirtual,dbValue:r.dbValue};rt(n,o,i),e[r.path]=o;}},ya=(e,t,n)=>{for(let[r,i]of Object.entries(t??{})){let o=e[r],s={type:"ref",name:r,contentType:i.contentType,cardinality:i.cardinality??"ONE"};rt(n,s,o),e[r]=s;}},ga=(e,t,n,r,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 "${n}": only alphanumeric characters, underscores, dashes, and spaces are allowed`);let s=r.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 m={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};rt(n,m,l),e[o.path]=m;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 p=s.roles?.[o.targetRole];if(!p)throw new Error(`Target role ${o.targetRole} not found in relation ${o.relation}`);let u=p.cardinality;if(o.cardinality==="ONE"&&u==="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:u,opposite:c,isVirtual:o.isVirtual,dbValue:o.dbValue};rt(n,f,l),e[o.path]=f;}},Ea=(e,t,n,r)=>{for(let[i,o]of Object.entries(t)){let s=r[n]?.[i]?.targetingRelation??r[n]?.[i]?.targetingRole;if(!s)throw new Error(`Role ${i} in relation ${n} 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};rt(n,l,a),e[i]=l;}},rt=(e,t,n)=>{if(n&&!isEqual(t,n))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},jr=(e,t)=>{let n=new Map,r=(i,o,s)=>{let a=n.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}"`);n.set(i,{originalName:o,fieldType:s});};for(let i of Object.values(t))if(i.type==="link"){r(i.name,i.name,i.type);let o=be(i.name);o!==i.name&&r(o,i.name,i.type);}else r(i.name,i.name,i.type);},Ba=e=>{let t={};for(let[n,r]of [...Object.entries(e.relations),...Object.entries(e.entities)])for(let i of r.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===n||Pr(n,a.thing,e))continue;if(!Pr(a.thing,n,e))throw new Error(`Found multiple players for role ${i.plays} in relation ${i.relation}`)}i.target==="relation"?s.targetingRelation={thing:n,path:i.path,cardinality:i.cardinality}:s.targetingRole={thing:n,path:i.path,cardinality:i.cardinality};}return t},Pr=(e,t,n)=>Fa(e,n).includes(t),Fa=(e,t)=>{let n=[],r=e;for(;r;){let i=t.entities[r]??t.relations[r];if(!i)throw new Error(`Thing "${r}" not found`);if(!("extends"in i)||!i.extends)break;n.push(i.extends),r=i.extends;}return n.reverse()},ba=(e,t)=>{if(t.idFields&&t.idFields.length>0)return [t.idFields[0],...t.idFields.slice(1)];let n=t.dataFields?.find(r=>r.contentType==="ID");if(n)return [n.path];throw new Error(`No id field found for entity "${e}"`)},Ra=e=>{let t={entities:{},relations:{}};for(let n in e.entities)xr(n,e,t);for(let n in e.relations)Vr(n,e,t);return t},xr=(e,t,n)=>{let r=t.entities[e];if(!r)throw new Error(`Entity "${e}" not found`);if("extends"in r&&r.extends){let i=xr(r.extends,t,n),o={...r,idFields:r.idFields??i.idFields,dataFields:zr(i,r),linkFields:Wr(i,r),refFields:Ur(i,r),hooks:vr(i.hooks,r.hooks)};return n.entities[e]=o,o}return n.entities[e]=r,r},Vr=(e,t,n)=>{let r=t.relations[e];if(!r)throw new Error(`Relation "${e}" not found`);if("extends"in r&&r.extends){let i=Vr(r.extends,t,n),o={...r,idFields:r.idFields??i.idFields,dataFields:zr(i,r),linkFields:Wr(i,r),refFields:Ur(i,r),roles:Ta(i,r),hooks:vr(i.hooks,r.hooks)};return n.relations[e]=o,o}return n.relations[e]=r,r},zr=(e,t)=>{let n=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!n.has(i.path))??[],...t.dataFields??[]]},Wr=(e,t)=>{let n=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!n.has(i.path))??[],...t.linkFields??[]]},Ur=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([r])=>!t.refFields?.[r])),...t.refFields??{}}),Ta=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([r])=>!t.roles?.[r])),...t.roles??{}}),vr=(e,t)=>{if(!(!e&&!t))return e?t?{pre:[...e.pre??[],...t.pre??[]]}:e:t};var pe=z$1.json(),we=z$1.array(pe),Hr=z$1.strictObject({$exists:z$1.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:we.optional(),$nin:we.optional(),$containsAll:we.optional(),$containsAny:we.optional(),$containsNone:we.optional()}),Me=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>Me)).optional(),$not:z$1.lazy(()=>Me).optional()}).catchall(z$1.union([pe,we,z$1.lazy(()=>z$1.union([it,z$1.array(it)]))]))),it=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>Me)).optional(),$not:z$1.lazy(()=>Me).optional(),$exists:z$1.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:we.optional(),$nin:we.optional(),$containsAll:we.optional(),$containsAny:we.optional(),$containsNone:we.optional()}).catchall(z$1.union([pe,we,z$1.lazy(()=>z$1.union([it,z$1.array(it)]))]))),Yr=z$1.object({$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([Me,z$1.array(Me)]).optional(),$fields:z$1.array(z$1.union([z$1.string(),z$1.lazy(()=>wa)])).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()}),wa=Yr.extend({$path:z$1.string(),$as:z$1.string().optional()}),Kr=Yr.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:n,$relation:r,...i}=e;return {...i,$thing:t??n??r}});var Jr=(e,t,n)=>{let r=t[e.$thing],i=Zr({fields:e.$fields,thing:r,schema:t,metadata:n}),o=e.$filter?Pe(e.$filter,r,t):void 0,s=Array.isArray(e.$id)?e.$id:e.$id?[e.$id]:[],a=s.length===1||wn(r,o)?"ONE":"MANY";return {source:s.length>0?{type:"record_pointer",thing:[r.name,...r.subTypes],ids:s}:{type:"table_scan",thing:[r.name,...r.subTypes]},projection:i,filter:o,limit:ti(e.$limit),offset:ni(e.$offset),sort:ri(i,Gr(e.$sort)),cardinality:a}},Zr=e=>{let{fields:t,thing:n,schema:r,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(n.fields)){let a=Tn(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 p=n.fields[s];if(!p)throw new Error(`Field ${s} not found in ${n.name}`);let u=Tn(p);u&&o.push(u);continue}if(s.$path==="$id"||s.$path==="$thing"){o.push({type:"metadata",path:s.$path,alias:s.$as});continue}let a=n.fields[s.$path];if(!a)throw new Error(`Field ${s} not found in ${n.name}`);if(a.type==="constant"||a.type==="computed")continue;if(a.type==="data"||a.type==="ref"){let p=Tn(a,s.$as);p&&o.push(p);continue}let l=r[a.opposite.thing],d=Zr({fields:s.$fields,thing:l,schema:r,metadata:i}),c="$filter"in s&&s.$filter?Pe(s.$filter,l,r):void 0;o.push({type:a.type==="role"?"nested_ref":"nested_computed_ref",path:s.$path,projection:d,resultCardinality:typeof s.$id=="string"||wn(l,c)?"ONE":a.cardinality,fieldCardinality:a.cardinality,alias:s.$as,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:c,limit:ti(s.$limit),offset:ni(s.$offset),sort:ri(d,Gr(s.$sort))});}return {fields:o}},Tn=(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}},Pe=(e,t,n)=>Array.isArray(e)?{type:"or",filters:e.map(o=>Pe(o,t,n)).filter(o=>!!o)}:{type:"and",filters:Sa(e,t,n)},Sa=(e,t,n)=>Object.entries(e).map(([r,i])=>{if(r==="$not"&&e.$not)return Ma(e.$not,t,n);if(r==="$or"&&e.$or)return Aa(e.$or,t,n);let o=t.fields[r];if(!o)throw new Error(`Field ${r} not found in ${t.name}`);if(o.type==="constant"||o.type==="computed")throw new Error(`Filtering on constant or computed field ${r} is not supported`);if(i!==void 0)return o.type==="data"?La(o,i):o.type==="ref"?Da(o,i):Xr(o,i,n)}).filter(r=>r!==void 0),Ma=(e,t,n)=>{let r=Pe(e,t,n);return r?{type:"not",filter:r}:void 0},Aa=(e,t,n)=>Pe(e,t,n),La=(e,t)=>{let n=Hr.safeParse(t);if(n.success){let r=[];for(let[i,o]of Object.entries(n.data)){if(i==="$exists"){r.push({type:"null",op:o?"IS NOT":"IS",left:e.name,emptyIsArray:false});continue}if((i==="$eq"||i==="$ne")&&o===null){r.push({type:"null",op:i==="$eq"?"IS":"IS NOT",left:e.name,emptyIsArray:false});continue}let s=ka[i];if(s){r.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=ei[i];if(a){r.push({type:"list",op:a,left:e.name,right:o});continue}throw new Error(`Invalid filter operation: ${i}`)}return {type:"and",filters:r}}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}},Da=(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(Vt.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(Vt.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")},Xr=(e,t,n)=>{let r=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:r};if(typeof t=="string")return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],cardinality:s,oppositeCardinality:a};if(Vt.safeParse(t).success)return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,cardinality:s,oppositeCardinality:a};let l=xt.union([it,xt.array(it)]).safeParse(t);if(l.error)throw new Error(`Invalid nested filter: ${l.error.message}`);let d=n[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(D=>Xr(e,D,n))};let{$eq:p,$ne:u,$contains:f,$containsNot:m,$in:h,$nin:y,$containsAll:$,$containsAny:g,$containsNone:B,...E}=l.data;for(let R of ["$gt","$lt","$gte","$lte"])if(E[R])throw new Error(`Filtering ${e.type} field with ${R} operator is not supported`);let T=[];for(let R of ["$exists","$eq","$ne","$contains","$containsNot"]){let D=l.data[R];if(D!==void 0){if(R==="$exists"){T.push({type:"null",op:D?"IS NOT":"IS",left:e.name,emptyIsArray:r});continue}if((R==="$eq"||R==="$ne")&&D===null){T.push({type:"null",op:R==="$eq"?"IS":"IS NOT",left:e.name,emptyIsArray:r});continue}if(typeof D!="string")throw new Error(`Filter value for ${e.type} field with operator ${R} must be a string`);T.push({type:i,op:R==="$eq"||R==="$contains"?"IN":"NOT IN",left:e.name,right:[D],thing:c,cardinality:s,oppositeCardinality:a});}}for(let R of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let D=l.data[R];if(D===void 0)continue;let I=Vt.safeParse(D);if(!I.success)throw new Error(`Filter value for ${e.type} field with operator ${R} must be a string array`);let q=ei[R];if(!q)throw new Error(`Invalid list operator: ${R}`);T.push({type:i,op:q,left:e.name,right:I.data,thing:c,cardinality:s,oppositeCardinality:a});}let A=n[e.opposite.thing];if(!A)throw new Error(`Unknown thing: ${e.opposite.thing}`);let k=Pe(E,A,n);return k&&T.push({type:o,path:e.name,filter:k,cardinality:s,oppositeCardinality:a}),{type:"and",filters:T}},wn=(e,t)=>{if(!t)return false;if(t.type==="scalar"){if(t.op!=="=")return false;let n=e.fields[t.left];if(!n)throw new Error(`Field ${t.left} not found in ${e.name}`);return n.type==="data"&&n.unique}if(t.type==="list"){if(t.op!=="IN"||t.right.length>1)return false;let n=e.fields[t.left];if(!n)throw new Error(`Field ${t.left} not found in ${e.name}`);return n.type==="data"&&n.unique}return t.type==="and"?t.filters.some(n=>wn(e,n)):false},Gr=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},ka={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},ei={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},Vt=xt.array(xt.string()),ti=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},ni=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},ri=(e,t)=>{if(!t||t.length===0)return;let n=new Set(e.fields.map(r=>r.type==="metadata"?r.path:r.alias??r.path));for(let r of t)if(!n.has(r.field))throw new Error(`Missing sorter field in the selected fields: ${r.field}`);return t};var ci=(e,t)=>{let n={schema:t,mutation:{matches:[],subMatches:[],creates:[],updates:[],deletes:[]},nameCounters:{},tempIdMap:new Map},r=Array.isArray(e)?e:[e];for(let i of r)Ln(i,n);for(let i of r)Na(i,null,null,n);return Ha(n.mutation),n.mutation},Oa=e=>e.replace(/[\s-]/g,"_").replace(/[^a-zA-Z0-9_]/g,""),Fe=(e,t)=>{let n=Oa(e),r=t.nameCounters[n]??0;return t.nameCounters[n]=r+1,`${n}_${r}`},Nn=customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",16),Ln=(e,t)=>{if(e.$tempId){let n=e.$tempId.replace(/^_:/,"");if(e.$op==="create"){if(t.tempIdMap.has(e.$tempId))throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${n}". Existing: create. Current: create`);if(e.$thing&&t.schema[e.$thing]){let r=t.schema[e.$thing],i=$t(r),o=e.$id??e[i]??Nn();t.tempIdMap.set(e.$tempId,{thing:r.name,id:o}),e[i]===void 0&&e.$id===void 0&&(e[i]=o);}}}for(let[n,r]of Object.entries(e))if(!n.startsWith("$")&&r!=null)if(Array.isArray(r))for(let i of r)li(i)&&Ln(i,t);else li(r)&&Ln(r,t);},Na=(e,t,n,r)=>{let i=e.$op,o=In(e,r);switch(i){case "create":st(e,o,t,n,r);break;case "update":Ut(e,o,t,n,r);break;case "delete":Mt(e,o,t,n,r);break;}},st=(e,t,n,r,i)=>{let o=$t(t),s=e.$tempId?i.tempIdMap.get(e.$tempId):void 0,a=s?s.id:e.$id??e[o]??Nn();e.$tempId&&!i.tempIdMap.has(e.$tempId)&&i.tempIdMap.set(e.$tempId,{thing:t.name,id:a}),Ga(e,t);let l=Fe(t.name,i),d={name:l,thing:t.name,id:a,tempId:e.$tempId,op:"create",values:{}};i.mutation.creates.push(d);for(let[c,p]of Object.entries(e)){if(c.startsWith("$")||c===o||p===void 0)continue;let u=ui(c,p,t,e,l,i);u&&(d.values[c]=u);}return l},Ut=(e,t,n,r,i,o,s)=>{let a=$t(t);Xa(a,t.name,e);let l=di(e,t,n,r,i,o,s),d={},c=false;for(let[p,u]of Object.entries(e)){if(p.startsWith("$")||u===void 0)continue;let f=ui(p,u,t,e,l,i);f&&(d[p]=f,c=true);}if(c){let p={name:Fe(t.name,i),match:l,op:"update",values:d};i.mutation.updates.push(p);}},Mt=(e,t,n,r,i,o,s)=>{let a=di(e,t,n,r,i,o,s);for(let[d,c]of Object.entries(e)){if(d.startsWith("$")||c==null)continue;let p=t.fields[d];if(p)if(p.type==="role"){let u=Array.isArray(c)?c:[c];for(let f of u)if(Be(f)){let m=f,h=m.$thing?i.schema[m.$thing]:i.schema[p.opposite.thing];h&&(m.$thing||(m.$thing=h.name),m.$op==="delete"&&Mt(m,h,a,d,i,p.cardinality));}}else p.type==="link"&&Qn(d,c,p,t,e,a,i);}let l={name:Fe(t.name,i),match:a,op:"delete"};i.mutation.deletes.push(l);},di=(e,t,n,r,i,o,s)=>{let a=$t(t),{ids:l,remainingFilter:d}=Ia(e.$filter,a),p=[...e.$id?Array.isArray(e.$id)?e.$id:[e.$id]:[],...l];if(n&&r){let h=Fe(t.name,i),y={name:h,parent:n,path:r,cardinality:o??"MANY",isComputed:s,ids:p.length>0?p:void 0,filter:d?Pe(d,t,i.schema):void 0};return i.mutation.subMatches.push(y),h}let u=Fe(t.name,i),f=[t.name,...t.subTypes],m=d?Pe(d,t,i.schema):void 0;if(p.length>0){let h={name:u,source:{type:"record_pointer",thing:f,ids:p},filter:m};i.mutation.matches.push(h);}else if(m){let h={name:u,source:{type:"table_scan",thing:f},filter:m};i.mutation.matches.push(h);}else {let h={name:u,source:{type:"table_scan",thing:f}};i.mutation.matches.push(h);}return u},Ia=(e,t)=>{if(!e||Array.isArray(e))return {ids:[],remainingFilter:e};let n=e[t];if(n===void 0)return {ids:[],remainingFilter:e};let r={...e};delete r[t];let o=Object.keys(r).filter(s=>!s.startsWith("$")).length>0||r.$not!==void 0||r.$or!==void 0?r:void 0;return typeof n=="string"?{ids:[n],remainingFilter:o}:Array.isArray(n)&&n.every(s=>typeof s=="string")?{ids:n,remainingFilter:o}:{ids:[],remainingFilter:e}},ui=(e,t,n,r,i,o)=>{if(e.startsWith("%"))return;let s=n.fields[e];if(!s)throw new Error(`Unknown field '${e}' on '${n.name}'`);if(s.type==="constant")throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(s.type==="computed")throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(s.type==="data"&&s.isVirtual)throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(s.type==="link"&&s.isVirtual)throw new Error(`Virtual fields can't be sent to DB: "${e}"`);if(t===null){if(s.type==="link"){Qn(e,[{$op:"unlink"}],s,n,r,i,o);return}return (s.type==="role"||s.type==="ref")&&s.cardinality==="MANY"?{type:"empty",path:e}:{type:"null",path:e}}switch(s.type){case "data":return Ca(e,t,s);case "ref":return _a(e,t,s,r,i,o);case "role":return Pa(e,t,s,r,i,o);case "link":Qn(e,t,s,n,r,i,o);return;default:throw new Error(`Unsupported field type for '${e}' on '${n.name}'`)}},Ca=(e,t,n)=>{let r=n.contentType==="JSON"?Dn(t):t;return n.cardinality==="MANY"?{type:"data_field",cardinality:"MANY",path:e,value:Array.isArray(r)?r:[r]}:{type:"data_field",cardinality:"ONE",path:e,value:r}},Dn=e=>{if(e==null)return e;if(Array.isArray(e))return e.map(Dn);if(Be(e)){let t=e;if(Object.keys(t).length===1&&typeof t.$ref=="string"){let i=at(t.$ref);if(i)return new RecordId(i.thing,i.id)}let r={};for(let[i,o]of Object.entries(t))r[i]=Dn(o);return r}return e},_a=(e,t,n,r,i,o)=>{if(n.contentType==="FLEX")return ja(e,t,n,o,i);if(n.cardinality==="ONE"){if(Be(t)&&t.$op==="create"){let u=t;if(!u.$thing)throw new Error(`Nested create in ref field '${e}' must have $thing`);let f=o.schema[u.$thing];if(!f)throw new Error(`Thing '${u.$thing}' not found in schema`);let m=st(u,f,i,null,o),h=o.mutation.creates.find(y=>y.name===m);return {type:"ref_field",cardinality:"ONE",path:e,value:`${h.thing}:${h.id}`}}if(Be(t)&&t.$op==="link"){let u=Sn(t,o);if(!u)return;let f=Array.isArray(u)?u[0]:u;return {type:"ref_field",cardinality:"ONE",path:e,value:`${f.thing}:${f.id}`}}let p=ii(t,r,i,o);return p?{type:"ref_field",cardinality:"ONE",path:e,value:`${p.thing}:${p.id}`}:void 0}let s=Array.isArray(t)?t:[t],a=[],l=[],d=[],c=false;for(let p of s)if(Be(p)&&p.$op==="create"){let u=p;if(!u.$thing)throw new Error(`Nested create in ref field '${e}' must have $thing`);let f=o.schema[u.$thing];if(!f)throw new Error(`Thing '${u.$thing}' not found in schema`);let m=st(u,f,i,null,o),h=o.mutation.creates.find(y=>y.name===m);a.push(`${h.thing}:${h.id}`),c=true;}else if(Be(p)&&p.$op==="link"){let f=Sn(p,o);f&&(Array.isArray(f)?l.push(...f):l.push(f));}else if(Be(p)&&p.$op==="unlink"){let f=Sn(p,o);f&&(Array.isArray(f)?d.push(...f):d.push(f));}else {let u=ii(p,r,i,o);u&&a.push(`${u.thing}:${u.id}`);}if(l.length>0||d.length>0||c){let p=[...a,...l.map(u=>`${u.thing}:${u.id}`)];return {type:"ref_field",cardinality:"MANY",path:e,value:p}}return {type:"ref_field",cardinality:"MANY",path:e,value:a}},ii=(e,t,n,r)=>{if(typeof e=="string"){let i=at(e);if(i)return i;if(e.startsWith("_:")){let o=e,s=r.tempIdMap.get(o);if(!s)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${o.replace(/^_:/,"")}`);return s}throw new Error(`Invalid ref value: ${e}. Expected 'Type:id' format.`)}if(Be(e)){let i=e;if(i.$thing&&i.$id)return {thing:i.$thing,id:i.$id};if(i.$tempId){let o=r.tempIdMap.get(i.$tempId);if(!o)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(i.$tempId).replace(/^_:/,"")}`);return o}}},Sn=(e,t)=>{if(e.$id){let n=Array.isArray(e.$id)?e.$id:[e.$id];if(e.$thing){let r=n.map(i=>({thing:e.$thing,id:i}));return r.length===1?r[0]:r}}if(e.$tempId){let n=t.tempIdMap.get(e.$tempId);if(!n)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(e.$tempId).replace(/^_:/,"")}`);return n}},ja=(e,t,n,r,i)=>{if(n.cardinality==="ONE")return {type:"flex_field",cardinality:"ONE",path:e,value:oi(t,r,i)};let o=Array.isArray(t)?t:[t];return {type:"flex_field",cardinality:"MANY",path:e,value:o.map(s=>oi(s,r,i))}},oi=(e,t,n)=>{if(Be(e)){let r=e;if(r.$op==="create"&&r.$thing){let i=t.schema[r.$thing];if(!i)throw new Error(`Thing '${r.$thing}' not found in schema`);let o=st(r,i,n??null,null,t),s=t.mutation.creates.find(a=>a.name===o);return new RecordId(s.thing,s.id)}}return kn(e,t)},kn=(e,t)=>{if(e==null)return null;if(typeof e=="string"){let n=/^([^:]+):(_:.+)$/.exec(e);if(n){let[,i,o]=n,s=t.tempIdMap.get(o);if(s)return new RecordId(i,s.id)}let r=at(e);return r&&t.schema[r.thing]?new RecordId(r.thing,r.id):e}if(typeof e=="number"||typeof e=="boolean"||e instanceof Date||e instanceof RecordId)return e;if(Be(e)){let n=e;if(n.$op&&n.$op!=="link"&&n.$op!=="create")throw new Error(`Flex fields do not support '$op: ${n.$op}' operations. Use link operations instead.`);let r=Object.keys(n);if(r.length===2&&n.$thing&&n.$id||r.length===3&&n.$thing&&n.$id&&n.$op==="link")return new RecordId(n.$thing,n.$id);if(r.length===1&&n.$ref&&typeof n.$ref=="string"){let o=at(n.$ref);if(o)return new RecordId(o.thing,o.id)}let i={};for(let[o,s]of Object.entries(n))i[o]=kn(s,t);return i}return Array.isArray(e)?e.map(n=>kn(n,t)):e},Pa=(e,t,n,r,i,o)=>{if(n.cardinality==="ONE"&&r.$op==="update"&&Be(t)&&!Array.isArray(t)&&!t.$op&&!t.$id&&!t.$tempId&&Wt(t))throw new Error(`Please specify if it is a create or an update. Path: $root.0.${e}`);let s=o.schema[n.opposite.thing],a=s?.subTypes?.length?s.subTypes:void 0;if(typeof t=="string"){let m=An(t,n,a,o);return n.cardinality==="ONE"?{type:"role_field",cardinality:"ONE",path:e,ref:m}:{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:[m]}}if(Array.isArray(t)&&t.length>0&&t.every(m=>typeof m=="string")){let m=t.map(h=>An(h,n,a,o));return {type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:m}}let l=Array.isArray(t)?t:[t],d=[],c=[],p=[],u=false,f=false;for(let m of l){if(!Be(m)){d.push(An(m,n,a,o));continue}let h=m,y=h.$op;if(y==="create"||!y&&Wt(h)){let $=h.$thing?o.schema[h.$thing]:o.schema[n.opposite.thing];if(!$)throw new Error(`Thing '${n.opposite.thing}' not found in schema`);h.$thing||(h.$thing=$.name),h.$op||(h.$op="create");let g=st(h,$,i,null,o),B=o.mutation.creates.find(E=>E.name===g);d.push({thing:B.thing,id:B.id});}else if(y==="link"){if(u=true,h.$id){let $=Array.isArray(h.$id)?h.$id:[h.$id];for(let g of $)c.push(Mn(g,h,n,o));}else if(h.$tempId){let $=o.tempIdMap.get(h.$tempId);if(!$)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(h.$tempId).replace(/^_:/,"")}`);c.push($);}}else if(y==="unlink")if(u=true,h.$id){let $=Array.isArray(h.$id)?h.$id:[h.$id];for(let g of $)p.push(Mn(g,h,n,o));}else f=true;else if(y==="update"){let $=h.$thing?o.schema[h.$thing]:o.schema[n.opposite.thing];if(!$)throw new Error(`Thing '${n.opposite.thing}' not found`);h.$thing||(h.$thing=$.name),Ut(h,$,i,e,o,n.cardinality);}else if(y==="delete"){let $=h.$thing?o.schema[h.$thing]:o.schema[n.opposite.thing];if(!$)throw new Error(`Thing '${n.opposite.thing}' not found`);h.$thing||(h.$thing=$.name),Mt(h,$,i,e,o,n.cardinality);}else if(!y&&!Wt(h)){if(h.$tempId){let $=o.tempIdMap.get(h.$tempId);if(!$)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(h.$tempId).replace(/^_:/,"")}`);d.push($);}else if(h.$id){let $=Array.isArray(h.$id)?h.$id:[h.$id];for(let g of $)d.push(Mn(g,h,n,o));}}}if(n.cardinality==="ONE")return d.length>0?{type:"role_field",cardinality:"ONE",path:e,ref:d[0]}:c.length>0?{type:"role_field",cardinality:"ONE",path:e,ref:c[0]}:void 0;if(u)return f&&c.length>0?{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:c}:f?{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:[]}:{type:"role_field",cardinality:"MANY",op:"patch",path:e,links:[...c],unlinks:[...p]};if(d.length>0)return r.$op==="update"?{type:"role_field",cardinality:"MANY",op:"patch",path:e,links:d,unlinks:[]}:{type:"role_field",cardinality:"MANY",op:"replace",path:e,refs:d}},Mn=(e,t,n,r)=>{let i=t.$thing??n.opposite.thing,o=r.schema[i],s=o?.subTypes?.length?o.subTypes:void 0;if(e.startsWith("_:")){let a=r.tempIdMap.get(e);if(!a)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${e.replace(/^_:/,"")}`);return a}return {thing:i,subTypes:s,id:e}},An=(e,t,n,r)=>{if(e.startsWith("_:")){let i=r.tempIdMap.get(e);if(!i)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${e.replace(/^_:/,"")}`);return i}return {thing:t.opposite.thing,subTypes:n,id:e}},Qn=(e,t,n,r,i,o,s)=>{n.target==="relation"?qa(e,t,n,r,i,o,s):xa(e,t,n,r,i,o,s);},qa=(e,t,n,r,i,o,s)=>{if(!s.schema[n.relation])throw new Error(`Relation '${n.relation}' not found`);let l=In(i,s),d=$t(l),c=hi(i,d,s),p=i.$id&&Array.isArray(i.$id)?i.$id:[c],u=Array.isArray(t)?t:[t];for(let f of u){if(typeof f=="string"){let y=at(f);si(n,c,l.name,y?.id??f,s);continue}if(!Be(f))continue;let m=f,h=m.$op;if(h==="link"){let y=m.$id?Array.isArray(m.$id)?m.$id:[m.$id]:[];if(m.$tempId){let $=s.tempIdMap.get(m.$tempId);if(!$)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(m.$tempId).replace(/^_:/,"")}`);y.push($.id);}for(let $ of y)for(let g of p)si(n,g,l.name,$,s);}else if(h==="unlink")if(m.$id){let y=Array.isArray(m.$id)?m.$id:[m.$id];for(let $ of y)for(let g of p)Va(n,g,l.name,$,s);}else za(n,c,l.name,o,s);else if(h==="update"){m.$thing||(m.$thing=n.relation);let y=s.schema[m.$thing];if(!y)throw new Error(`Thing '${m.$thing}' not found`);Ut(m,y,o,e,s,n.cardinality,true);}else if(h==="delete"){m.$thing||(m.$thing=n.relation);let y=s.schema[m.$thing];if(!y)throw new Error(`Thing '${m.$thing}' not found`);Mt(m,y,o,e,s,n.cardinality,true);}else {m.$thing||(m.$thing=n.relation),m.$op=m.$op??"create";let y=s.schema[m.$thing];if(!y)throw new Error(`Thing '${m.$thing}' not found`);{let $=s.schema[n.relation],g=$?.type==="relation"?$.fields[n.plays]:void 0;if(g?.type==="role"&&g.cardinality==="ONE")m[n.plays]=c;else if(m[n.plays]===void 0)m[n.plays]=[c];else {let B=Array.isArray(m[n.plays])?m[n.plays]:[m[n.plays]];B.push(c),m[n.plays]=B;}}st(m,y,o,null,s);}}},xa=(e,t,n,r,i,o,s)=>{if(n.cardinality==="ONE"&&i.$op==="update"&&Be(t)&&!Array.isArray(t)&&!t.$op&&!t.$id&&!t.$tempId&&Wt(t))throw new Error(`Please specify if it is a create or an update. Path: $root.0.${e}`);if(!s.schema[n.relation])throw new Error(`Relation '${n.relation}' not found`);let l=In(i,s),d=$t(l),c=hi(i,d,s),p=Array.isArray(t)?t:[t];for(let u of p){if(typeof u=="string"){let h=/^([^:]+):(_:.+)$/.exec(u);if(h){let[,$,g]=h,B=s.tempIdMap.get(g);if(B)On(n,c,l.name,$,B.id,s);else throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${g.replace(/^_:/,"")}`);continue}let y=at(u);if(y)On(n,c,l.name,y.thing,y.id,s);else if(u.startsWith("_:")){let $=s.tempIdMap.get(u);if($)zt(n,c,l.name,$.id,s);else throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${u.replace(/^_:/,"")}`)}else zt(n,c,l.name,u,s);continue}if(!Be(u))continue;let f=u,m=f.$op;if(m==="link"){let h=f.$id?Array.isArray(f.$id)?f.$id:[f.$id]:[];if(f.$tempId){let y=s.tempIdMap.get(f.$tempId);if(!y)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${String(f.$tempId).replace(/^_:/,"")}`);h.push(y.id);}if(h.length===0&&!f.$tempId){if(i.$op==="update"&&n.cardinality==="ONE")throw new Error("The query was not executed due to a failed transaction");let y=[n.opposite.thing,...s.schema[n.opposite.thing]?.subTypes??[]],$=s.schema[n.relation],g=$?.type==="relation"?$.fields[n.plays]:void 0,B=$?.type==="relation"?$.fields[n.targetRole]:void 0,E=g?.type==="role"?g.cardinality:"MANY",T=B?.type==="role"?B.cardinality:"MANY";s.mutation.linkAlls||(s.mutation.linkAlls=[]),s.mutation.linkAlls.push({oppositeThings:y,relation:n.relation,playsField:n.plays,targetRoleField:n.targetRole,playsCardinality:E,targetCardinality:T,parentThing:l.name,parentId:c});}else for(let y of h)zt(n,c,l.name,y,s);}else if(m==="unlink")if(f.$id){let h=Array.isArray(f.$id)?f.$id:[f.$id];for(let y of h)Ua(n,c,l.name,y,o,s);}else va(n,c,l.name,o,s);else if(m==="update"){let h=f.$thing?s.schema[f.$thing]:s.schema[n.opposite.thing];if(!h)throw new Error(`Thing '${n.opposite.thing}' not found`);f.$thing||(f.$thing=h.name),Ut(f,h,o,e,s,n.cardinality,true);}else if(m==="delete"){let h=f.$thing?s.schema[f.$thing]:s.schema[n.opposite.thing];if(!h)throw new Error(`Thing '${n.opposite.thing}' not found`);f.$thing||(f.$thing=h.name),Mt(f,h,o,e,s,n.cardinality,true);}else {let h=f.$thing??n.opposite.thing,y=s.schema[h];if(!y)throw new Error(`Thing '${h}' not found`);f.$thing||(f.$thing=y.name),f.$op=f.$op??"create";let $=st(f,y,o,null,s),g=s.mutation.creates.find(B=>B.name===$);zt(n,c,l.name,g.id,s);}}},si=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l={name:o,source:{type:"record_pointer",thing:a,ids:[r]}};i.mutation.matches.push(l);let d=We(e.relation,e.plays,i),c={thing:n,subTypes:i.schema[n]?.subTypes?.length?i.schema[n].subTypes:void 0,id:t},u={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:d==="ONE"?{type:"role_field",cardinality:"ONE",path:e.plays,ref:c}:{type:"role_field",cardinality:"MANY",op:"patch",path:e.plays,links:[c],unlinks:[]}}};i.mutation.updates.push(u);},Va=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l={name:o,source:{type:"record_pointer",thing:a,ids:[r]}};i.mutation.matches.push(l);let c={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:vt(e.plays,n,t,We(e.relation,e.plays,i))}};i.mutation.updates.push(c);},We=(e,t,n)=>{let r=n.schema[e];if(r?.type==="relation"){let i=r.fields[t];if(i?.type==="role")return i.cardinality}return "MANY"},vt=(e,t,n,r)=>r==="ONE"?{type:"null",path:e}:{type:"role_field",cardinality:"MANY",op:"patch",path:e,links:[],unlinks:[{thing:t,id:n}]},pi=(e,t,n)=>{for(let r of Object.values(e.fields))if(r.type==="link"&&r.target==="relation"&&r.relation===t&&r.plays===n)return r},za=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l=i.schema[n],d=l?pi(l,e.relation,e.plays):void 0;if(d){let f={name:o,parent:r,path:d.name,cardinality:d.cardinality,isComputed:true};i.mutation.subMatches.push(f);}else Wa(o,e,t,n,a,i);let c=We(e.relation,e.plays,i),u={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:vt(e.plays,n,t,c)}};i.mutation.updates.push(u);},Wa=(e,t,n,r,i,o)=>{let a=We(t.relation,t.plays,o)==="ONE"?{type:"ref",op:"IN",left:t.plays,right:[n],thing:[r],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:t.plays,right:[n],thing:[r],cardinality:"MANY"},l={name:e,source:{type:"table_scan",thing:i},filter:a};o.mutation.matches.push(l);},On=(e,t,n,r,i,o)=>{let s=Nn(),a=Fe(e.relation,o),l=o.schema[e.relation];if(!l||l.type!=="relation")throw new Error(`Relation '${e.relation}' not found`);let d=l.fields[e.plays],c=d?.type==="role"?d.cardinality:"MANY",p=o.schema[n],u=p?.subTypes?.length?p.subTypes:void 0,f=o.schema[r],m=f?.subTypes?.length?f.subTypes:void 0,h={thing:n,subTypes:u,id:t},y={thing:r,subTypes:m,id:i},$={name:a,thing:e.relation,id:s,op:"create",values:{[e.plays]:c==="ONE"?{type:"role_field",cardinality:"ONE",path:e.plays,ref:h}:{type:"role_field",cardinality:"MANY",op:"replace",path:e.plays,refs:[h]},[e.targetRole]:e.targetRoleCardinality==="ONE"?{type:"role_field",cardinality:"ONE",path:e.targetRole,ref:y}:{type:"role_field",cardinality:"MANY",op:"replace",path:e.targetRole,refs:[y]}}};$.isIntermediary=true,o.mutation.creates.push($);},zt=(e,t,n,r,i)=>{let o=i.schema[e.relation];if(!o||o.type!=="relation")throw new Error(`Relation '${e.relation}' not found`);let s=o.fields[e.targetRole];if(!s||s.type!=="role")throw new Error(`Role '${e.targetRole}' not found in relation '${e.relation}'`);let a=s.opposite.thing;On(e,t,n,a,r,i);},Ua=(e,t,n,r,i,o)=>{let s=Fe(e.relation,o),a=o.schema[e.relation];if(!a)throw new Error(`Relation '${e.relation}' not found`);let l=[e.relation,...a.subTypes],d=a.type==="relation"?a.fields[e.targetRole]:void 0,c=d?.type==="role"?d.opposite.thing:e.opposite.thing,u=We(e.relation,e.plays,o)==="ONE"?{type:"ref",op:"IN",left:e.plays,right:[t],thing:[n],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:e.plays,right:[t],thing:[n],cardinality:"MANY"},m=(d?.type==="role"?d.cardinality:"MANY")==="ONE"?{type:"ref",op:"IN",left:e.targetRole,right:[r],thing:[c],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:e.targetRole,right:[r],thing:[c],cardinality:"MANY"},h={name:s,source:{type:"table_scan",thing:l},filter:{type:"and",filters:[u,m]}};o.mutation.matches.push(h);let y=We(e.relation,e.plays,o),g={name:Fe(e.relation,o),match:s,op:"update",values:{[e.plays]:vt(e.plays,n,t,y)}};o.mutation.updates.push(g);},va=(e,t,n,r,i)=>{let o=Fe(e.relation,i),s=i.schema[e.relation];if(!s)throw new Error(`Relation '${e.relation}' not found`);let a=[e.relation,...s.subTypes],l=i.schema[n],d=l?pi(l,e.relation,e.plays):void 0;if(d){let u={name:o,parent:r,path:d.name,cardinality:d.cardinality,isComputed:true};i.mutation.subMatches.push(u);}else {let f=We(e.relation,e.plays,i)==="ONE"?{type:"ref",op:"IN",left:e.plays,right:[t],thing:[n],cardinality:"ONE"}:{type:"ref",op:"CONTAINSANY",left:e.plays,right:[t],thing:[n],cardinality:"MANY"},m={name:o,source:{type:"table_scan",thing:a},filter:f};i.mutation.matches.push(m);}let p={name:Fe(e.relation,i),match:o,op:"update",values:{[e.plays]:vt(e.plays,n,t,We(e.relation,e.plays,i))}};i.mutation.updates.push(p);},fi=(e,t)=>{for(let n of e.creates){let r=t[n.thing];r&&ai(n.values,r,"create");}for(let n of e.updates){let r=e.matches.find(s=>s.name===n.match)??e.subMatches.find(s=>s.name===n.match);if(!r)continue;let i;if("source"in r){let s=r.source;s.type!=="subquery"&&(i=s.thing[0]);}if(!i)continue;let o=t[i];o&&ai(n.values,o,"update");}},ai=(e,t,n)=>{let r=t.idFields[0];for(let i of Object.values(t.fields)){if(i.type!=="data"||i.isVirtual||!i.validations)continue;let o=e[i.name];if(n==="create"&&i.validations.required&&i.name!==r&&o===void 0)throw new Error(`[Validations] Required field "${i.name}" is missing.`);if(!o||o.type!=="data_field")continue;let s=o.cardinality==="MANY"?o.value:[o.value];for(let a of s)if(a!==null){if(i.validations.enum&&!i.validations.enum.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${i.name}".`);if(i.validations.fn)try{if(!i.validations.fn(a))throw new Error(`[Validations:attribute:${i.name}] Failed validation function.`)}catch(l){if(l instanceof Error&&l.message.startsWith("[Validations:attribute:"))throw l;let d=l instanceof Error?l.message:String(l);throw new Error(`[Validations:attribute:${i.name}] ${d}`)}}}},Ha=e=>{let t=new Map;for(let a of e.creates)t.set(a.name,a);let n=new Map;for(let a of e.creates){let l=new Set;for(let d of Object.values(a.values))Ya(d,t,l);n.set(a.name,l);}let r=[],i=new Set,o=new Set,s=a=>{if(i.has(a))return;if(o.has(a)){Ka(a,n,e);return}o.add(a);let l=n.get(a);if(l)for(let c of l)t.has(c)&&s(c);o.delete(a),i.add(a);let d=t.get(a);d&&r.push(d);};for(let a of e.creates)s(a.name);e.creates=r;},mt=(e,t,n,r)=>r.id!==t?false:r.thing===e||(n?.includes(r.thing)??false),Ya=(e,t,n)=>{if(e.type==="role_field"){if(e.cardinality==="ONE")for(let[r,i]of t)mt(e.ref.thing,e.ref.id,e.ref.subTypes,i)&&n.add(r);else if("refs"in e)for(let r of e.refs)for(let[i,o]of t)mt(r.thing,r.id,r.subTypes,o)&&n.add(i);else if("links"in e)for(let r of e.links)for(let[i,o]of t)mt(r.thing,r.id,r.subTypes,o)&&n.add(i);}else if(e.type==="ref_field"){let r=e.cardinality==="ONE"?[e.value]:e.value;for(let i of r){let o=at(i);if(o)for(let[s,a]of t)a.thing===o.thing&&a.id===o.id&&n.add(s);}}},Ka=(e,t,n)=>{let r=t.get(e);if(r)for(let i of r){let o=t.get(i);if(o?.has(e)){let s=n.creates.find(a=>a.name===i);if(!s)return;for(let[a,l]of Object.entries(s.values))if(Ja(l,e,n)){let d={name:Za(i),match:i,op:"update",values:{[a]:l}};n.updates.push(d),delete s.values[a],o.delete(e);return}}}},Ja=(e,t,n)=>{let r=n.creates.find(i=>i.name===t);if(!r)return false;if(e.type==="role_field"){if(e.cardinality==="ONE")return mt(e.ref.thing,e.ref.id,e.ref.subTypes,r);if("refs"in e)return e.refs.some(i=>mt(i.thing,i.id,i.subTypes,r));if("links"in e)return e.links.some(i=>mt(i.thing,i.id,i.subTypes,r))}return false},Za=e=>`${e}_deferred`,In=(e,t)=>{let n=t.schema[e.$thing];if(!n)throw new Error(`Thing '${e.$thing}' not found in schema`);return n},$t=e=>{if(e.idFields.length>1)throw new Error(`Composite id fields are not supported for '${e.name}'`);return e.idFields[0]},hi=(e,t,n)=>{if(e.$id)return Array.isArray(e.$id)?e.$id[0]:e.$id;if(e[t])return e[t];if(e.$tempId){let r=n.tempIdMap.get(e.$tempId);if(r)return r.id}if(e.$thing){let r=[...n.mutation.creates].reverse().find(i=>i.thing===e.$thing);if(r)return r.id}return ""},Xa=(e,t,n)=>{if(n[e]!==void 0){let r=Array.isArray(n.$id)?n.$id[0]:n.$id;if(r!==void 0&&n[e]===r){delete n[e];return}throw new Error(`Cannot mutate id field '${e}' on '${t}'. Use '$id' to identify the record instead.`)}},Wt=e=>Object.keys(e).some(t=>!t.startsWith("$")),Be=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date),li=e=>Be(e)&&Object.keys(e).some(t=>t.startsWith("$")),at=e=>{if(/\s/.test(e))return;let t=/^([^:]+):([^:]+)$/.exec(e);if(!t)return;let[,n,r]=t;if(!(!n||!r)&&n!=="_")return {thing:n,id:r}},Ga=(e,t)=>{let n=new Map;for(let[r,i]of Object.entries(e)){if(r.startsWith("$")||i===null||i===void 0)continue;let o=t.fields[r];if(o?.type==="link"){let s=n.get(o.relation);if(s&&s!==o.target)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");n.set(o.relation,o.target);}}};var yi=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,r])=>t(n,r))))[0],me=(e,t)=>{let n=Reflect.ownKeys(e).map(r=>[r,e[r]]);return Object.fromEntries(n.filter(([r,i])=>{let[o,s]=tryit(()=>t(r,i))();return o?false:s}))},oe=(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)}`)},Ht=(e,t)=>{let n=e.dataFields?.find(o=>o.path===t);if(e.idFields?.includes(t)){if(!n)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",n]}if(n)return ["dataField",n];let r=e.linkFields?.find(o=>o.path===t);if(r)return ["linkField",r];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`)},Yt=(e,t)=>{let n=z(e,t);if(n?.idFields?.length&&n?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${n?.idFields}`);let[r]=n.idFields;return r},gi=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},_n=(e,t,n)=>{let r=z(e,t),i=r.linkFields?.find(l=>l.path===n);if(i)return i;let o=r.dataFields?.find(l=>l.path===n);if(o)return o;let s="roles"in r?r.roles?.[n]:void 0;if(s)return s;let a="refFields"in r?r.refFields?.[n]:void 0;if(a)return a;throw new Error(`Field ${n} not found in schema`)},jn=(e,t,n)=>_n(e,t,n)?.cardinality,$e=(e,t)=>{let n=e.dataFields?.map(h=>h.path)||[],r=e.linkFields?.map(h=>h.path)||[],i="refFields"in e?listify(e.refFields,h=>h):[],o="roles"in e?listify(e.roles,h=>h):[],s=[...n||[],...r||[],...o||[],...i||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...s];if(!t)return {fields:s,dataFields:n,roleFields:o,linkFields:r};let d=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!s.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!s.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),c=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&n?.includes(h)):[],p=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...r||[]].includes(h)):[],u=[...d,...c].filter(h=>!h?.startsWith("%")).filter(h=>!l.includes(h)).filter(h=>h),f=t.$filter?me(t.$filter,(h,y)=>c.includes(h)):{},m=t.$filter?me(t.$filter,(h,y)=>p.includes(h)):{};return {fields:s,dataFields:n,roleFields:o,linkFields:r,refFields:i,usedFields:d,usedLinkFields:r.filter(h=>d.includes(h)),usedRoleFields:o.filter(h=>d.includes(h)),usedDataFields:n.filter(h=>d.includes(h)),usedRefFields:i.filter(h=>d.includes(h)),unidentifiedFields:u,...c.length?{localFilters:f}:{},...p.length?{nestedFilters:m}:{}}};var Ei=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Bi=(e,t,n)=>{let i=(n.nodePath||"").split("."),o=isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?getNodeByPath(e,o):{}},Ue=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var Kt=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,n={};for(let[r,i]of Object.entries(t))n[r]=isDraft(i)?current(i):i;return n}return e},Ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},N=(e,t)=>{let n="";for(let r=0;r<t;r++)n+=" ";return `${n}${e}`},ve=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),yt=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)();var Fi=(e,t)=>{let n=[],r=e.cardinality==="MANY"?0:1;e.cardinality==="ONE"&&n.push("array::first("),n.push(bi(e.projection,r,t)),n.push(Lt(e.source,r,t));let i=e.filter&&Le(e.filter,t);return i&&n.push(J(`WHERE ${i}`,r)),e.sort&&e.sort.length>0&&n.push(Ri(e.sort,r)),e.limit!==void 0&&n.push(J(`LIMIT ${e.limit}`,r)),e.offset!==void 0&&n.push(J(`START ${e.offset}`,r)),e.cardinality==="ONE"&&n.push(")"),n.join(`
68
+ `)},bi=(e,t,n)=>{let r=[],i=t+1;for(let s of e.fields)s.type==="metadata"?r.push(il(s,i)):s.type==="data"?r.push(ol(s,i)):s.type==="ref"||s.type==="computed_ref"?r.push(sl(s,i)):s.type==="nested_ref"||s.type==="nested_computed_ref"?r.push(al(s,i,n)):s.type==="flex"&&r.push(ll(s,i));let o=[];return o.push(J("SELECT",t)),o.push(r.join(`,
69
69
  `)),o.join(`
70
- `)},rl=(e,t)=>{if(e.path==="$id")return J(`record::id(id) AS ${ae(e.alias??"$id")}`,t);if(e.path==="$thing")return J(`record::tb(id) AS ${ae(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},il=(e,t)=>{if(e.path==="id")return J(`record::id(id) AS ${ae(e.alias??"id")}`,t);let n=ae(e.path);return e.alias?J(`${n} AS ${ae(e.alias)}`,t):J(n,t)},ol=(e,t)=>{let{path:n,alias:r}=e,i=e.type==="computed_ref"?be(n):ae(n),o=ae(r||n),s=e.fieldCardinality==="ONE"?`SELECT VALUE record::id(id) FROM [$this.${i}] WHERE id IS NOT NONE`:`SELECT VALUE record::id(id) FROM $this.${i}[*]`;return e.resultCardinality==="ONE"?J(`array::first(${s}) AS ${o}`,t):J(`(${s}) AS ${o}`,t)},sl=(e,t,n)=>{let r=[];e.resultCardinality==="MANY"?r.push(J("(",t)):r.push(J("array::first(",t)),r.push(Fi(e.projection,t+1,n));let i=e.filter?Le(e.filter,n):void 0,o=e.type==="nested_computed_ref"?be(e.path):ae(e.path);e.fieldCardinality==="ONE"?r.push(J(`FROM $this.${o}`,t+1)):r.push(J(`FROM $this.${o}[*]`,t+1));let s=[];if(e.ids&&e.ids.length>0){let a=e.ids.map(l=>`$${Se(n,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&&r.push(J(`WHERE ${s.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&r.push(bi(e.sort,t+1)),e.limit!==void 0&&r.push(J(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&r.push(J(`START ${e.offset}`,t+1)),r.push(J(`) AS ${ae(e.alias||e.path)}`,t)),r.join(`
71
- `)},al=(e,t)=>{let{path:n,alias:r,cardinality:i}=e,o=ae(n),s=ae(r||n);return J(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)},At=(e,t,n)=>{let r=[];switch(e.type){case "table_scan":{r.push(J(`FROM ${e.thing.map(ae)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>{let a=Se(n,o),l=Se(n,s);return `type::record($${a}, $${l})`})).join(", ");r.push(J(`FROM ${i}`,t));break}case "subquery":{r.push(J(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t));let i=e.isComputedPath?be(e.oppositePath):ae(e.oppositePath);r.push(J(`SELECT VALUE ${i}`,t+1)),r.push(At(e.source,t+1,n));let o=e.filter?Le(e.filter,n):void 0;o&&r.push(J(`WHERE ${o}`,t+1)),r.push(J(e.cardinality==="MANY"?"))":")",t));break}}return r.join(`
72
- `)},Le=(e,t,n)=>{let r=n??"";switch(e.type){case "scalar":{let i=e.left==="id"?`record::id(${r}id)`:`${r}${ae(e.left)}`,o=Se(t,e.right);return `${i} ${e.op} $${o}`}case "list":{let i=e.right.map(s=>`$${Se(t,s)}`).join(", ");return `${`${r}${ae(e.left)}`} ${e.op} [${i}]`}case "ref":case "biref":case "computed_biref":{let i=e.type==="computed_biref"?be(e.left):ae(e.left),o=e.left==="id"?`record::id(${r}id)`:`${r}${i}`;if(e.thing){let s=e.thing.flatMap(a=>e.right.map(l=>{let d=Se(t,a),c=Se(t,l);return `type::record($${d}, $${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}) = $${Se(t,e.right[0])}`;if(e.op==="NOT IN")return `${o} && record::id(${o}) != $${Se(t,e.right[0])}`;if(e.op==="CONTAINSANY")return `$${Se(t,e.right[0])} IN (${o} ?: []).map(|$i| record::id($i))`;if(e.op==="CONTAINSNONE")return `$${Se(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=>`$${Se(t,s)}`).join(", ")}]`}case "null":return e.emptyIsArray?e.op==="IS"?`array::len(${r}${ae(e.left)}) = 0`:`array::len(${r}${ae(e.left)}) > 0`:`${r}${ae(e.left)} ${e.op} NONE`;case "and":{let i=e.filters.map(o=>{let s=Le(o,t,n);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=Le(o,t,n);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" OR "):void 0}case "not":{let i=Le(e.filter,t,n);return i?`NOT(${i})`:void 0}case "falsy":return "false";case "nested_ref":case "nested_computed_ref":{let i=e.type==="nested_computed_ref"?be(e.path):ae(e.path),o=`${r}${i}`;if(e.cardinality==="ONE")return Le(e.filter,t,`${o}.`);let s=Le(e.filter,t);return s?`${o}[WHERE ${s}]`:void 0}}},bi=(e,t)=>{let n=e.map(r=>`${ae(r.field)} ${r.desc?"DESC":"ASC"}`).join(", ");return J(`ORDER BY ${n}`,t)},J=(e,t)=>`${" ".repeat(t*2)}${e}`,Se=(e,t)=>{let n=$t();for(;e[n]!==void 0;)n=$t();return e[n]=t,n},ae=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var Ti=(e,t,n,r)=>{let i=[],o=[],s=n.mutation?.ignoreNonexistingThings??false,a=new Set;for(let d of e.updates)a.add(d.match);for(let d of e.subMatches)a.has(d.name)&&a.add(d.parent);let l=new Set;for(let d of e.creates)l.add(`${d.thing}:${d.id}`);for(let d of e.matches){let c=!s&&a.has(d.name);ll(d,i,o,t,c,l);}for(let d of e.subMatches)cl(d,i,o,t);for(let d of e.creates)ul(d,i,o,t,e,r);for(let d of e.updates)pl(d,i,o,t,e);for(let d=e.deletes.length-1;d>=0;d--)fl(e.deletes[d],i,o,t,e,r);if(e.linkAlls)for(let d of e.linkAlls)ml(d,i,t);for(let d of o)d.type==="create"?(d.resultIndex=i.length,i.push(`RETURN $${d.name};`)):d.type==="update"?(d.resultIndex=i.length,i.push(`RETURN $${d.name}_result;`)):d.type==="delete"&&(d.resultIndex=i.length,i.push(`RETURN $${d.name}_result;`));return {surql:i.join(`
73
- `),stmtMap:o}},ll=(e,t,n,r,i,o)=>{let s=e.source,a=e.filter?Le(e.filter,r):void 0;if(s.type==="record_pointer"&&s.ids.every(d=>s.thing.some(c=>o.has(`${c}:${d}`)))&&s.type==="record_pointer"){let d=s.thing.flatMap(c=>s.ids.map(p=>{let u=ye(r,c),f=ye(r,p);return `type::record($${u}, $${f})`}));t.push(`LET $${e.name} = [${d.join(", ")}];`),n.push({type:"match",name:e.name});}else if(s.type==="record_pointer"&&i){let d=a?`${e.name}_ptr`:e.name,c=[];if(c.push("SELECT VALUE id"),c.push(At(s,1,r)),t.push(`LET $${d} = ${c.join(`
70
+ `)},il=(e,t)=>{if(e.path==="$id")return J(`record::id(id) AS ${ae(e.alias??"$id")}`,t);if(e.path==="$thing")return J(`record::tb(id) AS ${ae(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},ol=(e,t)=>{if(e.path==="id")return J(`record::id(id) AS ${ae(e.alias??"id")}`,t);let n=ae(e.path);return e.alias?J(`${n} AS ${ae(e.alias)}`,t):J(n,t)},sl=(e,t)=>{let{path:n,alias:r}=e,i=e.type==="computed_ref"?be(n):ae(n),o=ae(r||n),s=e.fieldCardinality==="ONE"?`SELECT VALUE record::id(id) FROM [$this.${i}] WHERE id IS NOT NONE`:`SELECT VALUE record::id(id) FROM $this.${i}[*]`;return e.resultCardinality==="ONE"?J(`array::first(${s}) AS ${o}`,t):J(`(${s}) AS ${o}`,t)},al=(e,t,n)=>{let r=[];e.resultCardinality==="MANY"?r.push(J("(",t)):r.push(J("array::first(",t)),r.push(bi(e.projection,t+1,n));let i=e.filter?Le(e.filter,n):void 0,o=e.type==="nested_computed_ref"?be(e.path):ae(e.path);e.fieldCardinality==="ONE"?r.push(J(`FROM $this.${o}`,t+1)):r.push(J(`FROM $this.${o}[*]`,t+1));let s=[];if(e.ids&&e.ids.length>0){let a=e.ids.map(l=>`$${Se(n,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&&r.push(J(`WHERE ${s.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&r.push(Ri(e.sort,t+1)),e.limit!==void 0&&r.push(J(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&r.push(J(`START ${e.offset}`,t+1)),r.push(J(`) AS ${ae(e.alias||e.path)}`,t)),r.join(`
71
+ `)},ll=(e,t)=>{let{path:n,alias:r,cardinality:i}=e,o=ae(n),s=ae(r||n);return J(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)},Lt=(e,t,n)=>{let r=[];switch(e.type){case "table_scan":{r.push(J(`FROM ${e.thing.map(ae)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>{let a=Se(n,o),l=Se(n,s);return `type::record($${a}, $${l})`})).join(", ");r.push(J(`FROM ${i}`,t));break}case "subquery":{r.push(J(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t));let i=e.isComputedPath?be(e.oppositePath):ae(e.oppositePath);r.push(J(`SELECT VALUE ${i}`,t+1)),r.push(Lt(e.source,t+1,n));let o=e.filter?Le(e.filter,n):void 0;o&&r.push(J(`WHERE ${o}`,t+1)),r.push(J(e.cardinality==="MANY"?"))":")",t));break}}return r.join(`
72
+ `)},Le=(e,t,n)=>{let r=n??"";switch(e.type){case "scalar":{let i=e.left==="id"?`record::id(${r}id)`:`${r}${ae(e.left)}`,o=Se(t,e.right);return `${i} ${e.op} $${o}`}case "list":{let i=e.right.map(s=>`$${Se(t,s)}`).join(", ");return `${`${r}${ae(e.left)}`} ${e.op} [${i}]`}case "ref":case "biref":case "computed_biref":{let i=e.type==="computed_biref"?be(e.left):ae(e.left),o=e.left==="id"?`record::id(${r}id)`:`${r}${i}`;if(e.thing){let s=e.thing.flatMap(a=>e.right.map(l=>{let d=Se(t,a),c=Se(t,l);return `type::record($${d}, $${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}) = $${Se(t,e.right[0])}`;if(e.op==="NOT IN")return `${o} && record::id(${o}) != $${Se(t,e.right[0])}`;if(e.op==="CONTAINSANY")return `$${Se(t,e.right[0])} IN (${o} ?: []).map(|$i| record::id($i))`;if(e.op==="CONTAINSNONE")return `$${Se(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=>`$${Se(t,s)}`).join(", ")}]`}case "null":return e.emptyIsArray?e.op==="IS"?`array::len(${r}${ae(e.left)}) = 0`:`array::len(${r}${ae(e.left)}) > 0`:`${r}${ae(e.left)} ${e.op} NONE`;case "and":{let i=e.filters.map(o=>{let s=Le(o,t,n);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=Le(o,t,n);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" OR "):void 0}case "not":{let i=Le(e.filter,t,n);return i?`NOT(${i})`:void 0}case "falsy":return "false";case "nested_ref":case "nested_computed_ref":{let i=e.type==="nested_computed_ref"?be(e.path):ae(e.path),o=`${r}${i}`;if(e.cardinality==="ONE")return Le(e.filter,t,`${o}.`);let s=Le(e.filter,t);return s?`${o}[WHERE ${s}]`:void 0}}},Ri=(e,t)=>{let n=e.map(r=>`${ae(r.field)} ${r.desc?"DESC":"ASC"}`).join(", ");return J(`ORDER BY ${n}`,t)},J=(e,t)=>`${" ".repeat(t*2)}${e}`,Se=(e,t)=>{let n=yt();for(;e[n]!==void 0;)n=yt();return e[n]=t,n},ae=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var wi=(e,t,n,r)=>{let i=[],o=[],s=n.mutation?.ignoreNonexistingThings??false,a=new Set;for(let d of e.updates)a.add(d.match);for(let d of e.subMatches)a.has(d.name)&&a.add(d.parent);let l=new Set;for(let d of e.creates)l.add(`${d.thing}:${d.id}`);for(let d of e.matches){let c=!s&&a.has(d.name);cl(d,i,o,t,c,l);}for(let d of e.subMatches)dl(d,i,o,t);for(let d of e.creates)pl(d,i,o,t,e,r);for(let d of e.updates)fl(d,i,o,t,e);for(let d=e.deletes.length-1;d>=0;d--)hl(e.deletes[d],i,o,t,e,r);if(e.linkAlls)for(let d of e.linkAlls)$l(d,i,t);for(let d of o)d.type==="create"?(d.resultIndex=i.length,i.push(`RETURN $${d.name};`)):d.type==="update"?(d.resultIndex=i.length,i.push(`RETURN $${d.name}_result;`)):d.type==="delete"&&(d.resultIndex=i.length,i.push(`RETURN $${d.name}_result;`));return {surql:i.join(`
73
+ `),stmtMap:o}},cl=(e,t,n,r,i,o)=>{let s=e.source,a=e.filter?Le(e.filter,r):void 0;if(s.type==="record_pointer"&&s.ids.every(d=>s.thing.some(c=>o.has(`${c}:${d}`)))&&s.type==="record_pointer"){let d=s.thing.flatMap(c=>s.ids.map(p=>{let u=ye(r,c),f=ye(r,p);return `type::record($${u}, $${f})`}));t.push(`LET $${e.name} = [${d.join(", ")}];`),n.push({type:"match",name:e.name});}else if(s.type==="record_pointer"&&i){let d=a?`${e.name}_ptr`:e.name,c=[];if(c.push("SELECT VALUE id"),c.push(Lt(s,1,r)),t.push(`LET $${d} = ${c.join(`
74
74
  `)};`),n.push({type:"match",name:d}),t.push(`IF array::len($${d}) != ${s.ids.length} { THROW "Record not found" };`),n.push({type:"assertion",name:d}),a){let p=[];p.push("SELECT VALUE id"),p.push(J(`FROM $${d}`,1)),p.push(J(`WHERE ${a}`,1)),t.push(`LET $${e.name} = ${p.join(`
75
- `)};`),n.push({type:"filter_submatch",name:e.name});}}else {let d=[];d.push("SELECT VALUE id"),d.push(At(s,1,r)),a&&d.push(J(`WHERE ${a}`,1)),t.push(`LET $${e.name} = ${d.join(`
76
- `)};`),n.push({type:"match",name:e.name});}},cl=(e,t,n,r)=>{let i=e.isComputed?be(e.path):Y(e.path),o=[];if(e.ids&&e.ids.length>0)if(e.ids.length===1){let l=ye(r,e.ids[0]);o.push(`record::id(id) = $${l}`);}else {let l=e.ids.map(d=>`$${ye(r,d)}`);o.push(`record::id(id) IN [${l.join(", ")}]`);}if(e.filter){let l=Array.isArray(e.filter)?e.filter:[e.filter];for(let d of l){let c=Le(d,r);c&&o.push(c);}}let s=o.length>0?` WHERE ${o.join(" AND ")}`:"",a=e.cardinality==="MANY"?"[*]":"";t.push(`LET $${e.name} = SELECT VALUE id FROM array::flatten($${e.parent}.${i}${a})${s};`),n.push({type:"submatch",name:e.name});},dl=(e,t,n,r,i,o,s,a)=>{let l=s[e];if(!(!l||l.type!=="relation"))for(let[d,c]of Object.entries(t)){if(c.type!=="role_field")continue;let p=l.fields[d];if(p?.type!=="role")continue;let f=s[p.opposite.thing]?.fields[p.opposite.path];if(f?.type!=="link"||f.cardinality!=="ONE")continue;let m=c.cardinality==="MANY"&&("links"in c||"refs"in c);if(!a&&p.cardinality!=="ONE"&&!m)continue;let y=(c.cardinality==="ONE"?[c.ref]:"refs"in c?c.refs:"links"in c?c.links:[]).filter(g=>!o.creates.some(B=>B.thing===g.thing&&B.id===g.id));if(y.length===0)continue;let $=Y(d);for(let g of y){let B=Lt(g,i,o);p.cardinality==="ONE"?r.push(`UPDATE ${n} SET ${$} = NONE WHERE ${$} = ${B};`):r.push(`UPDATE ${n} SET ${$} -= [${B}] WHERE ${$} CONTAINSANY [${B}];`);}}},ul=(e,t,n,r,i,o)=>{let s=Y(e.thing);o&&dl(e.thing,e.values,s,t,r,i,o,e.isIntermediary);let a=[];for(let[p,u]of Object.entries(e.values)){let f=Si(p,u,r,i);a.push(...f);}let l=ye(r,e.thing),d=ye(r,e.id),c=a.length>0?` SET ${a.join(", ")}`:"";t.push(`LET $${e.name} = CREATE ONLY type::record($${l}, $${d})${c} RETURN AFTER;`),n.push({type:"create",name:e.name,op:"create",thing:e.thing,tempId:e.tempId,isIntermediary:e.isIntermediary});},pl=(e,t,n,r,i,o)=>{let s=[];for(let[c,p]of Object.entries(e.values)){let u=Si(c,p,r,i);s.push(...u);}if(s.length===0)return;let a=`${e.name}_result`;i.creates.some(c=>c.name===e.match)?t.push(`LET $${a} = UPDATE $${e.match}.id SET ${s.join(", ")} RETURN AFTER;`):t.push(`LET $${a} = UPDATE $${e.match} SET ${s.join(", ")} RETURN AFTER;`);let d=wi(e.match,i);n.push({type:"update",name:e.name,op:"update",thing:d});},wi=(e,t)=>{let n=t.creates.find(i=>i.name===e);if(n)return n.thing;let r=t.matches.find(i=>i.name===e);if(r&&r.source.type!=="subquery")return r.source.thing[0]},fl=(e,t,n,r,i,o)=>{let s=`${e.name}_result`;t.push(`LET $${s} = DELETE $${e.match} RETURN BEFORE;`);let a=wi(e.match,i);if(o&&a){let l=o[a];if(l?.type==="entity"){for(let d of Object.values(l.fields))if(d.type==="link"&&d.target==="role"){let c=Y(d.relation),p=Y(d.plays);t.push(`DELETE FROM ${c} WHERE ${p} IS NONE;`);}}}n.push({type:"delete",name:e.name,op:"delete",thing:a});},Si=(e,t,n,r)=>{let i=Y(e);switch(t.type){case "null":return [`${i} = NONE`];case "empty":return [`${i} = []`];case "data_field":if(t.cardinality==="MANY"){let o=t.value.map(s=>`$${ye(n,s)}`);return [`${i} = [${o.join(", ")}]`]}return [`${i} = $${ye(n,t.value)}`];case "ref_field":{if(t.cardinality==="ONE")return [`${i} = ${Ri(t.value,n)}`];let o=t.value.map(s=>Ri(s,n));return [`${i} = [${o.join(", ")}]`]}case "flex_field":return [`${i} = $${ye(n,(t.cardinality==="ONE",t.value))}`];case "role_field":return hl(e,t,n,r);default:return []}},hl=(e,t,n,r)=>{let i=Y(e),o=[];if(t.cardinality==="ONE"){let s=Lt(t.ref,n,r);return o.push(`${i} = ${s}`),o}if("refs"in t){if(t.refs.length===0)o.push(`${i} = []`);else {let s=t.refs.map(a=>Lt(a,n,r));o.push(`${i} = [${s.join(", ")}]`);}return o}if("links"in t){if(t.links.length>0){let s=t.links.map(a=>Lt(a,n,r));o.push(`${i} += [${s.join(", ")}]`);}if(t.unlinks.length>0){let s=t.unlinks.map(a=>Lt(a,n,r));o.push(`${i} -= [${s.join(", ")}]`);}return o}return o},Lt=(e,t,n)=>{let r=e.subTypes?[e.thing,...e.subTypes]:[e.thing],i=n.creates.find(a=>r.includes(a.thing)&&a.id===e.id);if(i)return `$${i.name}.id`;if(e.subTypes&&e.subTypes.length>0){let a=[e.thing,...e.subTypes],l=ye(t,e.id);return `array::first(SELECT VALUE id FROM [${a.map(c=>`type::record($${ye(t,c)}, $${l})`).join(", ")}])`}let o=ye(t,e.thing),s=ye(t,e.id);return `type::record($${o}, $${s})`},Ri=(e,t)=>{let n=e.split(":");if(n.length!==2)throw new Error(`Invalid record reference: ${e}`);let[r,i]=n,o=ye(t,r),s=ye(t,i);return `type::record($${o}, $${s})`},ml=(e,t,n)=>{let r=e.oppositeThings.map(u=>Y(u)).join(", "),i=Y(e.relation),o=ye(n,e.parentThing),s=ye(n,e.parentId),a=`type::record($${o}, $${s})`,l=e.playsCardinality==="ONE"?a:`[${a}]`,d=e.targetCardinality==="ONE"?"$item":"[$item]",c=Y(e.playsField),p=Y(e.targetRoleField);t.push(`FOR $item IN (SELECT VALUE id FROM ${r}) { CREATE ${i} SET ${c} = ${l}, ${p} = ${d}; };`);},ye=(e,t)=>{let n=$t();for(;e[n]!==void 0;)n=$t();return e[n]=t,n};var Mi=(e,t,n)=>{if(Array.isArray(e)){for(let r of e)jn(r,null,t,n);return e}return jn(e,null,t,n),e},jn=(e,t,n,r)=>{$l(e,n),Bl(e,t,n,r),yl(e,n,r),Fl(e,t,n,r);},$l=(e,t)=>{let n=e.$thing?t[e.$thing]:void 0;if(n&&e.$op==="create")for(let r of Object.values(n.fields))r.type==="data"&&(r.isVirtual||r.default&&e[r.name]===void 0&&(r.default.type==="value"?e[r.name]=r.default.value:r.default.type==="fn"&&(e[r.name]=r.default.fn(e))));if(n)for(let r of Object.values(n.fields)){if(r.type!=="data"||r.contentType!=="DATE"&&r.contentType!=="TIME")continue;let i=e[r.name];if(typeof i=="string"){let o=new Date(i);Number.isNaN(o.getTime())||(e[r.name]=o);}}},yl=(e,t,n)=>{let r=e.$thing?t[e.$thing]:void 0;for(let[i,o]of Object.entries(e)){if(i.startsWith("$")||o==null)continue;if(r){let a=r.fields[i];if(a&&a.type!=="role"&&a.type!=="link"&&a.type!=="ref")continue}let s=a=>{if(!bl(a))return;let l=a;gl(l,e,i,t),l.$thing&&jn(l,e,t,n);};if(Array.isArray(o))for(let a of o)s(a);else s(o);}},gl=(e,t,n,r)=>{if(e.$thing)return;let i=t.$thing?r[t.$thing]:void 0;if(!i)return;let o=i.fields[n];if(!o)return;let s;if(o.type==="role"?s=o.opposite.thing:o.type==="link"&&(s=o.target==="relation"?o.relation:o.opposite.thing),!s)return;let a=r[s];if(!a)return;let l=Object.keys(e).filter(c=>!c.startsWith("$"));if((e.$op!==void 0||e.$id!==void 0||l.length>0&&l.some(c=>c in a.fields||c===a.idFields[0]))&&(e.$thing=s,!e.$op)){let c=e.$id!==void 0,p=l.length>0;c&&p?e.$op="update":c?e.$op="link":e.$op="create";}},El={create:"onCreate",update:"onUpdate",delete:"onDelete",link:"onLink",unlink:"onUnlink"},Ai=(e,t)=>{let n=e.$thing?t[e.$thing]:void 0;if(!n?.hooks?.pre)return [];let r=e.$op?El[e.$op]:void 0;if(!r)return [];let i=[];for(let o of n.hooks.pre)(!o.triggers||o.triggers[r]?.())&&i.push(...o.actions);return i},Bl=(e,t,n,r)=>{let i=Ai(e,n).filter(a=>a.type==="transform");if(i.length===0)return;let o={...e},s=r.mutation?.context??{};for(let a of i){if(a.type!=="transform")continue;let l=a.fn(o,t??{},s,{});if(l&&Object.keys(l).length>0){Object.assign(o,l),Object.assign(e,l);for(let d of Object.keys(l))l[d]===void 0&&(delete o[d],delete e[d]);}}},Fl=(e,t,n,r)=>{let i=Ai(e,n).filter(a=>a.type==="validate"&&a.severity==="error");if(i.length===0)return;let o={...e},s=r.mutation?.context??{};for(let a of i)if(a.type==="validate")try{let l=a.fn(o,t??{},s,{});if(l===!1)throw new Error(`[Validations:thing:${e.$thing}] ${a.message}.`);if(l!==!0)throw new Error(`[Validations:thing:${e.$thing}] Validation function's output is not a boolean value.`)}catch(l){if(l instanceof Error&&l.message.startsWith("[Validations:"))throw l;let d=l instanceof Error?l.message:String(l);throw new Error(`[Validations:thing:${e.$thing}] ${d}`)}},bl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date);var Di=(e,t)=>{if(Array.isArray(e))return e.map(r=>yt(r,false,t)).filter(r=>r!==null);let n=yt(e,false,t);if(!n)throw new Error("[Wrong format] Root mutation node cannot be a filter-only block with no operations");return n},yt=(e,t,n)=>{let r=Object.keys(e).some(s=>!s.startsWith("$"));if(!e.$op){let s=e.$id!==void 0,a=e.$filter!==void 0,l=e.$tempId!==void 0;if(a&&!s&&!l&&!r)return null;e.$op=Rl(e,r);}Tl(e,r,t);let i=t||e.$op==="create",o=e.$thing?n[e.$thing]:void 0;for(let[s,a]of Object.entries(e))if(!s.startsWith("$")&&a!=null){if(o){let l=o.fields[s];if(l&&l.type!=="role"&&l.type!=="link"&&l.type!=="ref")continue}if(Array.isArray(a)){let l=[];for(let d of a)if(gt(d))if(Jt(d)){let c=yt(d,i,n);c!==null&&l.push(c);}else Kt(d,i,n),l.push(d);else l.push(d);e[s]=l;}else gt(a)&&(Jt(a)?yt(a,i,n)===null&&delete e[s]:Kt(a,i,n));}return e},Kt=(e,t,n)=>{for(let[r,i]of Object.entries(e))if(i!=null)if(Array.isArray(i)){let o=[];for(let s of i)if(gt(s))if(Jt(s)){let a=yt(s,t,n);a!==null&&o.push(a);}else Kt(s,t,n),o.push(s);else o.push(s);e[r]=o;}else gt(i)&&(Jt(i)?yt(i,t,n)===null&&delete e[r]:Kt(i,t,n));},Rl=(e,t)=>{let n=e.$id!==void 0,r=e.$filter!==void 0,i=e.$tempId!==void 0;return (n||r)&&t?"update":n&&!t?"link":i&&t?"create":i&&!t?"link":"create"},Tl=(e,t,n)=>{let r=e.$op;if(e.$tempId&&!e.$tempId.startsWith("_:"))throw new Error('[Wrong format] TempIds must start with "_:"');if(r==="create"){if(e.$id!==void 0)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(e.$filter!==void 0)throw new Error("[Wrong format] Can't use $filter with $op: 'create'.")}if(e.$tempId){if(r==="delete")throw new Error("Invalid op delete for tempId. TempIds can be created, or linked when created in another part of the same mutation.");if(r==="unlink")throw new Error("Invalid op unlink for tempId. TempIds can be created, or linked when created in another part of the same mutation.")}if(n){if(r==="update")throw new Error("[Wrong format] Cannot update under a create");if(r==="delete")throw new Error("[Wrong format] Cannot delete under a create");if(r==="unlink")throw new Error("[Wrong format] Cannot unlink under a create")}if(r==="delete"&&Li(e))throw new Error("Cannot set data fields with $op: 'delete'.");if((r==="link"||r==="unlink")&&Li(e))throw new Error("[Unsupported] Can't update fields on Link / Unlink")},gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date),Jt=e=>Object.keys(e).some(t=>t==="$op"||t==="$id"||t==="$thing"||t==="$entity"||t==="$relation"||t==="$tempId"||t==="$filter"),Li=e=>{for(let[t,n]of Object.entries(e))if(!t.startsWith("$")&&n!=null&&!(Array.isArray(n)&&n.length>0&&gt(n[0]))&&!(gt(n)&&Object.keys(n).some(r=>r.startsWith("$"))))return true;return false};var ki=(e,t)=>{let n=Array.isArray(e)?e:[e];for(let r of n)Qi(r,t);},Qi=(e,t)=>{let n=e.$thing?t[e.$thing]:void 0;if(n)for(let[r,i]of Object.entries(e)){if(r.startsWith("$")||i===null||i===void 0)continue;let o=n.fields[r];if(!o)continue;let s;if(o.type==="role"?s=o.opposite.thing:o.type==="link"&&(s=o.target==="relation"?o.relation:o.opposite.thing),!s)continue;let a=l=>{if(typeof l!="object"||l===null||Array.isArray(l)||l instanceof Date)return;let d=l;if(!d.$thing){let c=t[s];if(c){let p=Object.keys(d).filter(f=>!f.startsWith("$"));p.length>0&&p.some(f=>f in c.fields||f===c.idFields[0])&&(d.$thing=s,d.$op||(d.$id?d.$op="link":e.$op==="create"&&(d.$op="create")));}}Qi(d,t);};if(Array.isArray(i))for(let l of i)a(l);else a(i);}};var Ii=(e,t)=>{let n=ji(e.source,t),r=e.filter?He(e.filter):void 0,{source:i,filter:o}=Xt({source:e.source,filter:r,schema:t,thing:n});return {source:i,projection:_i(e.projection,t,n),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Xt=e=>{let{source:t,filter:n,schema:r,thing:i}=e;if(t.type!=="table_scan")return {source:t,filter:n};let o=n?.type==="and"?n.filters:n?[n]:[];for(let l=0;l<o.length;l++){let d=o[l];if(d?.type!=="scalar"&&d?.type!=="list")continue;let c=wl(d,t);if(c)return {source:c,filter:Pn(o.filter((p,u)=>u!==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=Sl(s,r,i);if(l)return {source:l,filter:Pn(o.filter(d=>d!==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=Ml(a,r,i);if(l)return {source:l,filter:Pn(o.filter(d=>d!==a))}}return {source:t,filter:n?Ll(n,i):void 0}},wl=(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"&&qt.array(qt.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},Sl=(e,t,n)=>{let r=n.fields[e.left];if(!r)throw new Error(`Field ${e.left} not found in ${n.name}`);let i=Ci(r,t,n);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=qn(o,t),d={type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},c=l.fields[s];return {type:"subquery",source:d,oppositePath:s,isComputedPath:c?.type==="link",cardinality:a}},Ml=(e,t,n)=>{let r=n.fields[e.path];if(!r)throw new Error(`Field ${e.path} not found in ${n.name}`);let i=Ci(r,t,n);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=qn(o,t),d={type:"table_scan",thing:[o,...l.subTypes]},c=Xt({source:d,filter:e.filter,schema:t,thing:l}),p=l.fields[s];return {type:"subquery",source:c.source,oppositePath:s,isComputedPath:p?.type==="link",cardinality:a,filter:c.filter}},Ci=(e,t,n)=>{if(!(e.type!=="link"&&e.type!=="role")){if(e.type==="role"){let r=t[e.opposite.thing]?.fields?.[e.opposite.path];if(r?.type!=="link")throw new Error(`Role field ${e.name} in relation ${n.name} is not played by a link field`);if(r.target!=="relation")return}return e.opposite}},_i=(e,t,n)=>({fields:e.fields.map(r=>Al(r,t,n))}),Al=(e,t,n)=>{if(e.type==="metadata"||e.type==="data"||e.type==="flex"||e.type==="ref"||e.type==="computed_ref")return e;let r=n.fields[e.path];if(!r)throw new Error(`Field ${e.path} not found in ${n.name}`);if(r.type!=="link"&&r.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[r.opposite.thing];if(!i)throw new Error(`Thing ${r.opposite.thing} not found in schema`);return {type:e.type,path:e.path,projection:_i(e.projection,t,i),ids:e.ids,filter:e.filter?He(e.filter):void 0,alias:e.alias,resultCardinality:e.resultCardinality,fieldCardinality:e.fieldCardinality,limit:e.limit,offset:e.offset,sort:e.sort}},He=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=He(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 r=t.map(i=>{if(i.type==="scalar")return {filter:i,score:Zt[i.op]??0};if(i.type==="list"){let o=Zt[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="biref"){let o=Zt[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:r.map(i=>i.filter)}}if(e.type==="not"){let t=He(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=He(e.filter);return t?{type:e.type,filter:t,path:e.path,cardinality:e.cardinality,oppositeCardinality:e.oppositeCardinality}:void 0}return e},Zt={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},Ll=(e,t)=>{if(e.type==="and"){let n=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=Zt[i.op];if(s)return [i.left,{filter:i,index:o,score:s}]}).filter(i=>i!==void 0)),r=t.indexes.filter(i=>i.type!=="single").sort((i,o)=>o.fields.length-i.fields.length);if(r.length>0){let i=[];for(let s of r){let a=[];for(let l of s.fields){let d=n[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 r=e.filters.map((a,l)=>{if(a.type==="scalar"&&a.op==="="){let d=t.fields[a.left];if(Ni(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(Ni(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]=r,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},Pn=e=>{if(e.length!==0)return e.length===1?e[0]:{type:"and",filters:e}},Ni=(e,t)=>e.type==="role"||e.type==="link"||t.some(n=>n.type==="single"&&n.field===e.name||n.type==="composite"&&n.fields.includes(e.name)),qn=(e,t)=>{let n=t[e];if(!n)throw new Error(`Thing ${e} not found in schema`);return n},ji=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return qn(e.thing[0],t);let n=ji(e.source,t),r=n.fields[e.oppositePath];if(!r)throw new Error(`Field ${e.oppositePath} not found in ${n.name}`);if(r.type==="constant"||r.type==="computed"||r.type==="data"||r.type==="ref")throw new Error(`Invalid source: ${JSON.stringify(e)}`);let i=t[r.opposite.thing];if(!i)throw new Error(`Thing ${r.opposite.thing} not found in schema`);return i},ve=(e,t)=>e.find(t);var Pi=(e,t)=>({matches:e.matches.map(n=>Dl(n,t)),subMatches:e.subMatches.map(n=>kl(n)),creates:e.creates,updates:e.updates,deletes:e.deletes,linkAlls:e.linkAlls}),Dl=(e,t)=>{let n=e.filter?He(e.filter):void 0,r=e.source,i=r.type==="table_scan"||r.type==="record_pointer"?r.thing[0]:e.name,o=t[i];if(o){let s=Xt({source:r,filter:n,schema:t,thing:o});return {...e,source:s.source,filter:s.filter}}return {...e,source:r,filter:n}},kl=e=>{let t=e.filter?He(e.filter):void 0;return {...e,filter:t}};var Ql=z$1.object({$thing:z$1.string().optional(),$entity:z$1.string().optional(),$relation:z$1.string().optional(),$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([Me,z$1.array(Me)]).optional(),$op:z$1.enum(["create","update","delete","link","unlink"]).optional(),$tempId:z$1.string().optional()}).catchall(z$1.any()).superRefine((e,t)=>{!e.$thing&&!e.$entity&&!e.$relation&&t.addIssue({code:z$1.ZodIssueCode.custom,message:"At least one of $thing, $entity, or $relation must be provided"});}).transform(e=>{let t=e.$thing??e.$entity??e.$relation,{$entity:n,$relation:r,...i}=e;return {...i,$thing:t}}),Ol=z$1.object({$thing:z$1.string().optional(),$entity:z$1.string().optional(),$relation:z$1.string().optional(),$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([Me,z$1.array(Me)]).optional(),$op:z$1.enum(["create","update","delete","link","unlink"]).optional(),$tempId:z$1.string().optional()}).catchall(z$1.any()).transform(e=>{if(e.$entity||e.$relation){let t=e.$thing??e.$entity??e.$relation,{$entity:n,$relation:r,...i}=e;return {...i,$thing:t}}return e}),zi=(e,t)=>{let n=structuredClone(e);return Array.isArray(n)?n.map(r=>qi(r,t)):qi(n,t)},qi=(e,t)=>{let n=Ql.parse(e);if(!t[n.$thing])throw new Error(`Thing '${n.$thing}' not found in schema`);return Wi(n,t),n},Wi=(e,t)=>{for(let[n,r]of Object.entries(e))if(!n.startsWith("$")&&r!=null)if(Array.isArray(r))for(let i=0;i<r.length;i++)Vi(r[i])&&(r[i]=xi(r[i],t));else Vi(r)&&(e[n]=xi(r,t));},xi=(e,t)=>{let n=Ol.safeParse(e);if(!n.success)return e;let r=n.data;if(r.$thing&&!t[r.$thing])throw new Error(`Thing '${r.$thing}' not found in schema`);return Wi(r,t),r},Vi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date);var Ui=(e,t,n,r,i)=>{let o=[],s=i.mutation?.noMetadata??false,a=t.filter(l=>(l.type==="create"||l.type==="update"||l.type==="delete")&&l.resultIndex!==void 0);for(let l of a){let d=l.resultIndex<e.length?e[l.resultIndex]:null;l.isIntermediary||(l.type==="create"?Il(d,l,r,s,o):l.type==="update"?Cl(d,l,n,r,s,o):l.type==="delete"&&_l(d,l,n,r,s,o));}return o},Il=(e,t,n,r,i)=>{let o=Wn(e);for(let s of o){if(!s||typeof s!="object")continue;let a=Vn(s),l=a._tableName;delete a._tableName;let d=t.thing??l??a.$thing,c=d?n[d]:void 0,p={...a};r||(p.$id=a.id,p.$thing=d,p.$thingType=c?.type??"entity",p.$op="create",t.tempId&&(p.$tempId=t.tempId)),i.push(p);}},Cl=(e,t,n,r,i,o)=>{let s=Wn(e);for(let a of s){if(!a||typeof a!="object")continue;let l=Vn(a),d=l._tableName;delete l._tableName;let c=t.thing??d??Hi(l),p=c?r[c]:void 0,u={...l};i||(u.$id=l.id,u.$thing=c,u.$thingType=p?.type??"entity",u.$op="update"),o.push(u);}},_l=(e,t,n,r,i,o)=>{let s=Wn(e);for(let a of s){if(!a||typeof a!="object")continue;let l=Vn(a),d=l._tableName;delete l._tableName;let c=t.thing??d??Hi(l),p=c?r[c]:void 0,u={...l};i||(u.$id=l.id,u.$thing=c,u.$thingType=p?.type??"entity",u.$op="delete"),o.push(u);}},Vn=(e,t)=>{let n={};for(let[r,i]of Object.entries(e)){if(r==="id"){n.id=vi(i),n._tableName=jl(i);continue}n[r]=xn(i);}return n},xn=e=>{if(e==null)return e;if(!(isArray(e)&&e.length===0)){if(zn(e))return vi(e);if(typeof e=="string"){let t=/^[A-Za-z][A-Za-z0-9_-]*:⟨(.+?)⟩$/.exec(e);if(t)return t[1]}if(e instanceof Date)return e;if(isArray(e))return e.map(xn);if(isObject(e)){let t={};for(let[n,r]of Object.entries(e)){let i=xn(r);i!==void 0&&(t[n]=i);}return t}return e}},vi=e=>{if(typeof e=="string"){let t=e.indexOf(":");return t>0?qe(e.slice(t+1)):qe(e)}if(zn(e)){let t=e;if(t.id!==void 0)return qe(String(t.id));let n=String(e),r=n.indexOf(":");return r>0?qe(n.slice(r+1)):qe(n)}return qe(String(e))},qe=e=>e.startsWith("\u27E8")&&e.endsWith("\u27E9")?e.slice(1,-1):e,jl=e=>{if(typeof e=="string"){let t=e.indexOf(":");return t>0?qe(e.slice(0,t)):void 0}if(zn(e)){let t=e;if(t.tb)return qe(t.tb);let n=String(e),r=n.indexOf(":");if(r>0)return qe(n.slice(0,r))}},zn=e=>{if(!e||typeof e!="object")return false;if(e.constructor?.name==="RecordId")return true;let t=e;return "tb"in t&&"id"in t},Hi=(e,t)=>{if(e.$thing)return e.$thing},Wn=e=>e==null?[]:isArray(e)?e.length>0&&isArray(e[0])?e.flat():e:[e];var Yi=async(e,t,n)=>{let r;try{r=await e.beginTransaction(),V(["executeMutation","executeMutation/surql"],t),V(["executeMutation","executeMutation/params"],n);let i=await r.query(t,n);return await r.commit(),i}catch(i){await r?.cancel().catch(()=>{}),V("executeMutation",`executeMutation/surql
77
- `,t),V("executeMutation",`executeMutation/params
78
- `,n),V("executeMutation",`executeMutation/error
79
- `,i);let o=i instanceof Error?i.message:String(i),s=o.match(/Database record `(.+?)`.*already exists/);if(s){let l=s[1],d=l.includes(":")?l.split(":").pop()?.replace(/[`⟨⟩]/g,""):l.replace(/[`⟨⟩]/g,"");throw new Error(`Duplicate id ${d}`)}let a=o.match(/Couldn't coerce value for field `(.+?)` of .+?: .+ but found `?NONE`?/);throw a&&(o=`Found NONE for field \`${a[1]}\``),o.startsWith("An error occurred: ")&&(o=`[{"result":"${o}"}]`),new Error(`Error running SURQL mutation: ${o}`)}};var Pl=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},Ki=async(e,t,n,r)=>{let i=Pl(r),o=zi(e,t);V(["runSurql","runSurql/parsed"],`> runSurql/parsed
80
- `,o);let s=Di(o,t);ki(s,t),V(["runSurql","runSurql/withOp"],`> runSurql/withOp
81
- `,s);let a=Mi(s,t,n);V(["runSurql","runSurql/hooked"],`> runSurql/hooked
82
- `,a);let l=li(a,t);V(["runSurql","runSurql/logical"],`> runSurql/logical
83
- `,l),pi(l,t);let d=Pi(l,t),c={},{surql:p,stmtMap:u}=Ti(d,c,n,t);V(["buildSurql","buildSurql/surql"],`> buildSurql/surql
84
- `,p),V(["buildSurql","buildSurql/params"],`> buildSurql/params
85
- `,c);let f=await Yi(i,p,c);V(["runSurql","runSurql/rawResults"],`> runSurql/rawResults
86
- `,f);let m=Ui(f,u,d,t,n);return V(["processResults","processResults/output"],`> processResults/output
87
- `,m),m};var Hn={};Cs(Hn,{action:()=>zl,createMachine:()=>Xl,d:()=>lt,guard:()=>Wl,immediate:()=>vl,interpret:()=>co,invoke:()=>Zl,reduce:()=>no,state:()=>Kl,transition:()=>Ul});function fe(e){return {enumerable:true,value:e}}function Ji(e){return {enumerable:true,writable:true,value:e}}var lt={},ql=()=>true,Zi=()=>({}),Gi=e=>e,xl=(e,t,n,r)=>e.apply(n,r)&&t.apply(n,r),Vl=(e,t,n,[r,i])=>t.call(n,e.call(n,r,i),i),Ye=(e,t)=>Object.freeze(Object.create(e,t));function Xi(e,t,n){return e.reduce((r,i)=>function(...o){return n(r,i,this,o)},t)}function eo(e){return Ye(this,{fn:fe(e)})}var to={},no=eo.bind(to),zl=e=>no((t,n)=>!!~e(t,n)&&t),ro={},Wl=eo.bind(ro);function en(e,t){return t.filter(n=>e.isPrototypeOf(n))}function io(e,t,...n){let r=Xi(en(ro,n).map(o=>o.fn),ql,xl),i=Xi(en(to,n).map(o=>o.fn),Gi,Vl);return Ye(this,{from:fe(e),to:fe(t),guards:fe(r),reducers:fe(i)})}var oo={},so={},Ul=io.bind(oo),vl=io.bind(so,null);function Hl(e,t,n){return vn(t,e,n,this.immediates)||e}function ao(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Yl={enter:Gi};function Kl(...e){let t=en(oo,e),n=en(so,e),r={final:fe(e.length===0),transitions:fe(ao(t))};return n.length&&(r.immediates=fe(n),r.enter=fe(Hl)),Ye(Yl,r)}var Jl={enter(e,t,n){let r=this.fn.call(t,t.context,n);return Un.isPrototypeOf(r)?Ye(lo,{machine:fe(r),transitions:fe(this.transitions)}).enter(e,t,n):(r.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)}},lo={enter(e,t,n){if(t.child=co(this.machine,r=>{t.onChange(r),t.child==r&&r.machine.state.value.final&&(delete t.child,t.send({type:"done",data:r.context}));},t.context,n),t.child.machine.state.value.final){let r=t.child.context;return delete t.child,vn(t,e,{type:"done",data:r},this.transitions.get("done"))}return e}};function Zl(e,...t){let n=fe(ao(t));return Un.isPrototypeOf(e)?Ye(lo,{machine:fe(e),transitions:n}):Ye(Jl,{fn:fe(e),transitions:n})}var Un={get state(){return {name:this.current,value:this.states[this.current]}}};function Xl(e,t,n=Zi){return typeof e!="string"&&(n=t||Zi,t=e,e=Object.keys(t)[0]),lt._create&&lt._create(e,t),Ye(Un,{context:fe(n),current:fe(e),states:fe(t)})}function vn(e,t,n,r){let{context:i}=e;for(let{to:o,guards:s,reducers:a}of r)if(s(i,n)){e.context=a.call(e,i,n);let l=t.original||t,d=Ye(l,{current:fe(o),original:{value:l}});lt._onEnter&&lt._onEnter(t,o,e.context,i,n);let c=d.state.value;e.machine=d;let p=c.enter(d,e,n);return e.onChange(e),p}}function Gl(e,t){let n=t.type||t,{machine:r}=e,{value:i,name:o}=r.state;return i.transitions.has(n)?vn(e,r,t,i.transitions.get(n))||r:(lt._send&&lt._send(n,o),r)}var ec={send(e){Gl(this,e);}};function co(e,t,n,r){let i=Object.create(ec,{machine:Ji(e),context:Ji(e.context(n,r)),onChange:fe(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,r),i}var{createMachine:Ce,guard:tn,interpret:_e,invoke:te,reduce:W,state:Re,transition:U}=Hn;var de="0.17.0";var Dt={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},kt=(e,t,n)=>{if(e==null)return e;let r=isArray(e),o=(r?e:[e]).map(s=>{let l=Object.keys(s).reduce((d,c)=>{let p=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...d,[c]:void 0,[Dt[c]]:kt(p,t,n)};if(c==="$id")return {...d,$id:void 0,[Dt[c]]:{$IN:isArray(p)?p:[p]}};if(c==="$thing")return d;if(c==="$exists")return {...d,$exists:void 0,[Dt[c]]:p};if(c==="$eq")return {...d,$eq:void 0,[Dt[c]]:p};if(c==="$in")return {...d,$in:void 0,[Dt[c]]:p};throw new Error(`Unknown filter operator ${c}`)}let u=t in n.entities?n.entities[t]:n.relations[t],[f,m]=vt(u,c);if(f==="idField"){if(u.idFields.length>1)throw new Error("Multiple id fields not supported");return {...d,"record::id(id)":{$IN:isArray(p)?p:[p]}}}if(f==="dataField")return {...d,[c]:kt(p,t,n)};if(f==="linkField"||f==="roleField"){let y=m[tt].queryPath;return {...d,[y]:kt(p,t,n)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return r?o:o[0]},Ke=e=>{if(e==null)return "";let t=Object.entries(e),n=[];for(let[r,i]of t){if(["$OR","$AND","$!"].includes(r)){let o=r.replace("$",""),s=Array.isArray(i)?i.map(a=>Ke(a)):[Ke(i)];o==="!"?n.push(`!(${s.join(" AND ")})`):n.push(`(${s.join(` ${o} `)})`);continue}if(isObject(i))if(r.includes("<-")||r.includes("->")){let o=Ke(i);n.push(`${r}[WHERE ${o}]`);}else if(r.startsWith("$parent.[")){let o=Ke(i),s=r.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");n.push(`array::flatten([${s}])[WHERE id && ${o}]`);}else if(r.startsWith("$parent")){let o=Ke(i),s=r.replace("$parent.","");n.push(`array::flatten([${s}])[WHERE id && ${o}]`);}else {if(r.startsWith("$"))throw new Error(`Invalid key ${r}`);{let o=Object.keys(i);if(o.length===1&&o[0].startsWith("$")){let[s]=o,a=i[s];if(s==="$exists")if(a===true)n.push(`${r} IS NOT NONE`);else if(a===false)n.push(`${r} IS NONE`);else throw new Error(`Invalid value for $exists: ${a}`);else {let l=s.replace("$","");if(Array.isArray(a))n.push(`${r} ${l} [${a.map(d=>d===null?"NONE":`'${d}'`).join(", ")}]`);else if(isObject(a)){let d=Ke(a);n.push(`${r} ${l} ${d}`);}else n.push(`${r} ${l} ${a===null?"NONE":`'${a}'`}`);}}else throw new Error(`Invalid key ${r}`)}}else if(Array.isArray(i)){let o=r.startsWith("$")?r.replace("$",""):"IN";n.push(`${r} ${o} [${i.map(s=>s===null?"NONE":`'${s}'`).join(", ")}]`);}else {let o=r.startsWith("$")?r.replace("$",""):"=";n.push(`${r} ${o} ${i===null?"NONE":`'${i}'`}`);}}return n.join(" AND ")};var po=async(e,t)=>{let n=c=>{let p=be(c);return p!==c?p:`\u27E8${c}\u27E9`},r=c=>{let{$filter:p,$thing:u,$bzId:f,$op:m,$id:h,$tempId:y}=c,$=oe(t,u),{usedDataFields:g}=$e($,c),{idFields:B}=$,E=h||c[B[0]],T=(isArray(u)?u:[u]).map(Y),A=me(c,F=>F.startsWith("$")),k=me(c,F=>!F.startsWith("$")),R=JSON.stringify(k),D=Object.entries(A).map(([F,b])=>F==="$tempId"?`'$tempId': '_:${b}'`:`'${F}': '${b}'`).join(","),I=c[ht],q=g.filter(F=>!B.includes(F)).map(F=>{let b=$.dataFields?.find(C=>C.path===F||C.dbPath===F);if(!b)throw new Error(`Data field schema not found for ${F}`);let Q=c[F];return Q===null?`${F} = NONE`:`${F} = ${pt(Q,b.contentType,t)}`}).filter(Boolean),ne=`$\u27E8${y||f}\u27E9`,L=`$\u27E8${y||f}_pre\u27E9`,O=I?.bzId?`array::flatten($\u27E8${I.bzId}_pre\u27E9.${n(I.edgeField)} || []).filter(|$v| $v != NONE).len`:E?isArray(E)?T.flatMap(F=>E.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):T.map(F=>`${F}:\u27E8${E}\u27E9`).join(", "):true,v=(()=>{if(I?.bzId){let F=`array::flatten($\u27E8${I.bzId}_pre\u27E9.${n(I.edgeField)} || []).filter(|$v| $v != NONE)`;return E?isArray(E)?`${F}[? $this.id() IN [${E.map(b=>`'${b}'`).join(", ")}] ]`:`${F}[? $this.id() IN ['${E}'] ]`:F}return E?isArray(E)?T.flatMap(F=>E.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):T.map(F=>`${F}:\u27E8${E}\u27E9`).join(", "):T.join(", ")})(),M=p?`WHERE ${Ke(kt(p,u,t))}`:"",w=q.length>0?`SET ${q.join(", ")}`:"",S=`VALUE (CREATE ONLY Delta SET input = ${R}, meta = {${D}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`;if(["link","unlink","replace"].includes(m))throw new Error("Edge ops don't belong to things");if(c.$op==="match")return y?"":`LET ${ne} = (SELECT VALUE id FROM ${v} ${M});
75
+ `)};`),n.push({type:"filter_submatch",name:e.name});}}else {let d=[];d.push("SELECT VALUE id"),d.push(Lt(s,1,r)),a&&d.push(J(`WHERE ${a}`,1)),t.push(`LET $${e.name} = ${d.join(`
76
+ `)};`),n.push({type:"match",name:e.name});}},dl=(e,t,n,r)=>{let i=e.isComputed?be(e.path):Y(e.path),o=[];if(e.ids&&e.ids.length>0)if(e.ids.length===1){let l=ye(r,e.ids[0]);o.push(`record::id(id) = $${l}`);}else {let l=e.ids.map(d=>`$${ye(r,d)}`);o.push(`record::id(id) IN [${l.join(", ")}]`);}if(e.filter){let l=Array.isArray(e.filter)?e.filter:[e.filter];for(let d of l){let c=Le(d,r);c&&o.push(c);}}let s=o.length>0?` WHERE ${o.join(" AND ")}`:"",a=e.cardinality==="MANY"?"[*]":"";t.push(`LET $${e.name} = SELECT VALUE id FROM array::flatten($${e.parent}.${i}${a})${s};`),n.push({type:"submatch",name:e.name});},ul=(e,t,n,r,i,o,s,a)=>{let l=s[e];if(!(!l||l.type!=="relation"))for(let[d,c]of Object.entries(t)){if(c.type!=="role_field")continue;let p=l.fields[d];if(p?.type!=="role")continue;let f=s[p.opposite.thing]?.fields[p.opposite.path];if(f?.type!=="link"||f.cardinality!=="ONE")continue;let m=c.cardinality==="MANY"&&("links"in c||"refs"in c);if(!a&&p.cardinality!=="ONE"&&!m)continue;let y=(c.cardinality==="ONE"?[c.ref]:"refs"in c?c.refs:"links"in c?c.links:[]).filter(g=>!o.creates.some(B=>B.thing===g.thing&&B.id===g.id));if(y.length===0)continue;let $=Y(d);for(let g of y){let B=Dt(g,i,o);p.cardinality==="ONE"?r.push(`UPDATE ${n} SET ${$} = NONE WHERE ${$} = ${B};`):r.push(`UPDATE ${n} SET ${$} -= [${B}] WHERE ${$} CONTAINSANY [${B}];`);}}},pl=(e,t,n,r,i,o)=>{let s=Y(e.thing);o&&ul(e.thing,e.values,s,t,r,i,o,e.isIntermediary);let a=[];for(let[p,u]of Object.entries(e.values)){let f=Mi(p,u,r,i);a.push(...f);}let l=ye(r,e.thing),d=ye(r,e.id),c=a.length>0?` SET ${a.join(", ")}`:"";t.push(`LET $${e.name} = CREATE ONLY type::record($${l}, $${d})${c} RETURN AFTER;`),n.push({type:"create",name:e.name,op:"create",thing:e.thing,tempId:e.tempId,isIntermediary:e.isIntermediary});},fl=(e,t,n,r,i,o)=>{let s=[];for(let[c,p]of Object.entries(e.values)){let u=Mi(c,p,r,i);s.push(...u);}if(s.length===0)return;let a=`${e.name}_result`;i.creates.some(c=>c.name===e.match)?t.push(`LET $${a} = UPDATE $${e.match}.id SET ${s.join(", ")} RETURN AFTER;`):t.push(`LET $${a} = UPDATE $${e.match} SET ${s.join(", ")} RETURN AFTER;`);let d=Si(e.match,i);n.push({type:"update",name:e.name,op:"update",thing:d});},Si=(e,t)=>{let n=t.creates.find(i=>i.name===e);if(n)return n.thing;let r=t.matches.find(i=>i.name===e);if(r&&r.source.type!=="subquery")return r.source.thing[0]},hl=(e,t,n,r,i,o)=>{let s=`${e.name}_result`;t.push(`LET $${s} = DELETE $${e.match} RETURN BEFORE;`);let a=Si(e.match,i);if(o&&a){let l=o[a];if(l?.type==="entity"){for(let d of Object.values(l.fields))if(d.type==="link"&&d.target==="role"){let c=Y(d.relation),p=Y(d.plays);t.push(`DELETE FROM ${c} WHERE ${p} IS NONE;`);}}}n.push({type:"delete",name:e.name,op:"delete",thing:a});},Mi=(e,t,n,r)=>{let i=Y(e);switch(t.type){case "null":return [`${i} = NONE`];case "empty":return [`${i} = []`];case "data_field":if(t.cardinality==="MANY"){let o=t.value.map(s=>`$${ye(n,s)}`);return [`${i} = [${o.join(", ")}]`]}return [`${i} = $${ye(n,t.value)}`];case "ref_field":{if(t.cardinality==="ONE")return [`${i} = ${Ti(t.value,n)}`];let o=t.value.map(s=>Ti(s,n));return [`${i} = [${o.join(", ")}]`]}case "flex_field":return [`${i} = $${ye(n,(t.cardinality==="ONE",t.value))}`];case "role_field":return ml(e,t,n,r);default:return []}},ml=(e,t,n,r)=>{let i=Y(e),o=[];if(t.cardinality==="ONE"){let s=Dt(t.ref,n,r);return o.push(`${i} = ${s}`),o}if("refs"in t){if(t.refs.length===0)o.push(`${i} = []`);else {let s=t.refs.map(a=>Dt(a,n,r));o.push(`${i} = [${s.join(", ")}]`);}return o}if("links"in t){if(t.links.length>0){let s=t.links.map(a=>Dt(a,n,r));o.push(`${i} += [${s.join(", ")}]`);}if(t.unlinks.length>0){let s=t.unlinks.map(a=>Dt(a,n,r));o.push(`${i} -= [${s.join(", ")}]`);}return o}return o},Dt=(e,t,n)=>{let r=e.subTypes?[e.thing,...e.subTypes]:[e.thing],i=n.creates.find(a=>r.includes(a.thing)&&a.id===e.id);if(i)return `$${i.name}.id`;if(e.subTypes&&e.subTypes.length>0){let a=[e.thing,...e.subTypes],l=ye(t,e.id);return `array::first(SELECT VALUE id FROM [${a.map(c=>`type::record($${ye(t,c)}, $${l})`).join(", ")}])`}let o=ye(t,e.thing),s=ye(t,e.id);return `type::record($${o}, $${s})`},Ti=(e,t)=>{let n=e.split(":");if(n.length!==2)throw new Error(`Invalid record reference: ${e}`);let[r,i]=n,o=ye(t,r),s=ye(t,i);return `type::record($${o}, $${s})`},$l=(e,t,n)=>{let r=e.oppositeThings.map(u=>Y(u)).join(", "),i=Y(e.relation),o=ye(n,e.parentThing),s=ye(n,e.parentId),a=`type::record($${o}, $${s})`,l=e.playsCardinality==="ONE"?a:`[${a}]`,d=e.targetCardinality==="ONE"?"$item":"[$item]",c=Y(e.playsField),p=Y(e.targetRoleField);t.push(`FOR $item IN (SELECT VALUE id FROM ${r}) { CREATE ${i} SET ${c} = ${l}, ${p} = ${d}; };`);},ye=(e,t)=>{let n=yt();for(;e[n]!==void 0;)n=yt();return e[n]=t,n};var Ai=(e,t,n)=>{if(Array.isArray(e)){for(let r of e)Pn(r,null,t,n);return e}return Pn(e,null,t,n),e},Pn=(e,t,n,r)=>{yl(e,n),Fl(e,t,n,r),gl(e,n,r),bl(e,t,n,r);},yl=(e,t)=>{let n=e.$thing?t[e.$thing]:void 0;if(n&&e.$op==="create")for(let r of Object.values(n.fields))r.type==="data"&&(r.isVirtual||r.default&&e[r.name]===void 0&&(r.default.type==="value"?e[r.name]=r.default.value:r.default.type==="fn"&&(e[r.name]=r.default.fn(e))));if(n)for(let r of Object.values(n.fields)){if(r.type!=="data"||r.contentType!=="DATE"&&r.contentType!=="TIME")continue;let i=e[r.name];if(typeof i=="string"){let o=new Date(i);Number.isNaN(o.getTime())||(e[r.name]=o);}}},gl=(e,t,n)=>{let r=e.$thing?t[e.$thing]:void 0;for(let[i,o]of Object.entries(e)){if(i.startsWith("$")||o==null)continue;if(r){let a=r.fields[i];if(a&&a.type!=="role"&&a.type!=="link"&&a.type!=="ref")continue}let s=a=>{if(!Rl(a))return;let l=a;El(l,e,i,t),l.$thing&&Pn(l,e,t,n);};if(Array.isArray(o))for(let a of o)s(a);else s(o);}},El=(e,t,n,r)=>{if(e.$thing)return;let i=t.$thing?r[t.$thing]:void 0;if(!i)return;let o=i.fields[n];if(!o)return;let s;if(o.type==="role"?s=o.opposite.thing:o.type==="link"&&(s=o.target==="relation"?o.relation:o.opposite.thing),!s)return;let a=r[s];if(!a)return;let l=Object.keys(e).filter(c=>!c.startsWith("$"));if((e.$op!==void 0||e.$id!==void 0||l.length>0&&l.some(c=>c in a.fields||c===a.idFields[0]))&&(e.$thing=s,!e.$op)){let c=e.$id!==void 0,p=l.length>0;c&&p?e.$op="update":c?e.$op="link":e.$op="create";}},Bl={create:"onCreate",update:"onUpdate",delete:"onDelete",link:"onLink",unlink:"onUnlink"},Li=(e,t)=>{let n=e.$thing?t[e.$thing]:void 0;if(!n?.hooks?.pre)return [];let r=e.$op?Bl[e.$op]:void 0;if(!r)return [];let i=[];for(let o of n.hooks.pre)(!o.triggers||o.triggers[r]?.())&&i.push(...o.actions);return i},Fl=(e,t,n,r)=>{let i=Li(e,n).filter(a=>a.type==="transform");if(i.length===0)return;let o={...e},s=r.mutation?.context??{};for(let a of i){if(a.type!=="transform")continue;let l=a.fn(o,t??{},s,{});if(l&&Object.keys(l).length>0){Object.assign(o,l),Object.assign(e,l);for(let d of Object.keys(l))l[d]===void 0&&(delete o[d],delete e[d]);}}},bl=(e,t,n,r)=>{let i=Li(e,n).filter(a=>a.type==="validate"&&a.severity==="error");if(i.length===0)return;let o={...e},s=r.mutation?.context??{};for(let a of i)if(a.type==="validate")try{let l=a.fn(o,t??{},s,{});if(l===!1)throw new Error(`[Validations:thing:${e.$thing}] ${a.message}.`);if(l!==!0)throw new Error(`[Validations:thing:${e.$thing}] Validation function's output is not a boolean value.`)}catch(l){if(l instanceof Error&&l.message.startsWith("[Validations:"))throw l;let d=l instanceof Error?l.message:String(l);throw new Error(`[Validations:thing:${e.$thing}] ${d}`)}},Rl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date);var ki=(e,t)=>{if(Array.isArray(e))return e.map(r=>gt(r,false,t)).filter(r=>r!==null);let n=gt(e,false,t);if(!n)throw new Error("[Wrong format] Root mutation node cannot be a filter-only block with no operations");return n},gt=(e,t,n)=>{let r=Object.keys(e).some(s=>!s.startsWith("$"));if(!e.$op){let s=e.$id!==void 0,a=e.$filter!==void 0,l=e.$tempId!==void 0;if(a&&!s&&!l&&!r)return null;e.$op=Tl(e,r);}wl(e,r,t);let i=t||e.$op==="create",o=e.$thing?n[e.$thing]:void 0;for(let[s,a]of Object.entries(e))if(!s.startsWith("$")&&a!=null){if(o){let l=o.fields[s];if(l&&l.type!=="role"&&l.type!=="link"&&l.type!=="ref")continue}if(Array.isArray(a)){let l=[];for(let d of a)if(Et(d))if(Zt(d)){let c=gt(d,i,n);c!==null&&l.push(c);}else Jt(d,i,n),l.push(d);else l.push(d);e[s]=l;}else Et(a)&&(Zt(a)?gt(a,i,n)===null&&delete e[s]:Jt(a,i,n));}return e},Jt=(e,t,n)=>{for(let[r,i]of Object.entries(e))if(i!=null)if(Array.isArray(i)){let o=[];for(let s of i)if(Et(s))if(Zt(s)){let a=gt(s,t,n);a!==null&&o.push(a);}else Jt(s,t,n),o.push(s);else o.push(s);e[r]=o;}else Et(i)&&(Zt(i)?gt(i,t,n)===null&&delete e[r]:Jt(i,t,n));},Tl=(e,t)=>{let n=e.$id!==void 0,r=e.$filter!==void 0,i=e.$tempId!==void 0;return (n||r)&&t?"update":n&&!t?"link":i&&t?"create":i&&!t?"link":"create"},wl=(e,t,n)=>{let r=e.$op;if(e.$tempId&&!e.$tempId.startsWith("_:"))throw new Error('[Wrong format] TempIds must start with "_:"');if(r==="create"){if(e.$id!==void 0)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(e.$filter!==void 0)throw new Error("[Wrong format] Can't use $filter with $op: 'create'.")}if(e.$tempId){if(r==="delete")throw new Error("Invalid op delete for tempId. TempIds can be created, or linked when created in another part of the same mutation.");if(r==="unlink")throw new Error("Invalid op unlink for tempId. TempIds can be created, or linked when created in another part of the same mutation.")}if(n){if(r==="update")throw new Error("[Wrong format] Cannot update under a create");if(r==="delete")throw new Error("[Wrong format] Cannot delete under a create");if(r==="unlink")throw new Error("[Wrong format] Cannot unlink under a create")}if(r==="delete"&&Di(e))throw new Error("Cannot set data fields with $op: 'delete'.");if((r==="link"||r==="unlink")&&Di(e))throw new Error("[Unsupported] Can't update fields on Link / Unlink")},Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date),Zt=e=>Object.keys(e).some(t=>t==="$op"||t==="$id"||t==="$thing"||t==="$entity"||t==="$relation"||t==="$tempId"||t==="$filter"),Di=e=>{for(let[t,n]of Object.entries(e))if(!t.startsWith("$")&&n!=null&&!(Array.isArray(n)&&n.length>0&&Et(n[0]))&&!(Et(n)&&Object.keys(n).some(r=>r.startsWith("$"))))return true;return false};var Qi=(e,t)=>{let n=Array.isArray(e)?e:[e];for(let r of n)Oi(r,t);},Oi=(e,t)=>{let n=e.$thing?t[e.$thing]:void 0;if(n)for(let[r,i]of Object.entries(e)){if(r.startsWith("$")||i===null||i===void 0)continue;let o=n.fields[r];if(!o)continue;let s;if(o.type==="role"?s=o.opposite.thing:o.type==="link"&&(s=o.target==="relation"?o.relation:o.opposite.thing),!s)continue;let a=l=>{if(typeof l!="object"||l===null||Array.isArray(l)||l instanceof Date)return;let d=l;if(!d.$thing){let c=t[s];if(c){let p=Object.keys(d).filter(f=>!f.startsWith("$"));p.length>0&&p.some(f=>f in c.fields||f===c.idFields[0])&&(d.$thing=s,d.$op||(d.$id?d.$op="link":e.$op==="create"&&(d.$op="create")));}}Oi(d,t);};if(Array.isArray(i))for(let l of i)a(l);else a(i);}};var Ci=(e,t)=>{let n=Pi(e.source,t),r=e.filter?Ye(e.filter):void 0,{source:i,filter:o}=Gt({source:e.source,filter:r,schema:t,thing:n});return {source:i,projection:ji(e.projection,t,n),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Gt=e=>{let{source:t,filter:n,schema:r,thing:i}=e;if(t.type!=="table_scan")return {source:t,filter:n};let o=n?.type==="and"?n.filters:n?[n]:[];for(let l=0;l<o.length;l++){let d=o[l];if(d?.type!=="scalar"&&d?.type!=="list")continue;let c=Sl(d,t);if(c)return {source:c,filter:qn(o.filter((p,u)=>u!==l))}}let s=He(o,l=>l.type==="computed_biref"&&l.oppositeCardinality==="ONE")??He(o,l=>l.type==="computed_biref")??He(o,l=>l.type==="biref"&&l.oppositeCardinality==="ONE")??He(o,l=>l.type==="biref");if(s){let l=Ml(s,r,i);if(l)return {source:l,filter:qn(o.filter(d=>d!==s))}}let a=He(o,l=>l.type==="nested_ref"&&l.oppositeCardinality==="ONE")??He(o,l=>l.type==="nested_ref"&&l.oppositeCardinality==="MANY")??He(o,l=>l.type==="nested_computed_ref"&&l.oppositeCardinality==="ONE")??He(o,l=>l.type==="nested_computed_ref"&&l.oppositeCardinality==="MANY");if(a){let l=Al(a,r,i);if(l)return {source:l,filter:qn(o.filter(d=>d!==a))}}return {source:t,filter:n?Dl(n,i):void 0}},Sl=(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"&&xt.array(xt.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},Ml=(e,t,n)=>{let r=n.fields[e.left];if(!r)throw new Error(`Field ${e.left} not found in ${n.name}`);let i=_i(r,t,n);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=xn(o,t),d={type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},c=l.fields[s];return {type:"subquery",source:d,oppositePath:s,isComputedPath:c?.type==="link",cardinality:a}},Al=(e,t,n)=>{let r=n.fields[e.path];if(!r)throw new Error(`Field ${e.path} not found in ${n.name}`);let i=_i(r,t,n);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=xn(o,t),d={type:"table_scan",thing:[o,...l.subTypes]},c=Gt({source:d,filter:e.filter,schema:t,thing:l}),p=l.fields[s];return {type:"subquery",source:c.source,oppositePath:s,isComputedPath:p?.type==="link",cardinality:a,filter:c.filter}},_i=(e,t,n)=>{if(!(e.type!=="link"&&e.type!=="role")){if(e.type==="role"){let r=t[e.opposite.thing]?.fields?.[e.opposite.path];if(r?.type!=="link")throw new Error(`Role field ${e.name} in relation ${n.name} is not played by a link field`);if(r.target!=="relation")return}return e.opposite}},ji=(e,t,n)=>({fields:e.fields.map(r=>Ll(r,t,n))}),Ll=(e,t,n)=>{if(e.type==="metadata"||e.type==="data"||e.type==="flex"||e.type==="ref"||e.type==="computed_ref")return e;let r=n.fields[e.path];if(!r)throw new Error(`Field ${e.path} not found in ${n.name}`);if(r.type!=="link"&&r.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[r.opposite.thing];if(!i)throw new Error(`Thing ${r.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?Ye(e.filter):void 0,alias:e.alias,resultCardinality:e.resultCardinality,fieldCardinality:e.fieldCardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Ye=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=Ye(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 r=t.map(i=>{if(i.type==="scalar")return {filter:i,score:Xt[i.op]??0};if(i.type==="list"){let o=Xt[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="biref"){let o=Xt[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:r.map(i=>i.filter)}}if(e.type==="not"){let t=Ye(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=Ye(e.filter);return t?{type:e.type,filter:t,path:e.path,cardinality:e.cardinality,oppositeCardinality:e.oppositeCardinality}:void 0}return e},Xt={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},Dl=(e,t)=>{if(e.type==="and"){let n=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=Xt[i.op];if(s)return [i.left,{filter:i,index:o,score:s}]}).filter(i=>i!==void 0)),r=t.indexes.filter(i=>i.type!=="single").sort((i,o)=>o.fields.length-i.fields.length);if(r.length>0){let i=[];for(let s of r){let a=[];for(let l of s.fields){let d=n[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 r=e.filters.map((a,l)=>{if(a.type==="scalar"&&a.op==="="){let d=t.fields[a.left];if(Ii(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(Ii(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]=r,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},qn=e=>{if(e.length!==0)return e.length===1?e[0]:{type:"and",filters:e}},Ii=(e,t)=>e.type==="role"||e.type==="link"||t.some(n=>n.type==="single"&&n.field===e.name||n.type==="composite"&&n.fields.includes(e.name)),xn=(e,t)=>{let n=t[e];if(!n)throw new Error(`Thing ${e} not found in schema`);return n},Pi=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return xn(e.thing[0],t);let n=Pi(e.source,t),r=n.fields[e.oppositePath];if(!r)throw new Error(`Field ${e.oppositePath} not found in ${n.name}`);if(r.type==="constant"||r.type==="computed"||r.type==="data"||r.type==="ref")throw new Error(`Invalid source: ${JSON.stringify(e)}`);let i=t[r.opposite.thing];if(!i)throw new Error(`Thing ${r.opposite.thing} not found in schema`);return i},He=(e,t)=>e.find(t);var qi=(e,t)=>({matches:e.matches.map(n=>kl(n,t)),subMatches:e.subMatches.map(n=>Ql(n)),creates:e.creates,updates:e.updates,deletes:e.deletes,linkAlls:e.linkAlls}),kl=(e,t)=>{let n=e.filter?Ye(e.filter):void 0,r=e.source,i=r.type==="table_scan"||r.type==="record_pointer"?r.thing[0]:e.name,o=t[i];if(o){let s=Gt({source:r,filter:n,schema:t,thing:o});return {...e,source:s.source,filter:s.filter}}return {...e,source:r,filter:n}},Ql=e=>{let t=e.filter?Ye(e.filter):void 0;return {...e,filter:t}};var Ol=z$1.object({$thing:z$1.string().optional(),$entity:z$1.string().optional(),$relation:z$1.string().optional(),$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([Me,z$1.array(Me)]).optional(),$op:z$1.enum(["create","update","delete","link","unlink"]).optional(),$tempId:z$1.string().optional()}).catchall(z$1.any()).superRefine((e,t)=>{!e.$thing&&!e.$entity&&!e.$relation&&t.addIssue({code:z$1.ZodIssueCode.custom,message:"At least one of $thing, $entity, or $relation must be provided"});}).transform(e=>{let t=e.$thing??e.$entity??e.$relation,{$entity:n,$relation:r,...i}=e;return {...i,$thing:t}}),Nl=z$1.object({$thing:z$1.string().optional(),$entity:z$1.string().optional(),$relation:z$1.string().optional(),$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([Me,z$1.array(Me)]).optional(),$op:z$1.enum(["create","update","delete","link","unlink"]).optional(),$tempId:z$1.string().optional()}).catchall(z$1.any()).transform(e=>{if(e.$entity||e.$relation){let t=e.$thing??e.$entity??e.$relation,{$entity:n,$relation:r,...i}=e;return {...i,$thing:t}}return e}),Wi=(e,t)=>{let n=structuredClone(e);return Array.isArray(n)?n.map(r=>xi(r,t)):xi(n,t)},xi=(e,t)=>{let n=Ol.parse(e);if(!t[n.$thing])throw new Error(`Thing '${n.$thing}' not found in schema`);return Ui(n,t),n},Ui=(e,t)=>{for(let[n,r]of Object.entries(e))if(!n.startsWith("$")&&r!=null)if(Array.isArray(r))for(let i=0;i<r.length;i++)zi(r[i])&&(r[i]=Vi(r[i],t));else zi(r)&&(e[n]=Vi(r,t));},Vi=(e,t)=>{let n=Nl.safeParse(e);if(!n.success)return e;let r=n.data;if(r.$thing&&!t[r.$thing])throw new Error(`Thing '${r.$thing}' not found in schema`);return Ui(r,t),r},zi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date);var vi=(e,t,n,r,i)=>{let o=[],s=i.mutation?.noMetadata??false,a=t.filter(l=>(l.type==="create"||l.type==="update"||l.type==="delete")&&l.resultIndex!==void 0);for(let l of a){let d=l.resultIndex<e.length?e[l.resultIndex]:null;l.isIntermediary||(l.type==="create"?Cl(d,l,r,s,o):l.type==="update"?_l(d,l,n,r,s,o):l.type==="delete"&&jl(d,l,n,r,s,o));}return o},Cl=(e,t,n,r,i)=>{let o=Un(e);for(let s of o){if(!s||typeof s!="object")continue;let a=zn(s),l=a._tableName;delete a._tableName;let d=t.thing??l??a.$thing,c=d?n[d]:void 0,p={...a};r||(p.$id=a.id,p.$thing=d,p.$thingType=c?.type??"entity",p.$op="create",t.tempId&&(p.$tempId=t.tempId)),i.push(p);}},_l=(e,t,n,r,i,o)=>{let s=Un(e);for(let a of s){if(!a||typeof a!="object")continue;let l=zn(a),d=l._tableName;delete l._tableName;let c=t.thing??d??Yi(l),p=c?r[c]:void 0,u={...l};i||(u.$id=l.id,u.$thing=c,u.$thingType=p?.type??"entity",u.$op="update"),o.push(u);}},jl=(e,t,n,r,i,o)=>{let s=Un(e);for(let a of s){if(!a||typeof a!="object")continue;let l=zn(a),d=l._tableName;delete l._tableName;let c=t.thing??d??Yi(l),p=c?r[c]:void 0,u={...l};i||(u.$id=l.id,u.$thing=c,u.$thingType=p?.type??"entity",u.$op="delete"),o.push(u);}},zn=(e,t)=>{let n={};for(let[r,i]of Object.entries(e)){if(r==="id"){n.id=Hi(i),n._tableName=Pl(i);continue}n[r]=Vn(i);}return n},Vn=e=>{if(e==null)return e;if(!(isArray(e)&&e.length===0)){if(Wn(e))return Hi(e);if(typeof e=="string"){let t=/^[A-Za-z][A-Za-z0-9_-]*:⟨(.+?)⟩$/.exec(e);if(t)return t[1]}if(e instanceof Date)return e;if(isArray(e))return e.map(Vn);if(isObject(e)){let t={};for(let[n,r]of Object.entries(e)){let i=Vn(r);i!==void 0&&(t[n]=i);}return t}return e}},Hi=e=>{if(typeof e=="string"){let t=e.indexOf(":");return t>0?qe(e.slice(t+1)):qe(e)}if(Wn(e)){let t=e;if(t.id!==void 0)return qe(String(t.id));let n=String(e),r=n.indexOf(":");return r>0?qe(n.slice(r+1)):qe(n)}return qe(String(e))},qe=e=>e.startsWith("\u27E8")&&e.endsWith("\u27E9")?e.slice(1,-1):e,Pl=e=>{if(typeof e=="string"){let t=e.indexOf(":");return t>0?qe(e.slice(0,t)):void 0}if(Wn(e)){let t=e;if(t.tb)return qe(t.tb);let n=String(e),r=n.indexOf(":");if(r>0)return qe(n.slice(0,r))}},Wn=e=>{if(!e||typeof e!="object")return false;if(e.constructor?.name==="RecordId")return true;let t=e;return "tb"in t&&"id"in t},Yi=(e,t)=>{if(e.$thing)return e.$thing},Un=e=>e==null?[]:isArray(e)?e.length>0&&isArray(e[0])?e.flat():e:[e];var Ki=async(e,t,n)=>{let r;try{r=await e.beginTransaction(),x(["executeMutation","executeMutation/surql"],t),x(["executeMutation","executeMutation/params"],n);let i=await r.query(t,n);return await r.commit(),i}catch(i){await r?.cancel().catch(()=>{}),x("executeMutation",`executeMutation/surql
77
+ `,t),x("executeMutation",`executeMutation/params
78
+ `,n),x("executeMutation",`executeMutation/error
79
+ `,i);let o=i instanceof Error?i.message:String(i),s=o.match(/Database record `(.+?)`.*already exists/);if(s){let l=s[1],d=l.includes(":")?l.split(":").pop()?.replace(/[`⟨⟩]/g,""):l.replace(/[`⟨⟩]/g,"");throw new Error(`Duplicate id ${d}`)}let a=o.match(/Couldn't coerce value for field `(.+?)` of .+?: .+ but found `?NONE`?/);throw a&&(o=`Found NONE for field \`${a[1]}\``),o.startsWith("An error occurred: ")&&(o=`[{"result":"${o}"}]`),new Error(`Error running SURQL mutation: ${o}`)}};var ql=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},Ji=async(e,t,n,r)=>{let i=ql(r),o=Wi(e,t);x(["runSurql","runSurql/parsed"],`> runSurql/parsed
80
+ `,o);let s=ki(o,t);Qi(s,t),x(["runSurql","runSurql/withOp"],`> runSurql/withOp
81
+ `,s);let a=Ai(s,t,n);x(["runSurql","runSurql/hooked"],`> runSurql/hooked
82
+ `,a);let l=ci(a,t);x(["runSurql","runSurql/logical"],`> runSurql/logical
83
+ `,l),fi(l,t);let d=qi(l,t);x(["runSurql","runSurql/optimized"],`> runSurql/optimized
84
+ `,d);let c={},{surql:p,stmtMap:u}=wi(d,c,n,t);x(["buildSurql","buildSurql/surql"],`> buildSurql/surql
85
+ `,p),x(["buildSurql","buildSurql/params"],`> buildSurql/params
86
+ `,c);let f=await Ki(i,p,c);x(["runSurql","runSurql/rawResults"],`> runSurql/rawResults
87
+ `,f);let m=vi(f,u,d,t,n);return x(["processResults","processResults/output"],`> processResults/output
88
+ `,m),m};var Yn={};_s(Yn,{action:()=>Wl,createMachine:()=>Gl,d:()=>lt,guard:()=>Ul,immediate:()=>Hl,interpret:()=>uo,invoke:()=>Xl,reduce:()=>ro,state:()=>Jl,transition:()=>vl});function fe(e){return {enumerable:true,value:e}}function Zi(e){return {enumerable:true,writable:true,value:e}}var lt={},xl=()=>true,Xi=()=>({}),eo=e=>e,Vl=(e,t,n,r)=>e.apply(n,r)&&t.apply(n,r),zl=(e,t,n,[r,i])=>t.call(n,e.call(n,r,i),i),Ke=(e,t)=>Object.freeze(Object.create(e,t));function Gi(e,t,n){return e.reduce((r,i)=>function(...o){return n(r,i,this,o)},t)}function to(e){return Ke(this,{fn:fe(e)})}var no={},ro=to.bind(no),Wl=e=>ro((t,n)=>!!~e(t,n)&&t),io={},Ul=to.bind(io);function tn(e,t){return t.filter(n=>e.isPrototypeOf(n))}function oo(e,t,...n){let r=Gi(tn(io,n).map(o=>o.fn),xl,Vl),i=Gi(tn(no,n).map(o=>o.fn),eo,zl);return Ke(this,{from:fe(e),to:fe(t),guards:fe(r),reducers:fe(i)})}var so={},ao={},vl=oo.bind(so),Hl=oo.bind(ao,null);function Yl(e,t,n){return Hn(t,e,n,this.immediates)||e}function lo(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Kl={enter:eo};function Jl(...e){let t=tn(so,e),n=tn(ao,e),r={final:fe(e.length===0),transitions:fe(lo(t))};return n.length&&(r.immediates=fe(n),r.enter=fe(Yl)),Ke(Kl,r)}var Zl={enter(e,t,n){let r=this.fn.call(t,t.context,n);return vn.isPrototypeOf(r)?Ke(co,{machine:fe(r),transitions:fe(this.transitions)}).enter(e,t,n):(r.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)}},co={enter(e,t,n){if(t.child=uo(this.machine,r=>{t.onChange(r),t.child==r&&r.machine.state.value.final&&(delete t.child,t.send({type:"done",data:r.context}));},t.context,n),t.child.machine.state.value.final){let r=t.child.context;return delete t.child,Hn(t,e,{type:"done",data:r},this.transitions.get("done"))}return e}};function Xl(e,...t){let n=fe(lo(t));return vn.isPrototypeOf(e)?Ke(co,{machine:fe(e),transitions:n}):Ke(Zl,{fn:fe(e),transitions:n})}var vn={get state(){return {name:this.current,value:this.states[this.current]}}};function Gl(e,t,n=Xi){return typeof e!="string"&&(n=t||Xi,t=e,e=Object.keys(t)[0]),lt._create&&lt._create(e,t),Ke(vn,{context:fe(n),current:fe(e),states:fe(t)})}function Hn(e,t,n,r){let{context:i}=e;for(let{to:o,guards:s,reducers:a}of r)if(s(i,n)){e.context=a.call(e,i,n);let l=t.original||t,d=Ke(l,{current:fe(o),original:{value:l}});lt._onEnter&&lt._onEnter(t,o,e.context,i,n);let c=d.state.value;e.machine=d;let p=c.enter(d,e,n);return e.onChange(e),p}}function ec(e,t){let n=t.type||t,{machine:r}=e,{value:i,name:o}=r.state;return i.transitions.has(n)?Hn(e,r,t,i.transitions.get(n))||r:(lt._send&&lt._send(n,o),r)}var tc={send(e){ec(this,e);}};function uo(e,t,n,r){let i=Object.create(tc,{machine:Zi(e),context:Zi(e.context(n,r)),onChange:fe(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,r),i}var{createMachine:Ce,guard:nn,interpret:_e,invoke:te,reduce:W,state:Re,transition:U}=Yn;var de="0.17.1";var kt={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Qt=(e,t,n)=>{if(e==null)return e;let r=isArray(e),o=(r?e:[e]).map(s=>{let l=Object.keys(s).reduce((d,c)=>{let p=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...d,[c]:void 0,[kt[c]]:Qt(p,t,n)};if(c==="$id")return {...d,$id:void 0,[kt[c]]:{$IN:isArray(p)?p:[p]}};if(c==="$thing")return d;if(c==="$exists")return {...d,$exists:void 0,[kt[c]]:p};if(c==="$eq")return {...d,$eq:void 0,[kt[c]]:p};if(c==="$in")return {...d,$in:void 0,[kt[c]]:p};throw new Error(`Unknown filter operator ${c}`)}let u=t in n.entities?n.entities[t]:n.relations[t],[f,m]=Ht(u,c);if(f==="idField"){if(u.idFields.length>1)throw new Error("Multiple id fields not supported");return {...d,"record::id(id)":{$IN:isArray(p)?p:[p]}}}if(f==="dataField")return {...d,[c]:Qt(p,t,n)};if(f==="linkField"||f==="roleField"){let y=m[nt].queryPath;return {...d,[y]:Qt(p,t,n)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return r?o:o[0]},Je=e=>{if(e==null)return "";let t=Object.entries(e),n=[];for(let[r,i]of t){if(["$OR","$AND","$!"].includes(r)){let o=r.replace("$",""),s=Array.isArray(i)?i.map(a=>Je(a)):[Je(i)];o==="!"?n.push(`!(${s.join(" AND ")})`):n.push(`(${s.join(` ${o} `)})`);continue}if(isObject(i))if(r.includes("<-")||r.includes("->")){let o=Je(i);n.push(`${r}[WHERE ${o}]`);}else if(r.startsWith("$parent.[")){let o=Je(i),s=r.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");n.push(`array::flatten([${s}])[WHERE id && ${o}]`);}else if(r.startsWith("$parent")){let o=Je(i),s=r.replace("$parent.","");n.push(`array::flatten([${s}])[WHERE id && ${o}]`);}else {if(r.startsWith("$"))throw new Error(`Invalid key ${r}`);{let o=Object.keys(i);if(o.length===1&&o[0].startsWith("$")){let[s]=o,a=i[s];if(s==="$exists")if(a===true)n.push(`${r} IS NOT NONE`);else if(a===false)n.push(`${r} IS NONE`);else throw new Error(`Invalid value for $exists: ${a}`);else {let l=s.replace("$","");if(Array.isArray(a))n.push(`${r} ${l} [${a.map(d=>d===null?"NONE":`'${d}'`).join(", ")}]`);else if(isObject(a)){let d=Je(a);n.push(`${r} ${l} ${d}`);}else n.push(`${r} ${l} ${a===null?"NONE":`'${a}'`}`);}}else throw new Error(`Invalid key ${r}`)}}else if(Array.isArray(i)){let o=r.startsWith("$")?r.replace("$",""):"IN";n.push(`${r} ${o} [${i.map(s=>s===null?"NONE":`'${s}'`).join(", ")}]`);}else {let o=r.startsWith("$")?r.replace("$",""):"=";n.push(`${r} ${o} ${i===null?"NONE":`'${i}'`}`);}}return n.join(" AND ")};var fo=async(e,t)=>{let n=c=>{let p=be(c);return p!==c?p:`\u27E8${c}\u27E9`},r=c=>{let{$filter:p,$thing:u,$bzId:f,$op:m,$id:h,$tempId:y}=c,$=oe(t,u),{usedDataFields:g}=$e($,c),{idFields:B}=$,E=h||c[B[0]],T=(isArray(u)?u:[u]).map(Y),A=me(c,F=>F.startsWith("$")),k=me(c,F=>!F.startsWith("$")),R=JSON.stringify(k),D=Object.entries(A).map(([F,b])=>F==="$tempId"?`'$tempId': '_:${b}'`:`'${F}': '${b}'`).join(","),I=c[ht],q=g.filter(F=>!B.includes(F)).map(F=>{let b=$.dataFields?.find(C=>C.path===F||C.dbPath===F);if(!b)throw new Error(`Data field schema not found for ${F}`);let Q=c[F];return Q===null?`${F} = NONE`:`${F} = ${pt(Q,b.contentType,t)}`}).filter(Boolean),ne=`$\u27E8${y||f}\u27E9`,L=`$\u27E8${y||f}_pre\u27E9`,O=I?.bzId?`array::flatten($\u27E8${I.bzId}_pre\u27E9.${n(I.edgeField)} || []).filter(|$v| $v != NONE).len`:E?isArray(E)?T.flatMap(F=>E.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):T.map(F=>`${F}:\u27E8${E}\u27E9`).join(", "):true,v=(()=>{if(I?.bzId){let F=`array::flatten($\u27E8${I.bzId}_pre\u27E9.${n(I.edgeField)} || []).filter(|$v| $v != NONE)`;return E?isArray(E)?`${F}[? $this.id() IN [${E.map(b=>`'${b}'`).join(", ")}] ]`:`${F}[? $this.id() IN ['${E}'] ]`:F}return E?isArray(E)?T.flatMap(F=>E.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):T.map(F=>`${F}:\u27E8${E}\u27E9`).join(", "):T.join(", ")})(),M=p?`WHERE ${Je(Qt(p,u,t))}`:"",w=q.length>0?`SET ${q.join(", ")}`:"",S=`VALUE (CREATE ONLY Delta SET input = ${R}, meta = {${D}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`;if(["link","unlink","replace"].includes(m))throw new Error("Edge ops don't belong to things");if(c.$op==="match")return y?"":`LET ${ne} = (SELECT VALUE id FROM ${v} ${M});
88
89
  LET ${L} = (SELECT * FROM ${v} ${M});`;if(c.$op==="create"){if(isArray(E))throw new Error("Cannot create multiple things at once");let F=Y(u);return `LET ${ne} = (CREATE ONLY ${F}:\u27E8${E}\u27E9 ${w} RETURN ${S});
89
90
  LET ${L} = ${ne};`}if(c.$op==="update")return `LET ${L} = IF (${O}) { (SELECT * FROM ${v} ${M}) };
90
91
  LET ${ne} = IF (${O}) { (UPDATE ${v} ${w} ${M} RETURN ${S}) };`;if(c.$op==="delete")return [`LET ${L} = IF (${O}) { (SELECT * FROM ${v} ${M}) };`,`LET ${ne} = IF (${L}) { array::flatten([${v}]) };`,`IF (${L}) { DELETE ${v} ${M} };`].join(`
@@ -104,37 +105,37 @@ LET ${ne} = IF (${O}) { (UPDATE ${v} ${w} ${M} RETURN ${S}) };`;if(c.$op==="dele
104
105
  }
105
106
  }
106
107
  }
107
- }`]}if(u==="delete")return `DELETE FROM ${m} WHERE array::flatten([${y}]) CONTAINSANY $\u27E8${g}\u27E9 AND array::flatten([${$}]) CONTAINSANY $\u27E8${B}\u27E9 RETURN BEFORE`},s=c=>{let{$thing:p,$bzId:u,$op:f,$tempId:m}=c,h=oe(t,p),{usedRefFields:y}=$e(h,c),$=`$\u27E8${m||u}\u27E9`,g=y.flatMap(T=>{let A=h.refFields[T];if(!A)throw new Error(`ReferenceField schema not found for ${T}`);let{cardinality:k,contentType:R}=A;if(R==="REF"){let D=isArray(c[T])?c[T]:[`${c[T]}`];if(k==="ONE"){if(D.length>1){let I=`array::filter(array::flatten([${D}]), |$v| !!$v)`;switch(f){case "link":case "replace":return `${T} = ${I}[0]`;case "unlink":return `${T} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}switch(f){case "link":case "replace":return `${T} = ((type::is_array(${D[0]}) && array::len(${D[0]})==1) && ${D[0]}[0]) || ${D[0]}`;case "unlink":return `${T} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}if(k==="MANY"){let I=`array::flatten([${D}])`;switch(f){case "link":return `${T} += ${I}`;case "unlink":return `${T} -= ${I}`;case "replace":return `${T} = ${I}`;default:throw new Error(`Unsupported operation ${f} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${k}`)}if(R==="FLEX"){if(k==="ONE")return `${T} = array::flatten([${c[T]}])[0]`;let I=(isArray(c[T])?c[T]:[c[T]]).map(q=>typeof q=="string"&&q.startsWith("$")?`array::flatten([${q}])[0]`:q);return `${T} = [${I.join(", ")}]`}throw new Error(`Unsupported contentType ${R}`)}),B=g.length>0?`${g.join(", ")}`:"",E=B?`SET ${B}`:"";return `IF ${$} { (UPDATE ${$} ${E} RETURN VALUE id) }; ${$};`},a=e.things.filter(c=>c.$op==="match"&&!c[ht]?.bzId),l=e.things.filter(c=>!(c.$op==="match"&&!c[ht]?.bzId));return [...a.map(r),...l.map(r),...e.edges.map(i),...e.arcs.flatMap(o),...e.references.map(s)]};var $o=e=>{let{res:t,config:n}=e;return t.flat().filter(Boolean).flatMap(i=>isArray(i)?i.filter(o=>isObject(o)&&"meta"in o).map(o=>ho(o,n)):!isObject(i)||!("meta"in i)?[]:ho(i,n))},ho=(e,t)=>{let n=mapEntries(e.after||{},(o,s)=>[o,o==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),r=me(e.input||{},(o,s)=>s===null),i={...n,...e.meta,...r};return t.mutation?.noMetadata?me(i,o=>!o.startsWith("$")):i};var yo=async(e,t)=>{let n=`
108
+ }`]}if(u==="delete")return `DELETE FROM ${m} WHERE array::flatten([${y}]) CONTAINSANY $\u27E8${g}\u27E9 AND array::flatten([${$}]) CONTAINSANY $\u27E8${B}\u27E9 RETURN BEFORE`},s=c=>{let{$thing:p,$bzId:u,$op:f,$tempId:m}=c,h=oe(t,p),{usedRefFields:y}=$e(h,c),$=`$\u27E8${m||u}\u27E9`,g=y.flatMap(T=>{let A=h.refFields[T];if(!A)throw new Error(`ReferenceField schema not found for ${T}`);let{cardinality:k,contentType:R}=A;if(R==="REF"){let D=isArray(c[T])?c[T]:[`${c[T]}`];if(k==="ONE"){if(D.length>1){let I=`array::filter(array::flatten([${D}]), |$v| !!$v)`;switch(f){case "link":case "replace":return `${T} = ${I}[0]`;case "unlink":return `${T} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}switch(f){case "link":case "replace":return `${T} = ((type::is_array(${D[0]}) && array::len(${D[0]})==1) && ${D[0]}[0]) || ${D[0]}`;case "unlink":return `${T} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}if(k==="MANY"){let I=`array::flatten([${D}])`;switch(f){case "link":return `${T} += ${I}`;case "unlink":return `${T} -= ${I}`;case "replace":return `${T} = ${I}`;default:throw new Error(`Unsupported operation ${f} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${k}`)}if(R==="FLEX"){if(k==="ONE")return `${T} = array::flatten([${c[T]}])[0]`;let I=(isArray(c[T])?c[T]:[c[T]]).map(q=>typeof q=="string"&&q.startsWith("$")?`array::flatten([${q}])[0]`:q);return `${T} = [${I.join(", ")}]`}throw new Error(`Unsupported contentType ${R}`)}),B=g.length>0?`${g.join(", ")}`:"",E=B?`SET ${B}`:"";return `IF ${$} { (UPDATE ${$} ${E} RETURN VALUE id) }; ${$};`},a=e.things.filter(c=>c.$op==="match"&&!c[ht]?.bzId),l=e.things.filter(c=>!(c.$op==="match"&&!c[ht]?.bzId));return [...a.map(r),...l.map(r),...e.edges.map(i),...e.arcs.flatMap(o),...e.references.map(s)]};var yo=e=>{let{res:t,config:n}=e;return t.flat().filter(Boolean).flatMap(i=>isArray(i)?i.filter(o=>isObject(o)&&"meta"in o).map(o=>mo(o,n)):!isObject(i)||!("meta"in i)?[]:mo(i,n))},mo=(e,t)=>{let n=mapEntries(e.after||{},(o,s)=>[o,o==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),r=me(e.input||{},(o,s)=>s===null),i={...n,...e.meta,...r};return t.mutation?.noMetadata?me(i,o=>!o.startsWith("$")):i};var go=async(e,t)=>{let n=`
108
109
  ${t.join(";")};
109
110
  LET $DELTAS = SELECT * FROM Delta;
110
111
  DELETE Delta;
111
112
  RETURN $DELTAS;
112
- `;ce(`>>> batchedMutation[${de}]`,JSON.stringify({batchedMutation:n}));let r;try{r=await e.beginTransaction();let i=await r.query(n);return await r.commit(),i.filter(Boolean)}catch(i){await r?.cancel().catch(()=>{});let o=i instanceof Error?i.message:String(i);V("runSURQLMutation",`runSURQLMutation/batchedMutation
113
- `,n),V("runSURQLMutation",`runSURQLMutation/error
114
- `,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 rc=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ic=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(n=>typeof n!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},oc=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Kn=U("error","error",W((e,t)=>({...e,error:t.error}))),sc=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},ac=Ce("buildMutation",{buildMutation:te(async e=>(ce(`>>> surqlMachine/buildMutation[${de}]`,JSON.stringify(e.bql.flat)),po(e.bql.flat,e.schema)),U("done","runMutation",W(ic)),Kn),runMutation:te(async e=>(ce(`>>> surqlMachine/runMutation[${de}]`,JSON.stringify(e.surql.mutations)),yo(sc(e.handles),e.surql.mutations)),U("done","parseMutation",W(oc)),Kn),parseMutation:te(async e=>(ce(`>>> surqlMachine/parseMutation[${de}]`,JSON.stringify(e.surql.res)),$o({res:e.surql.res,config:e.config,schema:e.schema})),U("done","success",W(rc)),Kn),success:Re(),error:Re()},e=>e),lc=async e=>new Promise((t,n)=>{_e(ac,r=>{r.machine.state.name==="success"&&t(r.context.bql.res),r.machine.state.name==="error"&&n(r.context.error);},e);}),Eo=async(e,t,n,r,i,o)=>lc({bql:{raw:e,enriched:t,flat:n,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:r,config:i,handles:o,error:null});var Jn=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 Fo=async(e,t,n)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!n)throw new Error("No schema provided");let r=u=>{let f=u.$op,m=`$${u.$bzId}`,h=z(n,u),{idFields:y,defaultDBConnector:$}=h,g=$?.path||u.$thing,B=u.$id,E=y?.[0],T=listify(u,(L,O)=>{if(L.startsWith("$")||L.startsWith("%")||L===E||O===void 0||O===null)return "";let v=h.dataFields?.find(S=>S.path===L);if(!v?.path)return "";let w=v.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(v.contentType))return `has ${w} '${O}'`;if(["NUMBER","BOOLEAN"].includes(v.contentType))return `has ${w} ${O}`;if(v.contentType==="DATE"){if(Number.isNaN(O.valueOf()))throw new Error("Invalid format, Nan Date");return O instanceof Date?`has ${w} ${O.toISOString().replace("Z","")}`:`has ${w} ${new Date(O).toISOString().replace("Z","")}`}if(v.contentType==="FLEX"){let S=`bza${Ue()}`,F=isArray(O)?O.map(b=>Jn(b)):Jn(O);if(Array.isArray(F))throw new Error("Array in FLEX fields not supported yet");return `has ${w} $${S}; $${S} '${S}' isa ${w}, has ${F.type}Attribute ${F.value}`}throw new Error(`Unsupported contentType ${v.contentType}`)}).filter(L=>L),A=`${m}-atts`,k=listify(u,L=>{if(L.startsWith("$")||L.startsWith("%")||L===E)return "";let O=h.dataFields?.find(w=>w.path===L);if(!O?.path)return "";let M=O.dbPath;return `{${A} isa ${M};}`}).filter(L=>L),R=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,D=B?[`has ${E} ${R}`]:[],I=[...D,...T].filter(L=>L).join(","),q=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${m} isa ${[g,...D].filter(L=>L).join(",")};`;if(f==="update"){if(!k.length)throw new Error("update without attributes");return `${m} isa ${[g,...D].filter(L=>L).join(",")}, has ${A};
115
- ${k.join(" or ")};`}return ""},ne=()=>f==="update"||f==="link"||f==="match"?`${m} isa ${[g,...D].filter(L=>L).join(",")};`:"";if(Yt(u))return {op:f,deletionMatch:q(),insertionMatch:ne(),insertion:f==="create"?`${m} isa ${[g,I].filter(L=>L).join(",")};`:f==="update"&&T.length?`${m} ${T.join(",")};`:"",deletion:f==="delete"?`${m} isa ${g};`:f==="update"&&k.length?`${m} has ${A};`:""};throw new Error("in attributes")},i=u=>{let f=u.$op,m=z(n,u),h=`$${u.$bzId}`,y=u.$id,$=m.defaultDBConnector?.path||u.$thing,g="roles"in m?listify(m.roles,O=>O):[],B="roles"in m?mapEntries(m.roles,(O,v)=>[O,v.dbConnector?.path||O]):{},E=listify(u,(O,v)=>{if(!g.includes(O))return null;if(!("roles"in m))throw new Error("This should have roles! ");let M=B[O];return Array.isArray(v)?v.map(w=>({path:M,id:w})):{path:M,id:v}}).filter(O=>O).flat(),T=E.map(O=>{if(!O?.path)throw new Error("Object without path");return `${O.path}: $${O.id}`}),A=E.length>0?`( ${T.join(" , ")} )`:"",k=u[et];if(!k)throw new Error("[internal error] Symbol edgeType not defined");let R=A?`${h} ${A} ${k==="linkField"||f==="delete"||f==="unlink"?`isa ${$}`:""}`:"",D=`${h} ${k==="linkField"||f==="delete"?`isa ${$}`:""}`,I=()=>R?f==="link"?`${R};`:f==="create"?`${R}, has id '${y}';`:"":"",q=()=>R&&f==="match"?`${R};`:"",ne=()=>R?f==="delete"?`${R};`:f==="match"?`${R};`:"":"",L=()=>R?f==="delete"?`${D};`:f==="unlink"?`${h} ${A};`:"":"";return {deletionMatch:ne(),insertionMatch:q(),deletion:L(),insertion:I(),op:""}},o=(u,f)=>{let m=f==="edges"?i:r;if(Array.isArray(u))return u.map(E=>{let{preDeletionBatch:T,insertionMatch:A,deletionMatch:k,insertion:R,deletion:D}=m(E);return shake({preDeletionBatch:T,insertionMatch:A,deletionMatch:k,insertion:R,deletion:D},I=>!I)}).filter(E=>E);let{preDeletionBatch:h,insertionMatch:y,deletionMatch:$,insertion:g,deletion:B}=m(u);return shake({preDeletionBatch:h,insertionMatch:y,deletionMatch:$,insertion:g,deletion:B},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(u=>u.insertionMatch).join(" ").trim(),deletionMatches:c.map(u=>u.deletionMatch).join(" ").trim(),insertions:c.map(u=>u.insertion).join(" ").trim(),deletions:c.map(u=>u.deletion).join(" ").trim()},u=>!u)};var bo=async(e,t,n,r,i)=>{let o=[...t,...n],s=o.map(a=>{let l=e.insertions?.find(p=>p.get(`${a.$bzId}`))?.get(`${a.$bzId}`),d=a.$thing||a.$relation||a.$entity,c=d?oe(r,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 p=l?.asThing().iid,u=Object.entries(a).filter(([m,h])=>!m.startsWith("$")).reduce((m,[h,y])=>{if(c?.dataFields?.find(g=>g.path===h)?.contentType==="JSON")return m[h]=JSON.parse(y),m;if(a.$thingType==="relation"){let g=o.filter(B=>B.$id&&B.$bzId===y);return g.length===1?(m[h]=g[0].$id,m):(m[h]=y,m)}return m[h]=y,m},{});if(i.mutation?.noMetadata)return u;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:p,...a,...u,[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 rn=async(e,t)=>{let n=t.dbConnectors[0].id,r=e.typeDB?.get(n)?.session,i=e.typeDB?.get(n)?.client;if(!r||!r.isOpen()){if(!i)throw new Error("Client not found");r=await i.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:i,session:r});}return {client:i,session:r}};var Ro=async(e,t,n)=>{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:r}=await rn(t,n),i=await r.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 hc=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),mc=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),$c=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Xn=U("error","error",W((e,t)=>({...e,error:t.error}))),yc=Ce("buildMutation",{buildMutation:te(async e=>Fo(e.bql.things,e.bql.edges,e.schema),U("done","runMutation",W(mc)),Xn),runMutation:te(async e=>Ro(e.tql.mutation,e.handles,e.config),U("done","parseMutation",W($c)),Xn),parseMutation:te(async e=>bo(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),U("done","success",W(hc)),Xn),success:Re(),error:Re()},e=>e),gc=async e=>new Promise((t,n)=>{_e(yc,r=>{r.machine.state.name==="success"&&t(r.context.bql.res),r.machine.state.name==="error"&&n(r.context.error);},e);}),To=async(e,t,n,r,i,o,s)=>gc({bql:{raw:e,enriched:t,things:n,edges:r,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:i,config:o,handles:s,error:null});var sn=(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 n=Array.isArray(e)?e:[e];return produce(n,i=>traverse(i,o=>{let{value:s,meta:a}=o,l=s;if(isObject(l)){if(a.nodePath?.includes(".$filter")||a.nodePath?.includes(".$playedBy"))return;if(l[Oe]=a.nodePath,l.$id){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=z(t,d);if(!c?.name)throw new Error(`Schema not found for ${l.$thing}`);if(l.$path=c.name,Array.isArray(l.$id)||(l.$filterByUnique=true),c.idFields.length===1){let[p]=c.idFields;l.$filter={...l.$filter,[p]: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=Je(l.$filter,l.$thing,t),l.$filterByUnique=er(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 u=l.$fields?.flatMap(f=>{let m=wo(f,c,t);return Array.isArray(m)?m:[m]}).filter(Boolean);l.$fields=u;}else {let u=Gn(c)?.flatMap(f=>{let m=wo(f,c,t);return Array.isArray(m)?m:[m]}).filter(Boolean);l.$fields=u;}l.$excludedFields&&(l.$fields=l.$fields.filter(p=>on(c,p)?true:!l.$excludedFields.includes(p.$path)));}}}))},Gn=e=>{let t=e.dataFields?.map(s=>s.path)||[],n=e.linkFields?.map(s=>s.path)||[],r=Object.keys(e.roles||{})||[],i=Object.keys(e.refFields||{})||[];return [...t,...n,...r,...i]},er=(e,t)=>Object.keys(e||{}).some(r=>{let i=e[r];if(i!==null&&typeof i<"u"){let o=t.idFields?.includes(r),s=t.dataFields?.some(d=>(d.dbPath===r||d.path===r)&&d?.validations?.unique),a=r==="$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}),on=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Fc=e=>{let{field:t,fieldStr:n,$justId:r,dbPath:i,isVirtual:o,fieldSchema:s}=e;return {$path:n,$dbPath:i,$thingType:"attribute",$as:t.$as||n,$var:n,$fieldType:"data",$justId:r,$id:t.$id,$isVirtual:o,[ze]:s}},bc=e=>{let{field:t,fieldStr:n,linkField:r,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e,{target:l,oppositeLinkFieldsPlayedBy:d}=r;return d.map(c=>{let p=l==="role"?c.thingType:"relation",u=l==="role"?c.thing:r.relation,f={[`$${p}`]:u},m=z(s,f),h=t?.$fields?.filter(g=>on(m,g)).length===0,y=[];if(typeof t!="string")if(t.$fields)if(h){let g=m.idFields||[];y=[...t.$fields,...g];}else y=t.$fields;else y=Gn(m);else y=["id"];t.$excludedFields&&(y=y.filter(g=>on(m,g)?true:!t.$excludedFields.includes(g.$path)));let $=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:p,$plays:r.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:o,$as:t.$as||n,$var:n,$thing:u,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:$,$idNotIncluded:h,$filterByUnique:er(t.$filter,m),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ze]:a}})},Rc=e=>{let{field:t,fieldStr:n,$justId:r,dbPath:i,fieldSchema:o}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:n,$dbPath:i,$contentType:o.contentType,$as:t.$as||n,$var:n,$fieldType:"ref",$justId:r,$fields:t.$fields,$id:t.$id,[ze]:o}},Tc=e=>{let{field:t,fieldStr:n,roleField:r,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e;return r.playedBy.map(l=>{let{thing:d,thingType:c,relation:p}=l,u={[`$${c}`]:d},f=z(s,u),m=t?.$fields?.filter($=>f?.idFields?.includes($)||f?.idFields?.includes($.$path)).length===0,h=[];if(typeof t!="string")if(t.$fields)if(m){let $=f.idFields||[];h=[...t.$fields,...$];}else h=t.$fields;else h=Gn(f);else h=["id"];t.$excludedFields&&(h=h.filter($=>on(f,$)?true:!t.$excludedFields.includes($.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:n,$dbPath:o,$as:t.$as||n,$var:n,$thing:d,$fields:h,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:p,$justId:i,$id:t.$id,$filter:y,$idNotIncluded:m,$filterByUnique:er(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ze]:a}})},wo=(e,t,n)=>{let r=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(d=>d.path===r),s=t.linkFields?.find(d=>d.path===r),a=t.roles?.[r],l=t.refFields?.[r];if(o){let d=!!o.isVirtual&&!!o.default;return Fc({field:e,fieldStr:r,$justId:i,dbPath:o.dbPath,isVirtual:d,fieldSchema:o})}return s?bc({field:e,fieldStr:r,linkField:s,$justId:i,dbPath:s.path,schema:n,fieldSchema:s}):a?Tc({field:e,fieldStr:r,roleField:a,$justId:i,dbPath:r,schema:n,fieldSchema:a}):l?Rc({field:e,fieldStr:r,$justId:i,dbPath:r,isVirtual:false,fieldSchema:l}):null},Je=(e,t,n)=>{if(e==null)return e;let r=isArray(e),o=(r?e:[e]).map(s=>Object.keys(s).reduce((d,c)=>{let p=s[c],u=isArray(p)?p:[p];if(c.startsWith("$"))if(["$id","$thing"].includes(c))d[c]=p;else if(["$not","$or","$and"].includes(c))d[c]=Je(p,t,n);else if(["$eq","$in","$exists"].includes(c))d[c]=p;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in n.entities?n.entities[t]:n.relations[t],[m,h]=vt(f,c);if(m==="idField")d[c]=p;else if(m==="dataField")isObject(p)||isArray(p)&&p.some(isObject)?d[c]=isArray(p)?{$or:Je(p,t,n)}:Je(p,t,n):isArray(p)?d[c]={$in:p}:d[c]={$eq:p};else if(m==="linkField"||m==="roleField"){let y=h,[$]=y.$things;u.every(g=>typeof g=="string")?d[c]={$id:u,$thing:$}:u.every(g=>isObject(g))&&(d[c]=isArray(p)?{$or:Je(p,$,n)}:Je(p,$,n));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return d},{}));return !r||o.length===1?o[0]:{$or:o}};var Sc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Mc=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,So=e=>{let n=e.toString().replace(Sc,"").trim().split("=>")[0].split("{")[0].replace(Mc,"").trim(),r=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return r?(r.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 Bt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=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(n){let{fn:r}=t.default,o=So(r).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 Mo=(e,t,n)=>{let r=e[t];if(r)return (isArray(r)?r:[r]).forEach(i=>{if(i.$op!=="create")return;let o=z(n,i),{unidentifiedFields:s}=$e(o,i),{computedFields:a,virtualFields:l}=o,d=listify(i,(u,f)=>f!==void 0?u:void 0),c=d.filter(u=>l?.includes(u));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(u=>!d.includes(u)).forEach(u=>{let f=o.dataFields?.find(g=>g.path===u),h=o.linkFields?.find(g=>g.path===u)?.oppositeLinkFieldsPlayedBy[0],y="roles"in o?$i(o.roles,(g,B)=>g===u):void 0,$=f||h||y;if(!$)throw new Error(`no field Def for ${u}`);if(!i[u]){let g=Bt({currentThing:i,fieldSchema:$,mandatoryDependencies:true});i[u]=g;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(i)}`)}),e};var tr=(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}_${Ue()}`:`SN_MANY_${Ue()}`:`SM_${Ue()}`;var Ze=(e,t,n)=>{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 r=z(n,t),{usedDataFields:i}=$e(r,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}},Lo=(e,t,n)=>{(isArray(t)?t:[t]).forEach(i=>{Ze(e,i,n);});};var Do=e=>{let t=Object.keys(e).filter(n=>!(n.startsWith("$")||n.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},ko=(e,t,n)=>{let r=z(n,t),{usedFields:i}=$e(r,t);return t.$op?(Ze(e,t,n),t.$op):t.$id||t.$filter?i.length>0?(Ze(e,{...t,$op:"update"},n),"update"):(Ze(e,{...t,$op:"link"},n),"link"):t.$tempId?i.length>0?(Ze(e,{...t,$op:"create"},n),"create"):(Ze(e,{...t,$op:"create"},n),"link"):(Ze(e,{...t,$op:"create"},n),"create")};var an=(e,t)=>{if(t[Z].fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}if(t[Z].fieldType==="roleField"){let n=t;if([...new Set(n.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n.playedBy}throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Oo=e=>isArray(e)?e.map(Oo):isObject(e)?{...e,[wt]:true}:e,No=(e,t,n,r)=>{let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);let s=Do(o),a=tr(o);if(n[Z].fieldType==="refField"){let c=n;if(!isObject(o)){if(c.contentType==="FLEX")return isArray(o)?[Oo(o)]:o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing){if(c.contentType==="FLEX")return {...o,[wt]:true};throw new Error("[Wrong format] The field $thing is required in refFields")}return {...o,$op:s,$bzId:a}}let l=n;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let d=n;if(d.$things.length===1){let c=an(t,l),[p]=c;if(o.$thing&&o.$thing!==p.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${p.thing}.`);return {...o,[Ne]:d,$thing:p.thing,$thingType:p.thing in r.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Ne]:d,$thing:o.$thing,$thingType:o.$thing in r.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 r.entities?"entity":"relation",$op:s,$bzId:tr(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var ln=(e,t)=>{let n=z(t,e).hooks;if(n?.pre){let r=`on${gi(e.$op)}`;return n.pre.filter(s=>!s.triggers||s.triggers[r]?.()).flatMap(s=>s.actions)}return []};var Io=(e,t,n,r)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!Yt(o)||o.$fields||o[En])return;let s=ln(o,n).filter(p=>p.type==="transform"),a=clone(Ie(e)),l=clone(Ie(o)),d=r.mutation?.context||{},c=clone(Ie(o[ft]||o.$dbNode));s.forEach(p=>{let u=p.fn(l,a,d,c||{});Object.keys(u).length!==0&&(l={...l,...u,...We(o),[En]:true},Object.assign(o,l));});});};var _o=(e,t,n,r)=>{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(n,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 p=d?.find(u=>u.path===c)?.validations?.enum;if(!p)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c])){for(let u of o[c])if(u!==null&&!p.includes(u))throw new Error(`[Validations] Option "${u}" is not a valid option for field "${c}".`)}else if(p&&!p.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 p=d?.find(u=>u.path===c)?.validations?.fn;if(!p)throw new Error("Missing validation function.");if(!p(o[c]))throw new Error("Failed validation function.")}catch(p){throw new Error(`[Validations:attribute:${c}] ${p.message}`)}}if(isObject(o)&&"$thing"in o){let c=o.$thing,p=o,u=clone(Ie(e)),f=clone(Ie(p)),m=r.mutation?.context||{},h=clone(Ie(o[ft]||{})),y=ln(p,n);for(let $ of y)if($.type==="validate"){if($.severity!=="error")continue;try{let g=$.fn(f,u,m,h);if(g===!1)throw new Error(`${$.message}.`);if(g!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(g){throw new Error(`[Validations:thing:${c}] ${g.message}`)}}}}};var jo=(e,t,n,r)=>{let i=isArray(e[t])?e[t]:[e[t]],o=r.slice(1).join(".");i.forEach(s=>{if(s){if(n?.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 qo=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:]+)$/),n=e.match(/^([^:]+):_:([^:]+)$/);if(t&&!e.includes(" ")){let[,r,i]=t;return {isPrefixed:true,obj:{$thing:r,$id:i}}}if(n&&!e.includes(" ")){let[,r,i]=n;return {isPrefixed:true,obj:{$thing:r,$tempId:`_:${i}`}}}return {isPrefixed:false,obj:e}},xo=(e,t,n)=>{let r=isArray(e[t])?e[t]:[e[t]];if(r.every(s=>typeof s=="object"))return;if(!r.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(r)})`);let i=e.$op==="update"&&n?.[Z].fieldType==="linkField"&&n.cardinality==="ONE",o=e.$op==="create"||i?"link":"replace";e[t]=r.map(s=>{if(typeof s=="string"){if(s.startsWith("_:"))return {$tempId:s,$op:o};let{isPrefixed:a,obj:l}=qo(s);return a?{...l,$op:o}:{$id:s,$op:o}}return s});},Vo=(e,t,n)=>{let r=isArray(e[t])?e[t]:[e[t]],i=e.$op==="create"?"link":"replace";return e[t]=r.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:i};let{isPrefixed:s,obj:a}=qo(o);if(s)return {...a,$op:i};if(n.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||n.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 Wo=(e,t)=>{let r=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=ko(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:yi(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${Ue()}`}},...i}});e.$root=isArray(e.$root)?r:r[0];};var cn=(e,t)=>{let n=t[Pt];return isSet(n)?n.has("clean")?(Reflect.set(t,Pt,n.add("clean")),true):false:(Reflect.set(t,Pt,new Set(["clean"])),true)};var Uo=(e,t,n)=>{if(cn("split_ids",e)){let r=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(isObject(i)&&"$id"in i&&isArray(i.$id)){let o=i;if(z(n,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}`,...We(o)}))}return i});(r.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=r);}};var vo=(e,t,n)=>{let r=an(t,n),[i]=r;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Ne]:n};};var Ft=e=>{if(Array.isArray(e)){for(let t of e)if(Ft(t))return true;return false}if(e.$fields)return true;for(let t in e){if(t.startsWith("$"))continue;let n=e[t];if(n&&typeof n=="object"&&Ft(e[t]))return true}return false};var zc=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(cn("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}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);},or=(e,t,n)=>{let r={$rootWrap:{$root:e}},i=Ft(Array.isArray(e)?e:[e]),o=produce(r,s=>traverse(s,({value:a,parent:l,key:d,meta:c})=>{if(!(!l||!d)&&isObject(a)){let p=c.nodePath?.split(".")||[];if(p.some(m=>m.startsWith("%"))||wt in a)return;if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let m=["$fields","$dbNode","$filter"],h=p.at(-1),y=p.at(-2);if(d==="$root")throw new Error("Root things must specify $entity or $relation");if(!m.includes(h||"")&&!m.includes(y||"")&&!h?.startsWith("%")&&!y?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let u=a,f=p.includes("$filter");"$filter"in u&&u.$filter&&(u.$filter=Je(u.$filter,u.$thing,t));for(let m of Object.keys(u)){if(zc(u,m),m!=="$root"&&f||m!=="$root"&&(m.startsWith("$")||m.startsWith("%")))continue;let h=m!=="$root"?Cn(t,u,m):{[Z]:{fieldType:"rootField"}};if(!h)throw new Error(`[Internal] Field ${m} not found in schema`);let{fieldType:y}=h[Z],$=["linkField","roleField"].includes(y),g=y==="refField",B=y==="rootField";if(y==="dataField"){continue}if(($||g)&&(u[m]===null?$&&vo(u,m,h):$?xo(u,m,h):Vo(u,m,h)),B){if(!("$root"in u))throw new Error(`[Internal] Field ${m} is a rootField but the object is not a root`);Wo(u,t);}if(($||g)&&jo(u,m,h,p),($||g)&&(No(u,m,h,t),Lo(u,u[m],t)),$||B){Uo(u,m,t),Mo(u,m,t);let E=isArray(u[m])?u[m]:[u[m]];for(let T of E){let A=z(t,T),{unidentifiedFields:k,usedLinkFields:R,usedFields:D,fields:I}=$e(A,T);for(let q of D)if(!I.includes(q))throw new Error(`[Schema] Field ${q} not found in the schema`);if(k.length>0)throw new Error(`Unknown fields: [${k.join(",")}] in ${JSON.stringify(a)}`);if(R.length>1){let q=A.linkFields?.filter(ne=>R.includes(ne.path));if(q)for(let ne=0;ne<q.length;ne++){let L=q[ne];for(let O=0;O<q.length;O++){let v=q[O];if(ne!==O&&L.target!==v.target&&L.relation===v.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}}}}i||(Io(u,m,t,n),_o(u,m,t,n));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Uc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ko=e=>e==null,Jo=e=>Array.isArray(e)&&e.length===0,Xo=e=>{let{batch:t,results:n,schema:r,metadata:i,returnNulls:o}=e;return t.map((s,a)=>vc({query:s,result:n[a],schema:r,metadata:i,returnNulls:o}))},vc=e=>{let{query:t,result:n,schema:r,metadata:i,returnNulls:o}=e;if(!n)return n??null;let s=r[t.$thing];if(!s)throw new Error(`Thing ${t.$thing} not found in schema`);return Array.isArray(n)?o&&n.length===0?null:n.map(a=>dn({query:t,result:a,thing:s,schema:r,metadata:i,returnNulls:o})):dn({query:t,result:n,thing:s,schema:r,metadata:i,returnNulls:o})},Hc=e=>{let{query:t,result:n,thing:r,schema:i,metadata:o,returnNulls:s}=e;return Array.isArray(n)?n.length===0?null:n.map(a=>dn({query:t,result:a,thing:r,schema:i,metadata:o,returnNulls:s})):dn({query:t,result:n,thing:r,schema:i,metadata:o,returnNulls:s})},dn=e=>{let{query:t,result:n,thing:r,schema:i,metadata:o,returnNulls:s}=e;if(!Uc(n))return null;let a={};o&&(a.$thing=n.$thing??null,a.$id=n.$id??null,a.$thingType=r.type);let l=t.$fields??Object.keys(r.fields);for(let d of l){let c=typeof d=="string"?d:d.$path,p=typeof d=="string"?d:d.$as??c;if(t.$excludedFields?.includes(c))continue;if(c==="$id"||c==="$thing"){a[p]=n[p]??null;continue}let u=r.fields[c];if(!u)throw new Error(`Field ${c} not found in ${r.name}`);if(u.type==="constant"){a[p]=u.value;continue}if(u.type==="computed"){a[p]=u.fn(n);continue}let f=n[p];if(u.type==="data"){if(!s&&Ko(f))continue;if(u.contentType==="JSON"){a[p]=jt(f)??null;continue}a[p]=Zo(f)??null;continue}if(!s&&(Ko(f)||Jo(f)))continue;if(typeof d=="string"||u.type==="ref"){a[p]=Jo(f)?null:Zo(f)??null;continue}let m=i[u.opposite.thing];a[p]=Hc({query:d,result:f,thing:m,schema:i,metadata:o,returnNulls:s});}return a},Zo=e=>Array.isArray(e)?e.map(t=>t instanceof DateTime?t.toDate():t):e instanceof DateTime?e.toDate():e;var Go=async e=>{let{client:t,queries:n,config:r,params:i}=e,o=n.join(`;
116
- `);return V("query",`query/batchedQuery
117
- `,o),r.query?.debugger&&ce(`batchedQuery[${de}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var es=async(e,t,n,r)=>{let i=nanoid(3);if(e.length===0)return [];let o=performance.now(),s=e.map(y=>Yr.parse(y));V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/bqlQueries"],`> runSurrealDbQueryMachine2/bqlQueries ${i}
118
- `,JSON.stringify(s));let a=s.map(y=>Kr(y,t,!n.query?.noMetadata));V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/logicalQueries"],`> runSurrealDbQueryMachine2/logicalQueries ${i}
119
- `,JSON.stringify(a));let l=a.map(y=>Ii(y,t));V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/optimizedQueries"],`> runSurrealDbQueryMachine2/optimizedQueries ${i}
120
- `,JSON.stringify(l));let d={},c=l.map(y=>Bi(y,d));V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/params"],`> runSurrealDbQueryMachine2/params ${i}
121
- `,JSON.stringify(d)),V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/surqlQueries"],`> runSurrealDbQueryMachine2/surqlQueries ${i}
122
- `,JSON.stringify(c));let p=performance.now(),u=await Go({client:r,queries:c,config:n,params:d}),f=performance.now();V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/queryDuration"],`> runSurrealDbQueryMachine2/queryDuration ${i}
123
- `,`${(f-p).toFixed(2)}ms`),V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/result"],`> runSurrealDbQueryMachine2/result ${i}
124
- `,JSON.stringify(u));let m=Xo({batch:s,results:u,schema:t,metadata:!n.query?.noMetadata,returnNulls:!!n.query?.returnNulls});V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/finalResult"],`> runSurrealDbQueryMachine2/finalResult ${i}
125
- `,m);let h=performance.now();return V(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/duration"],`> runSurrealDbQueryMachine2/duration ${i}
126
- `,`${(h-o).toFixed(2)}ms`),m};var is=(e,t)=>{if(!t)return;let n=Jc(t);return Zc(n,e.query)},Jc=e=>produce(e,t=>traverse(t,({value:n})=>{isObject(n);})),Zc=(e,t)=>produce(e,n=>traverse(n,({value:r})=>{if(isObject(r)){let i=r;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 os=async(e,t,n)=>n?(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,p=l[Oe];if(!p)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let u=getNodeByPath(t,p);if(u.$fieldType==="ref")return;let f=u.$fields.map(h=>h.$path),m=u.$excludedFields;c.forEach(h=>{if(m?.includes(h)||f.length>0&&!f.includes(h))return;let y=d.dataFields?.find($=>$.path===h);if(y?.default){let $=Bt({currentThing:l,fieldSchema:y,mandatoryDependencies:true});l[h]=$;}else if(l[h]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${h}`)}),m&&m.forEach(h=>{if(typeof h!="string")throw new Error("[Internal] ExcludedField is not a string");delete l[h];});}}})))(n):void 0;var un=e=>{let{$filter:t,$var:n,$thing:r,schema:i,depth:o}=e,s=od(t,oe(i,r)),{$not:a,...l}=s,d=[];if(ar(a)){let p=sr(a,n,r,i,o,true);d.push(...p);}else if(a!==void 0)throw new Error("$not must be a PositiveFilter object");let c=sr(l,n,r,i,o,false);return d.push(...c),d.join(`
127
- `)},sr=(e,t,n,r,i,o)=>{let s=oe(r,n),a=[];for(let[l,d]of Object.entries(e)){if(l.startsWith("$")){let u=l.toLowerCase();if(u==="$and"||u==="$or"){let m=(isArray(d)?d:[d]).map(y=>{if(ar(y))return sr(y,t,n,r,i+1,o).join(`
113
+ `;ce(`>>> batchedMutation[${de}]`,JSON.stringify({batchedMutation:n}));let r;try{r=await e.beginTransaction();let i=await r.query(n);return await r.commit(),i.filter(Boolean)}catch(i){await r?.cancel().catch(()=>{});let o=i instanceof Error?i.message:String(i);x("runSURQLMutation",`runSURQLMutation/batchedMutation
114
+ `,n),x("runSURQLMutation",`runSURQLMutation/error
115
+ `,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 ic=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),oc=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(n=>typeof n!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},sc=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Jn=U("error","error",W((e,t)=>({...e,error:t.error}))),ac=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},lc=Ce("buildMutation",{buildMutation:te(async e=>(ce(`>>> surqlMachine/buildMutation[${de}]`,JSON.stringify(e.bql.flat)),fo(e.bql.flat,e.schema)),U("done","runMutation",W(oc)),Jn),runMutation:te(async e=>(ce(`>>> surqlMachine/runMutation[${de}]`,JSON.stringify(e.surql.mutations)),go(ac(e.handles),e.surql.mutations)),U("done","parseMutation",W(sc)),Jn),parseMutation:te(async e=>(ce(`>>> surqlMachine/parseMutation[${de}]`,JSON.stringify(e.surql.res)),yo({res:e.surql.res,config:e.config,schema:e.schema})),U("done","success",W(ic)),Jn),success:Re(),error:Re()},e=>e),cc=async e=>new Promise((t,n)=>{_e(lc,r=>{r.machine.state.name==="success"&&t(r.context.bql.res),r.machine.state.name==="error"&&n(r.context.error);},e);}),Bo=async(e,t,n,r,i,o)=>cc({bql:{raw:e,enriched:t,flat:n,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:r,config:i,handles:o,error:null});var Zn=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var bo=async(e,t,n)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!n)throw new Error("No schema provided");let r=u=>{let f=u.$op,m=`$${u.$bzId}`,h=z(n,u),{idFields:y,defaultDBConnector:$}=h,g=$?.path||u.$thing,B=u.$id,E=y?.[0],T=listify(u,(L,O)=>{if(L.startsWith("$")||L.startsWith("%")||L===E||O===void 0||O===null)return "";let v=h.dataFields?.find(S=>S.path===L);if(!v?.path)return "";let w=v.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(v.contentType))return `has ${w} '${O}'`;if(["NUMBER","BOOLEAN"].includes(v.contentType))return `has ${w} ${O}`;if(v.contentType==="DATE"){if(Number.isNaN(O.valueOf()))throw new Error("Invalid format, Nan Date");return O instanceof Date?`has ${w} ${O.toISOString().replace("Z","")}`:`has ${w} ${new Date(O).toISOString().replace("Z","")}`}if(v.contentType==="FLEX"){let S=`bza${ve()}`,F=isArray(O)?O.map(b=>Zn(b)):Zn(O);if(Array.isArray(F))throw new Error("Array in FLEX fields not supported yet");return `has ${w} $${S}; $${S} '${S}' isa ${w}, has ${F.type}Attribute ${F.value}`}throw new Error(`Unsupported contentType ${v.contentType}`)}).filter(L=>L),A=`${m}-atts`,k=listify(u,L=>{if(L.startsWith("$")||L.startsWith("%")||L===E)return "";let O=h.dataFields?.find(w=>w.path===L);if(!O?.path)return "";let M=O.dbPath;return `{${A} isa ${M};}`}).filter(L=>L),R=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,D=B?[`has ${E} ${R}`]:[],I=[...D,...T].filter(L=>L).join(","),q=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${m} isa ${[g,...D].filter(L=>L).join(",")};`;if(f==="update"){if(!k.length)throw new Error("update without attributes");return `${m} isa ${[g,...D].filter(L=>L).join(",")}, has ${A};
116
+ ${k.join(" or ")};`}return ""},ne=()=>f==="update"||f==="link"||f==="match"?`${m} isa ${[g,...D].filter(L=>L).join(",")};`:"";if(Kt(u))return {op:f,deletionMatch:q(),insertionMatch:ne(),insertion:f==="create"?`${m} isa ${[g,I].filter(L=>L).join(",")};`:f==="update"&&T.length?`${m} ${T.join(",")};`:"",deletion:f==="delete"?`${m} isa ${g};`:f==="update"&&k.length?`${m} has ${A};`:""};throw new Error("in attributes")},i=u=>{let f=u.$op,m=z(n,u),h=`$${u.$bzId}`,y=u.$id,$=m.defaultDBConnector?.path||u.$thing,g="roles"in m?listify(m.roles,O=>O):[],B="roles"in m?mapEntries(m.roles,(O,v)=>[O,v.dbConnector?.path||O]):{},E=listify(u,(O,v)=>{if(!g.includes(O))return null;if(!("roles"in m))throw new Error("This should have roles! ");let M=B[O];return Array.isArray(v)?v.map(w=>({path:M,id:w})):{path:M,id:v}}).filter(O=>O).flat(),T=E.map(O=>{if(!O?.path)throw new Error("Object without path");return `${O.path}: $${O.id}`}),A=E.length>0?`( ${T.join(" , ")} )`:"",k=u[tt];if(!k)throw new Error("[internal error] Symbol edgeType not defined");let R=A?`${h} ${A} ${k==="linkField"||f==="delete"||f==="unlink"?`isa ${$}`:""}`:"",D=`${h} ${k==="linkField"||f==="delete"?`isa ${$}`:""}`,I=()=>R?f==="link"?`${R};`:f==="create"?`${R}, has id '${y}';`:"":"",q=()=>R&&f==="match"?`${R};`:"",ne=()=>R?f==="delete"?`${R};`:f==="match"?`${R};`:"":"",L=()=>R?f==="delete"?`${D};`:f==="unlink"?`${h} ${A};`:"":"";return {deletionMatch:ne(),insertionMatch:q(),deletion:L(),insertion:I(),op:""}},o=(u,f)=>{let m=f==="edges"?i:r;if(Array.isArray(u))return u.map(E=>{let{preDeletionBatch:T,insertionMatch:A,deletionMatch:k,insertion:R,deletion:D}=m(E);return shake({preDeletionBatch:T,insertionMatch:A,deletionMatch:k,insertion:R,deletion:D},I=>!I)}).filter(E=>E);let{preDeletionBatch:h,insertionMatch:y,deletionMatch:$,insertion:g,deletion:B}=m(u);return shake({preDeletionBatch:h,insertionMatch:y,deletionMatch:$,insertion:g,deletion:B},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(u=>u.insertionMatch).join(" ").trim(),deletionMatches:c.map(u=>u.deletionMatch).join(" ").trim(),insertions:c.map(u=>u.insertion).join(" ").trim(),deletions:c.map(u=>u.deletion).join(" ").trim()},u=>!u)};var Ro=async(e,t,n,r,i)=>{let o=[...t,...n],s=o.map(a=>{let l=e.insertions?.find(p=>p.get(`${a.$bzId}`))?.get(`${a.$bzId}`),d=a.$thing||a.$relation||a.$entity,c=d?oe(r,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 p=l?.asThing().iid,u=Object.entries(a).filter(([m,h])=>!m.startsWith("$")).reduce((m,[h,y])=>{if(c?.dataFields?.find(g=>g.path===h)?.contentType==="JSON")return m[h]=JSON.parse(y),m;if(a.$thingType==="relation"){let g=o.filter(B=>B.$id&&B.$bzId===y);return g.length===1?(m[h]=g[0].$id,m):(m[h]=y,m)}return m[h]=y,m},{});if(i.mutation?.noMetadata)return u;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:p,...a,...u,[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 on=async(e,t)=>{let n=t.dbConnectors[0].id,r=e.typeDB?.get(n)?.session,i=e.typeDB?.get(n)?.client;if(!r||!r.isOpen()){if(!i)throw new Error("Client not found");r=await i.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:i,session:r});}return {client:i,session:r}};var To=async(e,t,n)=>{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:r}=await on(t,n),i=await r.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 mc=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),$c=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),yc=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Gn=U("error","error",W((e,t)=>({...e,error:t.error}))),gc=Ce("buildMutation",{buildMutation:te(async e=>bo(e.bql.things,e.bql.edges,e.schema),U("done","runMutation",W($c)),Gn),runMutation:te(async e=>To(e.tql.mutation,e.handles,e.config),U("done","parseMutation",W(yc)),Gn),parseMutation:te(async e=>Ro(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),U("done","success",W(mc)),Gn),success:Re(),error:Re()},e=>e),Ec=async e=>new Promise((t,n)=>{_e(gc,r=>{r.machine.state.name==="success"&&t(r.context.bql.res),r.machine.state.name==="error"&&n(r.context.error);},e);}),wo=async(e,t,n,r,i,o,s)=>Ec({bql:{raw:e,enriched:t,things:n,edges:r,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:i,config:o,handles:s,error:null});var an=(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 n=Array.isArray(e)?e:[e];return produce(n,i=>traverse(i,o=>{let{value:s,meta:a}=o,l=s;if(isObject(l)){if(a.nodePath?.includes(".$filter")||a.nodePath?.includes(".$playedBy"))return;if(l[Oe]=a.nodePath,l.$id){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=z(t,d);if(!c?.name)throw new Error(`Schema not found for ${l.$thing}`);if(l.$path=c.name,Array.isArray(l.$id)||(l.$filterByUnique=true),c.idFields.length===1){let[p]=c.idFields;l.$filter={...l.$filter,[p]: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=Ze(l.$filter,l.$thing,t),l.$filterByUnique=tr(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 u=l.$fields?.flatMap(f=>{let m=So(f,c,t);return Array.isArray(m)?m:[m]}).filter(Boolean);l.$fields=u;}else {let u=er(c)?.flatMap(f=>{let m=So(f,c,t);return Array.isArray(m)?m:[m]}).filter(Boolean);l.$fields=u;}l.$excludedFields&&(l.$fields=l.$fields.filter(p=>sn(c,p)?true:!l.$excludedFields.includes(p.$path)));}}}))},er=e=>{let t=e.dataFields?.map(s=>s.path)||[],n=e.linkFields?.map(s=>s.path)||[],r=Object.keys(e.roles||{})||[],i=Object.keys(e.refFields||{})||[];return [...t,...n,...r,...i]},tr=(e,t)=>Object.keys(e||{}).some(r=>{let i=e[r];if(i!==null&&typeof i<"u"){let o=t.idFields?.includes(r),s=t.dataFields?.some(d=>(d.dbPath===r||d.path===r)&&d?.validations?.unique),a=r==="$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}),sn=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),bc=e=>{let{field:t,fieldStr:n,$justId:r,dbPath:i,isVirtual:o,fieldSchema:s}=e;return {$path:n,$dbPath:i,$thingType:"attribute",$as:t.$as||n,$var:n,$fieldType:"data",$justId:r,$id:t.$id,$isVirtual:o,[ze]:s}},Rc=e=>{let{field:t,fieldStr:n,linkField:r,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e,{target:l,oppositeLinkFieldsPlayedBy:d}=r;return d.map(c=>{let p=l==="role"?c.thingType:"relation",u=l==="role"?c.thing:r.relation,f={[`$${p}`]:u},m=z(s,f),h=t?.$fields?.filter(g=>sn(m,g)).length===0,y=[];if(typeof t!="string")if(t.$fields)if(h){let g=m.idFields||[];y=[...t.$fields,...g];}else y=t.$fields;else y=er(m);else y=["id"];t.$excludedFields&&(y=y.filter(g=>sn(m,g)?true:!t.$excludedFields.includes(g.$path)));let $=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:p,$plays:r.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:o,$as:t.$as||n,$var:n,$thing:u,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:$,$idNotIncluded:h,$filterByUnique:tr(t.$filter,m),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ze]:a}})},Tc=e=>{let{field:t,fieldStr:n,$justId:r,dbPath:i,fieldSchema:o}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:n,$dbPath:i,$contentType:o.contentType,$as:t.$as||n,$var:n,$fieldType:"ref",$justId:r,$fields:t.$fields,$id:t.$id,[ze]:o}},wc=e=>{let{field:t,fieldStr:n,roleField:r,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e;return r.playedBy.map(l=>{let{thing:d,thingType:c,relation:p}=l,u={[`$${c}`]:d},f=z(s,u),m=t?.$fields?.filter($=>f?.idFields?.includes($)||f?.idFields?.includes($.$path)).length===0,h=[];if(typeof t!="string")if(t.$fields)if(m){let $=f.idFields||[];h=[...t.$fields,...$];}else h=t.$fields;else h=er(f);else h=["id"];t.$excludedFields&&(h=h.filter($=>sn(f,$)?true:!t.$excludedFields.includes($.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:n,$dbPath:o,$as:t.$as||n,$var:n,$thing:d,$fields:h,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:p,$justId:i,$id:t.$id,$filter:y,$idNotIncluded:m,$filterByUnique:tr(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ze]:a}})},So=(e,t,n)=>{let r=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(d=>d.path===r),s=t.linkFields?.find(d=>d.path===r),a=t.roles?.[r],l=t.refFields?.[r];if(o){let d=!!o.isVirtual&&!!o.default;return bc({field:e,fieldStr:r,$justId:i,dbPath:o.dbPath,isVirtual:d,fieldSchema:o})}return s?Rc({field:e,fieldStr:r,linkField:s,$justId:i,dbPath:s.path,schema:n,fieldSchema:s}):a?wc({field:e,fieldStr:r,roleField:a,$justId:i,dbPath:r,schema:n,fieldSchema:a}):l?Tc({field:e,fieldStr:r,$justId:i,dbPath:r,isVirtual:false,fieldSchema:l}):null},Ze=(e,t,n)=>{if(e==null)return e;let r=isArray(e),o=(r?e:[e]).map(s=>Object.keys(s).reduce((d,c)=>{let p=s[c],u=isArray(p)?p:[p];if(c.startsWith("$"))if(["$id","$thing"].includes(c))d[c]=p;else if(["$not","$or","$and"].includes(c))d[c]=Ze(p,t,n);else if(["$eq","$in","$exists"].includes(c))d[c]=p;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in n.entities?n.entities[t]:n.relations[t],[m,h]=Ht(f,c);if(m==="idField")d[c]=p;else if(m==="dataField")isObject(p)||isArray(p)&&p.some(isObject)?d[c]=isArray(p)?{$or:Ze(p,t,n)}:Ze(p,t,n):isArray(p)?d[c]={$in:p}:d[c]={$eq:p};else if(m==="linkField"||m==="roleField"){let y=h,[$]=y.$things;u.every(g=>typeof g=="string")?d[c]={$id:u,$thing:$}:u.every(g=>isObject(g))&&(d[c]=isArray(p)?{$or:Ze(p,$,n)}:Ze(p,$,n));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return d},{}));return !r||o.length===1?o[0]:{$or:o}};var Mc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Ac=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Mo=e=>{let n=e.toString().replace(Mc,"").trim().split("=>")[0].split("{")[0].replace(Ac,"").trim(),r=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return r?(r.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 Ft=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=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(n){let{fn:r}=t.default,o=Mo(r).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 Ao=(e,t,n)=>{let r=e[t];if(r)return (isArray(r)?r:[r]).forEach(i=>{if(i.$op!=="create")return;let o=z(n,i),{unidentifiedFields:s}=$e(o,i),{computedFields:a,virtualFields:l}=o,d=listify(i,(u,f)=>f!==void 0?u:void 0),c=d.filter(u=>l?.includes(u));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(u=>!d.includes(u)).forEach(u=>{let f=o.dataFields?.find(g=>g.path===u),h=o.linkFields?.find(g=>g.path===u)?.oppositeLinkFieldsPlayedBy[0],y="roles"in o?yi(o.roles,(g,B)=>g===u):void 0,$=f||h||y;if(!$)throw new Error(`no field Def for ${u}`);if(!i[u]){let g=Ft({currentThing:i,fieldSchema:$,mandatoryDependencies:true});i[u]=g;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(i)}`)}),e};var nr=(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}_${ve()}`:`SN_MANY_${ve()}`:`SM_${ve()}`;var Xe=(e,t,n)=>{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 r=z(n,t),{usedDataFields:i}=$e(r,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}},Do=(e,t,n)=>{(isArray(t)?t:[t]).forEach(i=>{Xe(e,i,n);});};var ko=e=>{let t=Object.keys(e).filter(n=>!(n.startsWith("$")||n.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},Qo=(e,t,n)=>{let r=z(n,t),{usedFields:i}=$e(r,t);return t.$op?(Xe(e,t,n),t.$op):t.$id||t.$filter?i.length>0?(Xe(e,{...t,$op:"update"},n),"update"):(Xe(e,{...t,$op:"link"},n),"link"):t.$tempId?i.length>0?(Xe(e,{...t,$op:"create"},n),"create"):(Xe(e,{...t,$op:"create"},n),"link"):(Xe(e,{...t,$op:"create"},n),"create")};var ln=(e,t)=>{if(t[Z].fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}if(t[Z].fieldType==="roleField"){let n=t;if([...new Set(n.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n.playedBy}throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var No=e=>isArray(e)?e.map(No):isObject(e)?{...e,[St]:true}:e,Io=(e,t,n,r)=>{let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);let s=ko(o),a=nr(o);if(n[Z].fieldType==="refField"){let c=n;if(!isObject(o)){if(c.contentType==="FLEX")return isArray(o)?[No(o)]:o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing){if(c.contentType==="FLEX")return {...o,[St]:true};throw new Error("[Wrong format] The field $thing is required in refFields")}return {...o,$op:s,$bzId:a}}let l=n;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let d=n;if(d.$things.length===1){let c=ln(t,l),[p]=c;if(o.$thing&&o.$thing!==p.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${p.thing}.`);return {...o,[Ne]:d,$thing:p.thing,$thingType:p.thing in r.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Ne]:d,$thing:o.$thing,$thingType:o.$thing in r.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 r.entities?"entity":"relation",$op:s,$bzId:nr(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var cn=(e,t)=>{let n=z(t,e).hooks;if(n?.pre){let r=`on${Ei(e.$op)}`;return n.pre.filter(s=>!s.triggers||s.triggers[r]?.()).flatMap(s=>s.actions)}return []};var Co=(e,t,n,r)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!Kt(o)||o.$fields||o[Bn])return;let s=cn(o,n).filter(p=>p.type==="transform"),a=clone(Ie(e)),l=clone(Ie(o)),d=r.mutation?.context||{},c=clone(Ie(o[ft]||o.$dbNode));s.forEach(p=>{let u=p.fn(l,a,d,c||{});Object.keys(u).length!==0&&(l={...l,...u,...Ue(o),[Bn]:true},Object.assign(o,l));});});};var jo=(e,t,n,r)=>{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(n,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 p=d?.find(u=>u.path===c)?.validations?.enum;if(!p)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c])){for(let u of o[c])if(u!==null&&!p.includes(u))throw new Error(`[Validations] Option "${u}" is not a valid option for field "${c}".`)}else if(p&&!p.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 p=d?.find(u=>u.path===c)?.validations?.fn;if(!p)throw new Error("Missing validation function.");if(!p(o[c]))throw new Error("Failed validation function.")}catch(p){throw new Error(`[Validations:attribute:${c}] ${p.message}`)}}if(isObject(o)&&"$thing"in o){let c=o.$thing,p=o,u=clone(Ie(e)),f=clone(Ie(p)),m=r.mutation?.context||{},h=clone(Ie(o[ft]||{})),y=cn(p,n);for(let $ of y)if($.type==="validate"){if($.severity!=="error")continue;try{let g=$.fn(f,u,m,h);if(g===!1)throw new Error(`${$.message}.`);if(g!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(g){throw new Error(`[Validations:thing:${c}] ${g.message}`)}}}}};var Po=(e,t,n,r)=>{let i=isArray(e[t])?e[t]:[e[t]],o=r.slice(1).join(".");i.forEach(s=>{if(s){if(n?.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 xo=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:]+)$/),n=e.match(/^([^:]+):_:([^:]+)$/);if(t&&!e.includes(" ")){let[,r,i]=t;return {isPrefixed:true,obj:{$thing:r,$id:i}}}if(n&&!e.includes(" ")){let[,r,i]=n;return {isPrefixed:true,obj:{$thing:r,$tempId:`_:${i}`}}}return {isPrefixed:false,obj:e}},Vo=(e,t,n)=>{let r=isArray(e[t])?e[t]:[e[t]];if(r.every(s=>typeof s=="object"))return;if(!r.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(r)})`);let i=e.$op==="update"&&n?.[Z].fieldType==="linkField"&&n.cardinality==="ONE",o=e.$op==="create"||i?"link":"replace";e[t]=r.map(s=>{if(typeof s=="string"){if(s.startsWith("_:"))return {$tempId:s,$op:o};let{isPrefixed:a,obj:l}=xo(s);return a?{...l,$op:o}:{$id:s,$op:o}}return s});},zo=(e,t,n)=>{let r=isArray(e[t])?e[t]:[e[t]],i=e.$op==="create"?"link":"replace";return e[t]=r.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:i};let{isPrefixed:s,obj:a}=xo(o);if(s)return {...a,$op:i};if(n.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||n.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 Uo=(e,t)=>{let r=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=Qo(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:gi(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${ve()}`}},...i}});e.$root=isArray(e.$root)?r:r[0];};var dn=(e,t)=>{let n=t[qt];return isSet(n)?n.has("clean")?(Reflect.set(t,qt,n.add("clean")),true):false:(Reflect.set(t,qt,new Set(["clean"])),true)};var vo=(e,t,n)=>{if(dn("split_ids",e)){let r=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(isObject(i)&&"$id"in i&&isArray(i.$id)){let o=i;if(z(n,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}`,...Ue(o)}))}return i});(r.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=r);}};var Ho=(e,t,n)=>{let r=ln(t,n),[i]=r;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Ne]:n};};var bt=e=>{if(Array.isArray(e)){for(let t of e)if(bt(t))return true;return false}if(e.$fields)return true;for(let t in e){if(t.startsWith("$"))continue;let n=e[t];if(n&&typeof n=="object"&&bt(e[t]))return true}return false};var Wc=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(dn("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}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);},sr=(e,t,n)=>{let r={$rootWrap:{$root:e}},i=bt(Array.isArray(e)?e:[e]),o=produce(r,s=>traverse(s,({value:a,parent:l,key:d,meta:c})=>{if(!(!l||!d)&&isObject(a)){let p=c.nodePath?.split(".")||[];if(p.some(m=>m.startsWith("%"))||St in a)return;if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let m=["$fields","$dbNode","$filter"],h=p.at(-1),y=p.at(-2);if(d==="$root")throw new Error("Root things must specify $entity or $relation");if(!m.includes(h||"")&&!m.includes(y||"")&&!h?.startsWith("%")&&!y?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let u=a,f=p.includes("$filter");"$filter"in u&&u.$filter&&(u.$filter=Ze(u.$filter,u.$thing,t));for(let m of Object.keys(u)){if(Wc(u,m),m!=="$root"&&f||m!=="$root"&&(m.startsWith("$")||m.startsWith("%")))continue;let h=m!=="$root"?_n(t,u,m):{[Z]:{fieldType:"rootField"}};if(!h)throw new Error(`[Internal] Field ${m} not found in schema`);let{fieldType:y}=h[Z],$=["linkField","roleField"].includes(y),g=y==="refField",B=y==="rootField";if(y==="dataField"){continue}if(($||g)&&(u[m]===null?$&&Ho(u,m,h):$?Vo(u,m,h):zo(u,m,h)),B){if(!("$root"in u))throw new Error(`[Internal] Field ${m} is a rootField but the object is not a root`);Uo(u,t);}if(($||g)&&Po(u,m,h,p),($||g)&&(Io(u,m,h,t),Do(u,u[m],t)),$||B){vo(u,m,t),Ao(u,m,t);let E=isArray(u[m])?u[m]:[u[m]];for(let T of E){let A=z(t,T),{unidentifiedFields:k,usedLinkFields:R,usedFields:D,fields:I}=$e(A,T);for(let q of D)if(!I.includes(q))throw new Error(`[Schema] Field ${q} not found in the schema`);if(k.length>0)throw new Error(`Unknown fields: [${k.join(",")}] in ${JSON.stringify(a)}`);if(R.length>1){let q=A.linkFields?.filter(ne=>R.includes(ne.path));if(q)for(let ne=0;ne<q.length;ne++){let L=q[ne];for(let O=0;O<q.length;O++){let v=q[O];if(ne!==O&&L.target!==v.target&&L.relation===v.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}}}}i||(Co(u,m,t,n),jo(u,m,t,n));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var vc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Jo=e=>e==null,Zo=e=>Array.isArray(e)&&e.length===0,Go=e=>{let{batch:t,results:n,schema:r,metadata:i,returnNulls:o}=e;return t.map((s,a)=>Hc({query:s,result:n[a],schema:r,metadata:i,returnNulls:o}))},Hc=e=>{let{query:t,result:n,schema:r,metadata:i,returnNulls:o}=e;if(!n)return n??null;let s=r[t.$thing];if(!s)throw new Error(`Thing ${t.$thing} not found in schema`);return Array.isArray(n)?o&&n.length===0?null:n.map(a=>un({query:t,result:a,thing:s,schema:r,metadata:i,returnNulls:o})):un({query:t,result:n,thing:s,schema:r,metadata:i,returnNulls:o})},Yc=e=>{let{query:t,result:n,thing:r,schema:i,metadata:o,returnNulls:s}=e;return Array.isArray(n)?n.length===0?null:n.map(a=>un({query:t,result:a,thing:r,schema:i,metadata:o,returnNulls:s})):un({query:t,result:n,thing:r,schema:i,metadata:o,returnNulls:s})},un=e=>{let{query:t,result:n,thing:r,schema:i,metadata:o,returnNulls:s}=e;if(!vc(n))return null;let a={};o&&(a.$thing=n.$thing??null,a.$id=n.$id??null,a.$thingType=r.type);let l=t.$fields??Object.keys(r.fields);for(let d of l){let c=typeof d=="string"?d:d.$path,p=typeof d=="string"?d:d.$as??c;if(t.$excludedFields?.includes(c))continue;if(c==="$id"||c==="$thing"){a[p]=n[p]??null;continue}let u=r.fields[c];if(!u)throw new Error(`Field ${c} not found in ${r.name}`);if(u.type==="constant"){a[p]=u.value;continue}if(u.type==="computed"){a[p]=u.fn(n);continue}let f=n[p];if(u.type==="data"){if(!s&&Jo(f))continue;if(u.contentType==="JSON"){a[p]=Pt(f)??null;continue}a[p]=Xo(f)??null;continue}if(!s&&(Jo(f)||Zo(f)))continue;if(typeof d=="string"||u.type==="ref"){a[p]=Zo(f)?null:Xo(f)??null;continue}let m=i[u.opposite.thing];a[p]=Yc({query:d,result:f,thing:m,schema:i,metadata:o,returnNulls:s});}return a},Xo=e=>Array.isArray(e)?e.map(t=>t instanceof DateTime?t.toDate():t):e instanceof DateTime?e.toDate():e;var es=async e=>{let{client:t,queries:n,config:r,params:i}=e,o=n.join(`;
117
+ `);return x("query",`query/batchedQuery
118
+ `,o),r.query?.debugger&&ce(`batchedQuery[${de}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var ts=async(e,t,n,r)=>{let i=nanoid(3);if(e.length===0)return [];let o=performance.now(),s=e.map(y=>Kr.parse(y));x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/bqlQueries"],`> runSurrealDbQueryMachine2/bqlQueries ${i}
119
+ `,JSON.stringify(s));let a=s.map(y=>Jr(y,t,!n.query?.noMetadata));x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/logicalQueries"],`> runSurrealDbQueryMachine2/logicalQueries ${i}
120
+ `,JSON.stringify(a));let l=a.map(y=>Ci(y,t));x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/optimizedQueries"],`> runSurrealDbQueryMachine2/optimizedQueries ${i}
121
+ `,JSON.stringify(l));let d={},c=l.map(y=>Fi(y,d));x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/params"],`> runSurrealDbQueryMachine2/params ${i}
122
+ `,JSON.stringify(d)),x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/surqlQueries"],`> runSurrealDbQueryMachine2/surqlQueries ${i}
123
+ `,JSON.stringify(c));let p=performance.now(),u=await es({client:r,queries:c,config:n,params:d}),f=performance.now();x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/queryDuration"],`> runSurrealDbQueryMachine2/queryDuration ${i}
124
+ `,`${(f-p).toFixed(2)}ms`),x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/result"],`> runSurrealDbQueryMachine2/result ${i}
125
+ `,JSON.stringify(u));let m=Go({batch:s,results:u,schema:t,metadata:!n.query?.noMetadata,returnNulls:!!n.query?.returnNulls});x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/finalResult"],`> runSurrealDbQueryMachine2/finalResult ${i}
126
+ `,m);let h=performance.now();return x(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/duration"],`> runSurrealDbQueryMachine2/duration ${i}
127
+ `,`${(h-o).toFixed(2)}ms`),m};var os=(e,t)=>{if(!t)return;let n=Zc(t);return Xc(n,e.query)},Zc=e=>produce(e,t=>traverse(t,({value:n})=>{isObject(n);})),Xc=(e,t)=>produce(e,n=>traverse(n,({value:r})=>{if(isObject(r)){let i=r;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 ss=async(e,t,n)=>n?(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,p=l[Oe];if(!p)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let u=getNodeByPath(t,p);if(u.$fieldType==="ref")return;let f=u.$fields.map(h=>h.$path),m=u.$excludedFields;c.forEach(h=>{if(m?.includes(h)||f.length>0&&!f.includes(h))return;let y=d.dataFields?.find($=>$.path===h);if(y?.default){let $=Ft({currentThing:l,fieldSchema:y,mandatoryDependencies:true});l[h]=$;}else if(l[h]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${h}`)}),m&&m.forEach(h=>{if(typeof h!="string")throw new Error("[Internal] ExcludedField is not a string");delete l[h];});}}})))(n):void 0;var pn=e=>{let{$filter:t,$var:n,$thing:r,schema:i,depth:o}=e,s=sd(t,oe(i,r)),{$not:a,...l}=s,d=[];if(lr(a)){let p=ar(a,n,r,i,o,true);d.push(...p);}else if(a!==void 0)throw new Error("$not must be a PositiveFilter object");let c=ar(l,n,r,i,o,false);return d.push(...c),d.join(`
128
+ `)},ar=(e,t,n,r,i,o)=>{let s=oe(r,n),a=[];for(let[l,d]of Object.entries(e)){if(l.startsWith("$")){let u=l.toLowerCase();if(u==="$and"||u==="$or"){let m=(isArray(d)?d:[d]).map(y=>{if(lr(y))return ar(y,t,n,r,i+1,o).join(`
128
129
  `);throw new Error(`Invalid subfilter in ${u}: ${JSON.stringify(y)}`)}),h=m.join(u==="$and"?`
129
- `:" } or { ");u==="$or"&&m.length>1?a.push(N(`{ ${h} };`,i)):a.push(N(h,i));continue}continue}if(s.dataFields?.find(u=>u.dbPath===l||u.path===l)){let u=nd(l,d,t,i,o);a.push(...u);continue}let p=s.linkFields?.find(u=>u.path===l);if(p){let u=rd(p,d,t,r,i,o);a.push(...u);continue}if(s.thingType==="relation"){let u=s.roles[l];if(u){let f=id(u,d,t,n,r,i,o);a.push(...f);continue}}throw new Error(`"${n}" does not have property "${l}"`)}return a},nd=(e,t,n,r,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=`$${n} has ${e} ${Te(a)};`;break;case "$ne":d=`not { $${n} has ${e} ${Te(a)}; };`;break;case "$in":{if(!isArray(a))throw new Error("Value for $in operator must be an array");let c=a.map(p=>`$${n} has ${e} ${Te(p)};`);d=It(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 p=`not { $${n} has ${e} ${Te(c)}; };`;o.push(N(p,r));}continue;case "$exists":if(a===true)d=`$${n} has ${e} $${e}_${v4()};`;else if(a===false)d=`not { $${n} 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(N(d,r));}else if(isArray(t)){let s=t.map(l=>`$${n} has ${e} ${Te(l)};`),a=It(s);a&&(i&&(a=`not { ${a} };`),o.push(N(a,r)));}else {let s=`$${n} has ${e} ${Te(t)};`;i&&(s=`not { ${s} };`),o.push(N(s,r));}return o},rd=(e,t,n,r,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,d=oe(r,a.thing).idFields?.[0];if(!d)throw new Error(`"${a.thing}" does not have an id field`);let c=`${a.thing}_${v4()}`,p="";if(e.target==="relation")if(t===null)p=o?`(${e.plays}: $${n}) isa ${e.relation};`:`not { (${e.plays}: $${n}) isa ${e.relation}; };`;else if(isArray(t)){let u=t.map(f=>`(${e.plays}: $${n}) isa ${e.relation}, has ${d} ${Te(f)};`);p=It(u),o&&(p=`not { ${p} };`);}else p=`(${e.plays}: $${n}) isa ${e.relation}, has ${d} ${Te(t)};`,o&&(p=`not { ${p} };`);else if(t===null)p=o?`$${c} isa ${a.thing}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${a.thing}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let u=t.map(f=>`$${c} isa ${a.thing}, has ${d} ${Te(f)}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation};`);p=It(u),o&&(p=`not { ${p} };`);}else p=`$${c} isa ${a.thing}, has ${d} ${Te(t)}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation};`,o&&(p=`not { ${p} };`);return s.push(N(p,i)),s},id=(e,t,n,r,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=oe(i,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let p=`${l.thing}_${v4()}`,u=v4(),f=`${n}_${u}`;a.push(N(`$${f} isa ${r};`,o));let m="";if(t===null)m=`$${f} (${l.plays}: ${p});`,s?a.push(N(m,o)):a.push(N(`not { ${m} };`,o));else if(isArray(t)){let h=t.map(y=>`$${p} isa ${l.thing}, has ${c} ${Te(y)}; $${f} (${l.plays}: $${p});`);m=It(h),s?a.push(N(`not { ${m} };`,o)):a.push(N(m,o));}else m=`$${p} isa ${l.thing}, has ${c} ${Te(t)}; $${f} (${l.plays}: $${p});`,s?a.push(N(`not { ${m} };`,o)):a.push(N(m,o));return a.push(N(`$${n} is $${f};`,o)),a},It=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},Te=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("|")})$"`:Te(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},od=(e,t)=>{let n={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(n[s.path]=s.dbPath);}),Object.keys(n).length===0)return e;let{$not:r,...i}=e,o=ss(i,n);return r&&ar(r)&&(o.$not=ss(r,n)),o},ss=(e,t)=>{let n={};return Object.entries(e).forEach(([r,i])=>{let o=t[r]||r;n[o]=i;}),n},ar=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var lr="___",ls=async e=>{let{queries:t,schema:n}=e;return t.map(r=>sd({query:r,schema:n}))},sd=e=>{let{query:t,schema:n}=e,{$path:r,$thing:i,$filter:o,$fields:s,$sort:a,$offset:l,$limit:d,$id:c}=t;if(!r)throw new Error("Path is not defined");let p=[],u=t[Oe];if(p.push("match"),p.push(`$${r} isa ${i};`),o||c){let h=Ht(n,t),y={...o,...c?{[h]:c}:{}},$=un({$filter:y,$var:r,$thing:i,schema:n,depth:0});p.push(`
130
- ${$}`);}let f=pr({schema:n,$thing:i,$var:r,$sort:a,depth:0});f&&p.push(f.match);let m=`M_${v4()}`;if(p.push(`?queryPath${m} = "${u}";`),p.push("fetch"),p.push(`?queryPath${m} as "queryPath";`),s){let h=s.filter(g=>g.$fieldType==="data");h&&h.length>0&&p.push(...cr(h,r,0));let y=s.filter(g=>g.$fieldType==="link");y&&y.length>0&&p.push(...ur(y,r,r,0,n));let $=s.filter(g=>g.$fieldType==="role");$&&$.length>0&&p.push(...dr($,r,r,0,n));}return f&&p.push(f.sort),typeof l=="number"&&p.push(`
130
+ `:" } or { ");u==="$or"&&m.length>1?a.push(N(`{ ${h} };`,i)):a.push(N(h,i));continue}continue}if(s.dataFields?.find(u=>u.dbPath===l||u.path===l)){let u=rd(l,d,t,i,o);a.push(...u);continue}let p=s.linkFields?.find(u=>u.path===l);if(p){let u=id(p,d,t,r,i,o);a.push(...u);continue}if(s.thingType==="relation"){let u=s.roles[l];if(u){let f=od(u,d,t,n,r,i,o);a.push(...f);continue}}throw new Error(`"${n}" does not have property "${l}"`)}return a},rd=(e,t,n,r,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=`$${n} has ${e} ${Te(a)};`;break;case "$ne":d=`not { $${n} has ${e} ${Te(a)}; };`;break;case "$in":{if(!isArray(a))throw new Error("Value for $in operator must be an array");let c=a.map(p=>`$${n} has ${e} ${Te(p)};`);d=Ct(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 p=`not { $${n} has ${e} ${Te(c)}; };`;o.push(N(p,r));}continue;case "$exists":if(a===true)d=`$${n} has ${e} $${e}_${v4()};`;else if(a===false)d=`not { $${n} 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(N(d,r));}else if(isArray(t)){let s=t.map(l=>`$${n} has ${e} ${Te(l)};`),a=Ct(s);a&&(i&&(a=`not { ${a} };`),o.push(N(a,r)));}else {let s=`$${n} has ${e} ${Te(t)};`;i&&(s=`not { ${s} };`),o.push(N(s,r));}return o},id=(e,t,n,r,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,d=oe(r,a.thing).idFields?.[0];if(!d)throw new Error(`"${a.thing}" does not have an id field`);let c=`${a.thing}_${v4()}`,p="";if(e.target==="relation")if(t===null)p=o?`(${e.plays}: $${n}) isa ${e.relation};`:`not { (${e.plays}: $${n}) isa ${e.relation}; };`;else if(isArray(t)){let u=t.map(f=>`(${e.plays}: $${n}) isa ${e.relation}, has ${d} ${Te(f)};`);p=Ct(u),o&&(p=`not { ${p} };`);}else p=`(${e.plays}: $${n}) isa ${e.relation}, has ${d} ${Te(t)};`,o&&(p=`not { ${p} };`);else if(t===null)p=o?`$${c} isa ${a.thing}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${a.thing}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let u=t.map(f=>`$${c} isa ${a.thing}, has ${d} ${Te(f)}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation};`);p=Ct(u),o&&(p=`not { ${p} };`);}else p=`$${c} isa ${a.thing}, has ${d} ${Te(t)}; (${e.plays}: $${n}, ${a.plays}: $${c}) isa ${e.relation};`,o&&(p=`not { ${p} };`);return s.push(N(p,i)),s},od=(e,t,n,r,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=oe(i,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let p=`${l.thing}_${v4()}`,u=v4(),f=`${n}_${u}`;a.push(N(`$${f} isa ${r};`,o));let m="";if(t===null)m=`$${f} (${l.plays}: ${p});`,s?a.push(N(m,o)):a.push(N(`not { ${m} };`,o));else if(isArray(t)){let h=t.map(y=>`$${p} isa ${l.thing}, has ${c} ${Te(y)}; $${f} (${l.plays}: $${p});`);m=Ct(h),s?a.push(N(`not { ${m} };`,o)):a.push(N(m,o));}else m=`$${p} isa ${l.thing}, has ${c} ${Te(t)}; $${f} (${l.plays}: $${p});`,s?a.push(N(`not { ${m} };`,o)):a.push(N(m,o));return a.push(N(`$${n} is $${f};`,o)),a},Ct=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},Te=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("|")})$"`:Te(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},sd=(e,t)=>{let n={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(n[s.path]=s.dbPath);}),Object.keys(n).length===0)return e;let{$not:r,...i}=e,o=as(i,n);return r&&lr(r)&&(o.$not=as(r,n)),o},as=(e,t)=>{let n={};return Object.entries(e).forEach(([r,i])=>{let o=t[r]||r;n[o]=i;}),n},lr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var cr="___",cs=async e=>{let{queries:t,schema:n}=e;return t.map(r=>ad({query:r,schema:n}))},ad=e=>{let{query:t,schema:n}=e,{$path:r,$thing:i,$filter:o,$fields:s,$sort:a,$offset:l,$limit:d,$id:c}=t;if(!r)throw new Error("Path is not defined");let p=[],u=t[Oe];if(p.push("match"),p.push(`$${r} isa ${i};`),o||c){let h=Yt(n,t),y={...o,...c?{[h]:c}:{}},$=pn({$filter:y,$var:r,$thing:i,schema:n,depth:0});p.push(`
131
+ ${$}`);}let f=fr({schema:n,$thing:i,$var:r,$sort:a,depth:0});f&&p.push(f.match);let m=`M_${v4()}`;if(p.push(`?queryPath${m} = "${u}";`),p.push("fetch"),p.push(`?queryPath${m} as "queryPath";`),s){let h=s.filter(g=>g.$fieldType==="data");h&&h.length>0&&p.push(...dr(h,r,0));let y=s.filter(g=>g.$fieldType==="link");y&&y.length>0&&p.push(...pr(y,r,r,0,n));let $=s.filter(g=>g.$fieldType==="role");$&&$.length>0&&p.push(...ur($,r,r,0,n));}return f&&p.push(f.sort),typeof l=="number"&&p.push(`
131
132
  offset ${l};`),typeof d=="number"&&p.push(`
132
133
  limit ${d};`),p.join(`
133
- `)},cr=(e,t,n)=>{let r=[],i=[],o=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||r.push(e[c].$dbPath),e[c][ze].contentType==="FLEX"&&o.push({path:e[c][ze].dbPath}),i.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=r.join(", "),l=`$metadata:{as:[${i.join(",")}]}`,d=[N(`$${t} as "${t}.${l}.$dataFields": ${s};`,n)];return o.length>0&&o.forEach(c=>{d.push(N(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,n));}),d},dr=(e,t,n,r,i)=>{let o=r+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:p,$filterByUnique:u,$thing:f,$sort:m,$offset:h,$limit:y}=a,$=a[Oe],g=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${p},filterByUnique:${u}}`;s.push(N(`"${n}.${g}.${a.$var}": {`,r)),s.push(N("match",o));let B=`${t}${lr}${a.$var}`;if(s.push(N(`$${B} isa ${a.$thing};`,o)),s.push(N(`$${t} (${a.$var}: $${t}${lr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let T=Ht(i,a),A=a.$id?{[T]:a.$id}:{},k={...a.$filter,...A};s.push(un({$filter:k,$var:B,$thing:a.$thing,schema:i,depth:o}));}let E=pr({schema:i,$thing:f,$var:B,$sort:m,depth:o});if(E&&s.push(E.match),l){let T=`M_${v4()}`;s.push(N(`
134
- ?queryPath${T} = "${$}";`,o)),s.push(N("fetch",o)),s.push(N(`?queryPath${T} as "queryPath";`,o));let A=l?.filter(D=>D.$fieldType==="data");A&&A.length>0&&s.push(...cr(A,B,o));let k=l?.filter(D=>D.$fieldType==="link");k&&k.length>0&&s.push(...ur(k,B,`${t}.${a.$var}`,o,i));let R=l?.filter(D=>D.$fieldType==="role");R&&R.length>0&&s.push(...dr(R,B,`${t}.${a.$var}`,o,i));}E&&s.push(E.sort),typeof h=="number"&&s.push(N(`offset ${h};`,o)),typeof y=="number"&&s.push(N(`limit ${y};`,o)),s.push(N("};",r));}return s},ur=(e,t,n,r,i)=>{let o=r+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:p,$filterByUnique:u,$playedBy:f,$thing:m,$sort:h,$offset:y,$limit:$}=a,g=a[Oe],B=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${p},filterByUnique:${u}}`;s.push(N(`"${n}.${B}.${a.$var}": {`,r)),s.push(N("match",o));let E=`${t}${lr}${a.$var}`;if(s.push(N(`$${E} isa ${a.$thing};`,o)),a.$filter||a.$id){let A=Ht(i,a),k=a.$id?{[A]:a.$id}:{},R={...a.$filter,...k};s.push(un({$filter:R,$var:E,$thing:a.$thing,schema:i,depth:o}));}let T=pr({schema:i,$thing:m,$var:E,$sort:h,depth:o});if(T&&s.push(T.match),a.$target==="role"?s.push(N(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${E}) isa ${a.$intermediary};`,o)):s.push(N(`$${E} (${a.$plays}: $${t});`,o)),l){let A=`M_${v4()}`;s.push(N(`?queryPath${A} = "${g}";`,o)),s.push(N("fetch",o)),s.push(N(`?queryPath${A} as "queryPath";`,o));let k=l?.filter(I=>I.$fieldType==="data");k&&k.length>0&&s.push(...cr(k,E,o));let R=l?.filter(I=>I.$fieldType==="link");R&&R.length>0&&s.push(...ur(R,E,`${t}.${a.$var}`,o,i));let D=l?.filter(I=>I.$fieldType==="role");D&&D.length>0&&s.push(...dr(D,E,`${t}.${a.$var}`,o,i));}T&&s.push(T.sort),typeof y=="number"&&s.push(N(`offset ${y};`,o)),typeof $=="number"&&s.push(N(`limit ${$};`,o)),s.push(N("};",r));}return s},ad=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},pr=e=>{let{$var:t,$thing:n,schema:r,$sort:i,depth:o}=e,s=oe(r,n),a=[],l=[];if(i?.forEach(d=>{let c=ad(d),p=s.dataFields?.find(m=>m.path===c.field);if(!p)throw new Error(`"${n}" does not have data field "${c.field}"`);let u=`${c.field}_${v4()}`;a.push(N("{",o)),a.push(N(`$${t} has ${p.dbPath} $${u}_1;`,o+1)),a.push(N("not {",o+1)),a.push(N(`$${t} has ${p.dbPath} $${u}_2;`,o+2)),a.push(N(`$${u}_2 < $${u}_1;`,o+2)),a.push(N("};",o+1)),a.push(N(`?${u}_ = $${u}_1;`,o+1)),a.push(N("} or {",o)),a.push(N(`not { $${t} has ${p.dbPath} $${u}_1; };`,o+1)),a.push(N(`?${u}_ = "~";`,o+1)),a.push(N("};",o)),a.push(N(`?${u} = ?${u}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${u} ${f}`);}),a.length!==0)return {match:a.join(""),sort:N(`sort ${l.join(", ")};`,o)}};var ds=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:n,schema:r,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=n[a],d=t[a];return cd(s,l,d,r,i)})},cd=(e,t,n,r,i)=>e.length===0?null:n.$filterByUnique?cs(e[0],t,r,i):e.map(o=>cs(o,t,r,i)),cs=(e,t,n,r)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=fr(e,n),d=hr(i,o,r),c=$r(s,n,r),p=mr(a,n,r),u=t?.$fields?.every(m=>!o?.idFields?.includes(typeof m=="string"?m:m.$path));return {...c,...p,...l,...!r.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?d.id:t.$id}:{},...u?Object.fromEntries(Object.entries(d).filter(([m])=>!o?.idFields?.includes(m))):d}},fr=(e,t)=>{let n=Object.keys(e),r=n.find(f=>f.endsWith(".$dataFields")),i=n.filter(f=>f.endsWith(".$multiVal"));if(!r)throw new Error("No dataFields");if(i?.length>0)for(let f of i){let m=f.replace(/\.\$multiVal$/,""),h=e[f][0][m].attribute;e[r][m]=h;}let o=e[r],s=r.split(".")[r.split(".").length-2];if(o.$metaData=s,o.length===0)throw new Error("No dataFields");let a=o.type,l={$thing:a.label,$thingType:a.root,[Oe]:e.queryPath.value},d={[`$${l.$thingType}`]:l.$thing},c=z(t,d),p=n.filter(f=>{let m=Ae(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some(h=>h.path===m)}).map(f=>{let m=Ae(f.split(".").pop()),h=Ae(c.linkFields?.find(y=>y.path===m));return {$linkFields:e[f],$key:m,$metaData:f.split(".")[f.split(".").length-2],$cardinality:h.cardinality}}),u=n.filter(f=>{let m=f.split(".").pop();return m&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[m]}).map(f=>{let m=Ae(f.split(".").pop());return {$roleFields:e[f],$key:m,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[m].cardinality}});return {dataFields:o,schemaValue:l,currentSchema:c,linkFields:p,roleFields:u}},hr=(e,t,n)=>{let{$metaData:r}=e,{as:i}=dd(r),o=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).flatMap(([s,a])=>{let l=t.dataFields?.find(u=>u.path===s||u.dbPath===s),d=s==="id",c=Array.isArray(i)?i.find(u=>u[s])?.[s]:s,p;if(l?.cardinality==="ONE"){if(p=a[0]?a[0].value:n.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&a[0].type.value_type==="datetime"?p=p&&`${p}Z`:l.contentType==="JSON"&&(p=p&&JSON.parse(p)),d)return [[c,p],["$id",p]].filter(([u,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 n.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?p=a.map(u=>`${u.value}Z`):l.contentType==="FLEX"?p=a.map(u=>u.type.value_type==="datetime"?`${u.value}Z`:u.value):l.contentType==="JSON"?p=a.map(u=>u.value&&JSON.parse(u.value)):p=a.map(u=>u.value);}return [[c,p]].filter(([u,f])=>f!==void 0)});return Object.fromEntries([...o])},mr=(e,t,n)=>{let r={};for(let i of e){let{$roleFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:p}=us(s);if(l===null)continue;let u=o.map(f=>{let{dataFields:m,currentSchema:h,linkFields:y,roleFields:$,schemaValue:g}=fr(f,t),B=hr(m,h,n);if(d==="T")return B.id;let E=$r(y,t,n),T=mr($,t,n),A={...B};if(c==="true"&&h?.idFields)for(let k of h.idFields)delete A[k];return {...A,...E,...T,...g}});u.length>0?r[l]=a==="MANY"&&p==="false"?u:u[0]:n.query?.returnNulls&&(r[l]=null);}return r},$r=(e,t,n)=>{let r={};for(let i of e){let{$linkFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:p}=us(s);if(l===null)continue;let u=o.map(f=>{let{dataFields:m,currentSchema:h,linkFields:y,roleFields:$,schemaValue:g}=fr(f,t),B=hr(m,h,n);if(d==="T")return B.id;let E=$r(y,t,n),T=mr($,t,n),A={...B};if(c==="true")for(let k of h.idFields??[])delete A[k];return {...A,...E,...T,...g}});r[l]=u.length>0?a==="MANY"&&p==="false"?u:u[0]:n.query?.returnNulls?null:void 0;}return r},us=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,r=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,o=e.match(t),s=e.match(n),a=e.match(r),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}},dd=e=>{try{let n=(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(n)}catch(t){return console.error(t),{as:[]}}};var ps=async e=>{let{tqlRequest:t,dbHandles:n,config:r}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await rn(n,r),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 md=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,yr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,$d=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,yd=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,bt=U("error","error",W((e,t)=>({...e,error:t.error}))),gd=Ce("enrich",{enrich:te(async e=>(ce(`originalBQLQuery[${de}]`,JSON.stringify(e.bql.raw)),sn(e.bql.raw,e.schema)),U("done","build",W(md)),bt),build:te(async e=>ls({queries:e.bql.queries??[],schema:e.schema}),U("done","run",W($d)),bt),run:te(async e=>ps({dbHandles:e.handles,tqlRequest:Ae(e.tql.queries),config:e.config}),U("done","parse",W(yd)),bt),parse:te(async e=>ds({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:Ae(e.tql.res)}),U("done","postHooks",W(yr)),bt),postHooks:te(async e=>os(e.schema,Ae(e.bql.queries),Ae(e.bql.res)),U("done","clean",W(yr)),bt),clean:te(async e=>is(e.config,Ae(e.bql.res)),U("done","success",W(yr)),bt),success:Re(),error:Re()},e=>e),Ed=async e=>new Promise((t,n)=>{_e(gd,r=>{r.machine.state.name==="success"&&t(r.context.bql.res),r.machine.state.name==="error"&&n(r.context.error);},e);}),fs=async(e,t,n,r)=>Ed({bql:{raw:e},tql:{},schema:t,config:n,handles:r,error:null});var Bd=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Fd=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,hs=U("error","error",W((e,t)=>({...e,error:t.error}))),bd=Ce("enrich",{enrich:te(async e=>(ce(`originalBQLQuery[${de}]`,JSON.stringify(e.bql.raw)),sn(e.bql.raw,e.schema)),U("done","adapter",W(Bd)),hs),adapter:te(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 p=oe(e.schema,c),{id:u}=p.defaultDBConnector;if(p.db==="typeDB"){if(!t[u]){let m=e.handles.typeDB?.get(u)?.client;if(!m)throw new Error(`TypeDB client with id "${p.defaultDBConnector.id}" does not exist`);t[u]={db:"typeDB",client:m,rawBql:[],indices:[]};}}else if(p.db==="surrealDB"){if(!t[u]){let m=e.handles.surrealDB?.get(u)?.client;if(!m)throw new Error(`SurrealDB client with id "${p.defaultDBConnector.id}" does not exist`);t[u]={db:"surrealDB",client:m,rawBql:[],indices:[]};}}else throw new Error(`Unsupported DB "${p.db}"`);let f=t[u];f.rawBql.push(d),f.indices.push(l);});let n=Object.values(t),r=n.map(a=>{if(a.db==="typeDB")return fs(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return es(a.rawBql,e.draftSchema,e.config,a.client);throw new Error(`Unsupported DB "${JSON.stringify(a,null,2)}"`)}),i=await Promise.all(r),o=n.flatMap((a,l)=>{let d=i[l];return a.indices.map((c,p)=>({index:c,result:d[p]}))});return o.sort((a,l)=>a.index<l.index?-1:a.index>l.index?1:0),o.map(({result:a})=>a)},U("done","success",W(Fd)),hs),success:Re(),error:Re()},e=>e),Rd=async e=>new Promise((t,n)=>{_e(bd,r=>{r.machine.state.name==="success"&&t(r.context),r.machine.state.name==="error"&&n(r.context);},e);}),Rt=async(e,t,n,r,i)=>Rd({bql:{raw:e},schema:t,draftSchema:n,config:r,handles:i,error:null});var gs=async(e,t,n,r,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(d=>gr(d,true)),l=(await Rt(s,t,n,r,i)).bql.res;return o.map((d,c)=>{let p=oe(t,d.$thing);return Bs({mut:d,node:l[c],schema:t,thing:p})})},Es=new Set(["$op","$bzId","$parentKey"]),wd=new Set(["$relation","$entity","$id",...Es]),gr=(e,t)=>{let n={};e.$fields?.forEach(i=>{typeof i=="string"?n[i]=i:n[i.$path]=i;});let r={};for(let i in e){if(Es.has(i)||wd.has(i)&&!t)continue;let o=e[i];i.startsWith("$")?r[i]=o:Array.isArray(o)?o[0]&&typeof o[0]=="object"&&(n[i]={$path:i,...gr(o[0],false)}):isObject(o)&&(n[i]={$path:i,...gr(o,false)});}return r.$fields=Object.values(n),r},Bs=e=>{let{mut:t,node:n,schema:r,thing:i}=e,o=bs(i),s=Md(n);if(Array.isArray(t))return t.map(l=>{let d=s[l.$id];return d?ms({mut:l,node:d,schema:r,thing:i,...o}):l});let a=s[t.$id];return ms({mut:t,node:a,schema:r,thing:i,...o})},ms=e=>{let{mut:t,node:n,schema:r,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,{$fields:l,...d}=t;if(!n)return d;let c=Fs({$fields:t.$fields,node:n,schema:r,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),p={...d,[ft]:c};for(let u in t){if(u.startsWith("$"))continue;let f=t[u];if(o[u]||!f||typeof f!="object"){p[u]=f;continue}let h=s[u]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[u]?.playedBy?.[0]?.thing;if(!h)throw new Error(`"${i.name}" does not have field "${u}"`);let y=oe(r,h);p[u]=Bs({mut:f,schema:r,node:n[u],thing:y});}return p},Fs=e=>{let{$fields:t,node:n,schema:r,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Sd(i),d={$id:n.$id};return l.forEach(c=>{let p=typeof c!="string",u=p?c.$path:c,f=n[u];if(o[u]){d[u]=f;return}let h=s[u]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[u]?.playedBy?.[0]?.thing;if(!h)throw new Error(`"${i.name}" does not have field "${u}"`);if(!p){f&&(d[u]=Array.isArray(f)?f.map($s):$s(f));return}let y=oe(r,h),$=bs(y);d[u]=Array.isArray(f)?f.map(g=>ys({...$,$fields:c.$fields,value:g,schema:r,thing:y})):ys({...$,$fields:c.$fields,value:f,schema:r,thing:y});}),d},Sd=e=>{let t=[];return e.dataFields?.forEach(n=>{t.push(n.path);}),e.linkFields?.forEach(n=>{t.push(n.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},$s=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},ys=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 Fs({...e,node:t})},bs=e=>{let t=Object.fromEntries(e.dataFields?.map(i=>[i.path,i])||[]),n=Object.fromEntries(e.linkFields?.map(i=>[i.path,i])||[]),r=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:n,roleFieldMap:r}},Md=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(n=>{!n||typeof n!="object"||!n.$id||(t[n.$id]=n);}),t};var Rs=(e,t)=>{let n={things:[],edges:[],arcs:[],references:[]},r=(s,a)=>{if(!s?.$thing)return;let{$op:l,$bzId:d,$tempId:c}=s,p=t.relations[s.$thing]||t.entities[s.$thing];if(!p)throw new Error(`[Internal] No schema found for ${s.$thing}`);let u=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:m,usedRoleFields:h,usedRefFields:y}=$e(p,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let g={...me(s,B=>![...h,...m,...y].includes(B)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[ht]:u}};n.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=me(s,B=>isSymbol(B)||B.startsWith("$"));for(let B of h){if(isArray(s[B]))for(let T of s[B])r(T,{bzId:d,edgeField:B,tempId:c});else r(s[B],{bzId:d,edgeField:B,tempId:c});let E=(isArray(s[B])?s[B]:[s[B]]).filter(Boolean);for(let[T,A]of Object.entries($)){let k=E.filter(R=>A.includes(R.$op)).map(R=>R.$bzId);k.length>0&&n.edges.push({...g,[B]:k,$op:T});}}}if(m)for(let g of m){if(isArray(s[g]))for(let T of s[g])r(T,{bzId:d,edgeField:g,tempId:c});else r(s[g],{bzId:d,edgeField:g,tempId:c});let B=p.linkFields?.find(T=>T.path===g),E=isArray(s[g])?s[g]:[s[g]];if(B.target==="relation")for(let[T,A]of Object.entries($)){let k=E.filter(R=>A.includes(R.$op));for(let R of k){let D=me(R,I=>isSymbol(I)||I.startsWith("$"));n.edges.push({...D,[B.plays]:d,$op:T});}}if(B.target==="role"){let T={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[A,k]of Object.entries(T)){let R=E.filter(D=>k.includes(D.$op));if(R.length!==0)for(let D of R){let I={$thing:B.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[B.plays]:d,[B.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:A};n.arcs.push(I);}}}}if(y)for(let g of y){if(isArray(s[g]))for(let A of s[g])r(A,{bzId:d,edgeField:g,tempId:c});else r(s[g],{bzId:d,edgeField:g,tempId:c});let B=(isArray(s[g])?s[g]:[s[g]]).filter(A=>A!=null),E=me(s,A=>isSymbol(A)||A.startsWith("$")),T=B.map(A=>A.$op?`$\u27E8${A.$bzId}\u27E9`:pt(A,"FLEX"));T.length>0&&n.references.push({...E,[g]:T,$op:"replace"});}},i=Array.isArray(e)?e:[e];for(let s of i)r(s);let o=[...n.edges].sort((s,a)=>{let l=["unlink","link"];return l.indexOf(s.$op)-l.indexOf(a.$op)});return {...n,edges:o}};var Ms=async(e,t)=>{let n=c=>{let p=[],u=[],f=$=>{if($.$id)return $.$id;let g=z(t,$),{idFields:B}=g;if(!B)throw new Error(`no idFields: ${JSON.stringify($)}`);let[E]=B;if(!E)throw new Error(`no idField: ${JSON.stringify($)}`);let T=g.dataFields?.find(R=>R.path===E),A=Bt({currentThing:$,fieldSchema:T,mandatoryDependencies:true}),k=$[E]||$.$id||A;if(!k)throw new Error(`no idValue: ${JSON.stringify($)}`);return k},m=$=>{if($.$op==="create"){let g=f($);if(p.find(B=>B.$id===g&&B.$op==="create"))throw new Error(`Duplicate id ${g} for node ${JSON.stringify($)}`);p.push({...$,$id:g});return}$.$tempId&&$.$op==="match"||p.push($);},h=$=>{if($.$op==="create"){let g=f($);if(p.find(B=>B.$id===g&&B.$op==="create"))throw new Error(`Duplicate id ${g} for edge ${JSON.stringify($)}`);u.push({...$,$id:g});return}u.push($);};return traverse(c,({value:$,parent:g,meta:B})=>{if(!isObject($))return;let E=$;if(!B.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 T=z(t,E),{dataFields:A,roleFields:k,linkFields:R,refFields:D,usedFields:I}=$e(T,E),q=()=>{if(E.$op==="create"||E.$op==="delete")return E.$op;if(E.$op==="update"){let O=I.filter(S=>A?.includes(S)),v=I.filter(S=>k?.includes(S)),M=I.filter(S=>R?.includes(S)),w=I.filter(S=>D?.includes(S));if(O.length>0)return "update";if(v.length>0||M.length>0||w.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(E)}`)}return "match"},ne={...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,A||[""])),$op:q(),$bzId:E.$bzId};m(ne);let L=E[Ne];if(L?.[Z].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");p.push({...E,$op:"match"});}let O=L.$things.includes(E.$thing),v=O?E.$bzId:`LT_${v4()}`,w=Ei(c,g,B).$bzId;if(!w)throw new Error("No parent id found");let S=()=>E.$op==="delete"?O?"match":"delete":E.$op==="unlink"?O?"unlink":"delete":E.$op==="link"||E.$op==="create"?O?"link":"create":E.$op==="replace"?"replace":"match",F=z(t,{$thing:L.relation,$thingType:"relation"});if(!Object.keys(F.roles).includes(L.plays))throw new Error(`[Wrong format] Field ${L.plays} is not a role of relation ${L.relation}`);let Q={$bzId:v,$thing:O?E.$thing:L.relation,$thingType:"relation",...E.$tempId?{$tempId:E.$tempId}:{},$op:S(),...O?{}:{[L.path]:E.$bzId},[L.plays]:w,[Ne]:L,[et]:"linkField"};h(Q),(E.$op==="unlink"||S()==="unlink")&&O&&h({$thing:L.relation,$thingType:"relation",$bzId:v,$op:"match",[L.plays]:w,[Ne]:L,[et]:"linkField"});}if(E.$thingType==="relation"){let O=me(E,(w,S)=>k.includes(w)),v=mapEntries(O,(w,S)=>isArray(S)?[w,S]:isObject(S)?[w,S.$bzId]:[w,S]),M=me($,(w,S)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(O).filter(w=>!w.startsWith("$")).length>0){if(E.$op==="create"||E.$op==="delete"){let w=()=>{if(E.$op==="create")return "link";if(E.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=z(t,E).roles,F=mapEntries(v,(Q,C)=>{let H=S[Q]?.cardinality;if(!H)throw new Error(`Role ${Q} not found in schema`);return Array.isArray(C)?H==="ONE"?C.length>1?[Q,C.map(j=>j.$bzId||j)]:[Q,C[0].$bzId||C[0]]:[Q,C.map(j=>j.$bzId||j)]:[Q,C.$bzId||C]}),b={...M,$thing:E.$thing,$thingType:"relation",$op:w(),...F,$bzId:E.$bzId,[et]:"roleField"};h(b);return}if(E.$op==="match"||E.$op==="update"&&Object.keys(O).length>0){Object.entries(O).forEach(([S,F])=>{let b=isArray(F)?F:[F],Q=C=>C==="create"||C==="replace"?"link":C;b.forEach(C=>{if(!C)return;let H=Q(C.$op);if(H==="replace")throw new Error("Not supported yet: replace on roleFields");let j={...M,$thing:E.$thing,$thingType:"relation",$op:H==="delete"?"unlink":H,[S]:C.$bzId,$bzId:E.$bzId,[et]:"roleField"};h(j);});});}}}}}),[p,u]},[r,i]=n(e),o=r.reduce((c,p)=>{if(!p.$bzId)return [...c,p];let u=c.findIndex(f=>f.$bzId===p.$bzId);if(u===-1)return [...c,p];if(c[u].$op==="create"&&p.$op==="match")return c;if(c[u].$op==="match"&&(p.$op==="create"||p.$op==="match"))return [...c.slice(0,u),p,...c.slice(u+1)];if(c[u].$op==="update"&&p.$op==="update")return [...c.slice(0,u),{...c[u],...p},...c.slice(u+1)];if(c[u].$op==="update"&&p.$op==="match"||c[u].$op==="match"&&p.$op==="update")return [...c.slice(0,u),{...c[u],...p,$op:"update"},...c.slice(u+1)];if(c[u].$op==="delete"&&p.$op==="delete"){if(JSON.stringify(c[u].$filter)===JSON.stringify(p.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[u].$filter}. Current: ${p.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${p.$tempId||p.$id}". Existing: ${c[u].$op}. Current: ${p.$op}`)},[]),s=i.reduce((c,p)=>{let u=c.find(f=>(f.$id&&f.$id===p.$id||f.$bzId&&f.$bzId===p.$bzId)&&f.$thing===p.$thing&&f.$op===p.$op);if(u){let f={...u};return Object.keys(p).forEach(h=>{if(typeof h=="symbol"||h.startsWith("$"))return;let y=u[h],$=p[h];Array.isArray(y)&&Array.isArray($)?f[h]=Array.from(new Set([...y,...$])):!Array.isArray(y)&&Array.isArray($)?y!==void 0?f[h]=Array.from(new Set([y,...$])):f[h]=$:Array.isArray(y)&&!Array.isArray($)?$!==void 0&&(f[h]=Array.from(new Set([...y,$]))):y!==null&&$!==null&&y!==void 0&&$!==void 0?f[h]=Array.from(new Set([y,$])):y==null&&(f[h]=$);}),[...c.filter(h=>!((h.$id&&h.$id===p.$id||h.$bzId&&h.$bzId===p.$bzId)&&h.$thing===p.$thing&&h.$op===p.$op)),f]}return [...c,p]},[]),a=[...o,...s],l=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),d=Array.from(l).filter(c=>!a.some(p=>p.$tempId===c&&p.$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 Br="___",Od=Symbol.for("grandChildOfCreate"),As=async(e,t,n,r,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(M,w)=>Object.keys(M).filter(S=>!S.startsWith("$")&&!o.includes(S)&&M[S]!==void 0?w?!z(t,M).dataFields?.find(b=>b.path===S):true:false);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===false)return;let a=[];if(traverse(e,({parent:M,key:w,value:S})=>{M&&w&&!w.includes("$")&&!o.includes(w)&&isObject(M)?(Array.isArray(M[w])?M[w]:[M[w]]).forEach(b=>{if(isObject(b)){if(M.$op!=="create")a.includes(b.$op)||a.push(b.$op);else if(b.$op==="delete"||b.$op==="unlink")throw new Error(`Cannot ${b.$op} under a create`)}}):!M&&isObject(S)&&(a.includes(S.$op)||a.push(S.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(M=>{let w=(S,F)=>{let b=[],Q={},C=["$op","$bzId","$parentKey"],H=["$relation","$entity","$id",...C];for(let j in S)if(!C.includes(j)&&!(H.includes(j)&&!F))if(!j.includes("$")&&(isObject(S[j])||Array.isArray(S[j]))){let le=Nd(S[j]);if(Array.isArray(le)&&le.length>0)le.forEach(ke=>{let Qe={$path:j,...w(ke),...ke.$filter&&{$as:ke.$bzId}};b.find(re=>re.$path===Qe.$path&&!re.$filter)||(b=[...b,Qe]);});else {let ke={$path:j,...w(le),...!le.$filter&&{$as:le.$bzId}};b=[...b,ke];}}else Q[j]=S[j];return {...Q,$fields:b}};return M.map(S=>w(S,true))})(Array.isArray(e)?e:[e]),p=(await Rt(d,t,n,{...r,query:{...r.query,returnNulls:true}},i)).bql.res,u=(M,w)=>{let S=M.$id||M.id||M.$bzId;if(M.$objectPath){let{$objectPath:F}=M,b=F?.beforePath||"root",Q=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${b}.${Q}___${F.key}`,ids:S,key:w}}return {beforePath:"root",ids:S,key:w}},f=(M,w)=>{let S=M?.beforePath||"root";if(typeof S!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let F=(Array.isArray(M?.ids)?`[${M?.ids}]`:M?.ids);return `${S}.${F}___${M?.key}`},m=M=>{if(M.includes("[")&&M.includes("]")){let[w,S,F]=M.split(/[[\]]/);return S.split(",").map(Q=>`${w}${Q}${F}`)}return [M]},h={};(M=>produce(M,w=>traverse(w,({key:S,parent:F})=>{if(F&&S&&F.$id&&!S.includes("$")){let b=u(F,S),Q=f(b);if(Array.isArray(F[S])){let C=[];F[S].forEach(H=>{isObject(H)?(H.$objectPath=b,C.push(H.$id.toString())):H&&C.push(H.toString());}),h[Q]={$objectPath:b,$ids:C};}else {let C=F[S];isObject(C)?(h[Q]={$objectPath:b,$ids:[C.$id.toString()]},C.$objectPath=b):C?h[Q]={$objectPath:b,$ids:[C.toString()]}:C===null&&(h[Q]=null);}}})))(p||{});let $=M=>produce(M,w=>traverse(w,({key:S,value:F,parent:b})=>{b&&S&&!S.includes("$")&&(Array.isArray(F)||isObject(F))&&!Array.isArray(b)&&(Array.isArray(b[S])?b[S].forEach(Q=>{typeof Q!="string"&&(Q.$objectPath=u(b,S),Q.$parentIsCreate=b.$op==="create",Q[Od]=b.$parentIsCreate||b[Symbol.for("grandChildOfCreate")]);}):isObject(b[S])&&(b[S].$parentIsCreate=b.$op==="create",b[S][Symbol.for("grandChildOfCreate")]=b.$parentIsCreate||b[Symbol.for("grandChildOfCreate")],b[S].$objectPath=u(b,S)));})),g=$(e),B=M=>{let w=[];return M.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let b=f({...F.$objectPath,key:F.$bzId}),Q=h[b];Q&&(Array.isArray(Q.$ids)?Q.$ids:[Q.$ids]).forEach(H=>{let j={...F,$id:H,$bzId:`T4_${v4()}`,$filterBzId:F.$bzId};w.push(j);});}else {let b=f(F.$objectPath),Q=h[b];Q?Q?.$ids?.forEach(C=>{let H={...F,$id:C,$bzId:`T4_${v4()}`};w.push(H);}):w.push(F);}else w.push(F);}),w.map(F=>{let b={...F};return s(b,true).forEach(Q=>{let C=Array.isArray(b[Q])?b[Q]:[b[Q]],H=B(C);b[Q]=H;}),b})},E=B(Array.isArray(g)?g:[g]),T=$(E),k=(M=>{let w=S=>{let F=re=>{let se=[],G=[],x=[];return re.forEach(K=>{let he=s(K,true);if(he.length>0){let P=false;he.forEach(X=>{(Array.isArray(K[X])?K[X]:[K[X]]).filter(ue=>!ue.$id&&!ue.id&&typeof K=="object").length&&(P=true);}),P?se.push(K):G.push(K);}else K.$id?x.push({...K,$bzId:K.$tempId||K.$bzId}):x.push({...K,$bzId:K.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:se,operationWithoutMultiples:G,otherOps:x}},{operationWithMultiples:b,operationWithoutMultiples:Q,otherOps:C}=F(S),H=re=>{let G=(()=>{let X={};for(let ge in re){let ie=z(t,re);!ge.startsWith("$")&&ie.dataFields?.find(ue=>ue.path===ge)&&(X[ge]=re[ge]);}return X})(),x=Object.keys(re),K=s(re,true),he=[],P=(X,ge)=>{if(X===K.length){let ue={...ge};x.forEach(Ee=>{Ee.startsWith("$")&&(ue[Ee]=re[Ee]);}),he.push({...ue,...G});return}let ie={...ge,[K[X]]:re[K[X]],...We(ge),...G};P(X+1,ie),P(X+1,ge);};return P(0,{...We(re)}),he},j=[];return b.forEach(re=>{let se=H(re),G=[];se.forEach(x=>{let K=s(x,true);if(x.$op==="create")G.push(x);else if(x.$id){let he=f(x.$objectPath),P=[];if(K.forEach(X=>{let ge=`${he.includes("undefined")?"root":he}.${x.$id}${Br}${X}`,ie=h[ge];x[X].filter(Ee=>Ee.$op==="unlink"||Ee.$op==="delete"||Ee.$op==="update").length>0?ie?.$ids&&P.push({key:X,ids:ie.$ids}):P.push({key:X,ids:[""]});}),P.length===K.length&&!G.find(X=>X.$id===x.$id))G.push(x);else {let X={...x,$bzId:x.$tempId||`T4_${v4()}`};K.forEach(ie=>{let ue=x[ie].filter(Ee=>Ee.$id);ue.length>0?X[ie]=ue:X[ie]=void 0;}),s(X,true).length>0&&G.push(X);}}else if(x.$objectPath){let he=f(x.$objectPath),P=h[he]?.$ids||[];P.forEach(X=>{let ge=[];K.forEach(ie=>{let ue=`${he}.${X}${Br}${ie}`,Ee=h[ue];Ee&&ge.push({key:ie,ids:Ee.$ids});}),K.length===0?P.filter(ue=>!G.find(Ee=>Ee.$id===ue)).forEach(ue=>{G.push({...x,$id:ue,$bzId:x.$tempId||`PQT2_${v4()}`});}):ge.length===K.length&&!G.find(ie=>ie.$id===X)&&(K.forEach(ie=>{let ue=`${f(x.$objectPath)}.${X}${Br}${ie}`,Ee=h[ue]?.$ids||[],Ns=x[ie].find(ut=>!ut.$id),br=[...Ee.map(ut=>({...Ns,$id:ut,$objectPath:{beforePath:x.$objectPath.beforePath,ids:ut,key:ie}})),...x[ie].filter(ut=>ut.$id)];br.length>0&&(x[ie]=br);}),G.push({...x,$id:X,$bzId:x.$tempId||`PQ3_${v4()}`}));});}else G.push(x);}),G.forEach(x=>{j.push(x);});}),[...j,...Q,...C].filter(re=>s(re).length>0?true:re.$op!=="update").map(re=>{let se={...re};return s(se,true).forEach(G=>{let x=Array.isArray(se[G])?se[G]:[se[G]],K=w(x);se[G]=K;}),se})};return w(M)})(Array.isArray(T)?T:[T]),R=M=>M.map(w=>{let S=s(w,true),F={...w};return S.forEach(b=>{let Q=Array.isArray(w[b])?w[b]:[w[b]],C=[],H=[],j=[],le={},ke=_n(t,w,b);Q.filter(P=>P).forEach(P=>{P.$op==="replace"&&P.$id?(le=P,Array.isArray(P.$id)?H=[...H,...P.$id]:H.push(P.$id)):P.$op==="create"&&ke==="ONE"&&P.id?(le=P,Array.isArray(P.id)?j=[...H,...P.id]:j.push(P.id)):C.push(P);});let Qe=f(le.$objectPath),se=m(Qe).map(P=>h[P]),G=[];se.filter(P=>P!=null).forEach(P=>{G=[...G,...P?.$ids||[]];});let x=G.filter(P=>!H.includes(P)),K=H.filter(P=>!G.includes(P)),he=We(le);x.length>0&&C.push({...le,$op:"unlink",$id:x,$bzId:le.$tempId||`T4_${v4()}`,id:void 0,...he}),K.length>0&&K.forEach(P=>{C.push({...le,$op:"link",$id:P,$bzId:le.$tempId||`T5_${v4()}`,...he});}),j.length>0&&j.forEach(P=>{C.push({...le,$op:"create",id:P,$bzId:le.$tempId||`T6_${v4()}`,...he});}),F[b]=R(C);}),F}),D=$(R($(k)));(M=>produce(M,w=>traverse(w,S=>{let{key:F,value:b,parent:Q,meta:C}=S;F&&Q&&!F?.includes("$")&&F!=="$filter"&&!C.nodePath?.includes(".$filter.")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(Q)&&(Array.isArray(b)?b:[b]).forEach(j=>{let le=j.$filter?{...j.$objectPath,key:j.$filterBzId}:j.$objectPath,ke=f(le),Qe=h[ke],re=(x,K)=>x.every(he=>K.includes(he)),se=j.$id?Array.isArray(j.$id)?re(j.$id,Qe?.$ids?Qe.$ids:[]):Qe?.$ids?.includes(j.$id):Qe,G=_n(t,Q,j.$objectPath.key);if(j.$op==="link"&&se&&G==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(j.$objectPath)}" because it is already occupied.`);if(j.$op)switch(j.$op){case "delete":if(!se&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${j.$id}" because it is not linked to $id:"${Q.$id}"`);break;case "update":if(!se&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${j.$id}" because it is not linked to $id:"${Q.$id}"`);break;case "unlink":if(!se&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${j.$id}" because it is not linked to $id:"${Q.$id}"`);break;case "link":if(se)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${j.$id}" because it is already linked to $id:"${Q.$id}"`);break;}});})))(D);let ne=(M=>produce(M,w=>traverse(w,S=>{let{value:F,meta:b}=S;isObject(F)&&(F[Symbol.for("path")]=b.nodePath,F.$objectPath=void 0,F.$parentIsCreate=void 0);})))(D);return [...Array.isArray(ne)?ne:[ne]].sort((M,w)=>M.$op==="create"&&w.$op!=="create"?-1:M.$op!=="create"&&w.$op==="create"?1:0)},Nd=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Ls=(e,t)=>produce(e,r=>hn(t,r)),hn=(e,t,n)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)hn(e,i,n);return}let r=oe(e,n||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||Cd(e,t,i,r);},Cd=(e,t,n,r)=>{let i=t[n];if(!i)return;let o=r.dataFields?.find(l=>l.path===n);if(o){o.contentType==="JSON"&&i!=null&&(t[n]=JSON.stringify(i));return}let s=r.linkFields?.find(l=>l.path===n);if(s){let l=s.oppositeLinkFieldsPlayedBy[0]?.thing;hn(e,i,l);return}if(!("refFields"in r&&r.refFields[n])&&r.thingType==="relation"){let l=r.roles[n];if(!l)throw new Error(`[Schema] Role ${n} in ${r.name} is not defined`);let[d]=l.playedBy||[];if(!d)throw new Error(`Role ${l.path} in ${r} is not played by anything`);hn(e,i,d.thing);}};var Ds=Re,ct=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,_d=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),jd=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Pd=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),qd=async e=>(ce(`>>> mutationMachine/enrich[${de}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?or(e.bql.enriched,e.schema,e.config):or(e.bql.raw,e.schema,e.config)),xd=async e=>(ce(`>>> mutationMachine/preQuery[${de}]`,JSON.stringify(e.bql.enriched)),As(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),Vd=async e=>(ce(`>>> mutationMachine/preQueryDependencies[${de}]`,JSON.stringify(e.bql.enriched)),gs(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),zd=async e=>(ce(`>>> mutationMachine/parseBQL[${de}]`,JSON.stringify(e.bql.enriched)),Ms(e.bql.enriched,e.schema)),Wd=async e=>(ce(`>>> mutationMachine/flattenBQL[${de}]`,JSON.stringify(e.bql.enriched)),Rs(e.bql.enriched,e.schema)),Ud=e=>{let{dbConnectors:t}=e.config;return t.length!==1||t[0].provider!=="surrealDB"?false:process.env.BLITZ_ORM_OLD_SURREALDB_MUTATION!=="true"},vd=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:n}]=t;if(n==="typeDB")return true;if(n==="surrealDB")return false;throw new Error(`Unsupported provider ${n}.`)},Hd=e=>Ft(e.bql.enriched),dt=U("error","error",W((e,t)=>({...e,error:t.error}))),Yd=Ce("stringify",{stringify:te(async e=>(ce(`>>> mutationMachine/stringify[${de}]`,JSON.stringify(e.bql.raw)),Ls(e.bql.raw,e.schema)),U("done","adapter",tn(Ud),W(ct)),U("done","enrich",W(ct)),dt),enrich:te(qd,U("done","preQuery",tn(vd),W(ct)),U("done","parseBQL",W(ct)),dt),preQuery:te(xd,U("done","preHookDependencies",tn(Hd),W(ct)),U("done","parseBQL",W(ct)),dt),preHookDependencies:te(Vd,U("done","enrich",W(ct)),dt),parseBQL:te(zd,U("done","flattenBQL",W(_d)),dt),flattenBQL:te(Wd,U("done","adapter",W(jd)),dt),adapter:te(async e=>{ce(`>>> mutationMachine/adapter[${de}]`,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:n}]=t;if(n==="typeDB")return To(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(n==="surrealDB")return process.env.BLITZ_ORM_OLD_SURREALDB_MUTATION==="true"?Eo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles):Ki(e.bql.raw,e.draftSchema,e.config,e.handles);throw new Error(`Unsupported provider ${n}.`)},U("done","success",W(Pd)),dt),success:Ds(),error:Ds()},e=>e),Kd=async e=>new Promise((t,n)=>{_e(Yd,r=>{r.machine.state.name==="success"&&t(r.context),r.machine.state.name==="error"&&n(r.context);},e);}),ks=async(e,t,n,r,i)=>Kd({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,draftSchema:n,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Fr=class{schema;config;initializing=false;subscribers=[];initialized=null;constructor({schema:t,config:n}){this.schema=t,this.config=n;}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((n,r)=>{this.subscribers.push(i=>{i?r(i):n();});});this.initializing=true;let t={typeDB:new Map,surrealDB:new Map};try{await Promise.all(this.config.dbConnectors.map(async r=>{if(r.provider==="surrealDB"){let i=new _t({url:r.url,username:r.username,password:r.password,namespace:r.namespace,database:r.dbName});await i.connect(),t.surrealDB.set(r.id,{client:i});}else if(r.provider==="typeDB"&&r.dbName){let[i,o]=await tryit(TypeDB.coreDriver)(r.url);if(i){let s=`[BORM:${r.provider}:${r.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await o.session(r.dbName,SessionType.DATA);t.typeDB.set(r.id,{client:o,session:s});}catch(s){let a=`[BORM:${r.provider}:${r.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}else if(r.provider==="typeDBCluster"&&r.dbName){let i=new TypeDBCredential(r.username,r.password,r.tlsRootCAPath),[o,s]=await tryit(TypeDB.cloudDriver)(r.addresses,i);if(o){let a=`[BORM:${r.provider}:${r.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(r.dbName,SessionType.DATA);t.typeDB.set(r.id,{client:s,session:a});}catch(a){let l=`[BORM:${r.provider}:${r.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={draftSchema:Pr(this.schema),enrichedSchema:Nr(this.schema,t),dbHandles:t};let n=this.subscribers;this.subscribers=[];for(let r of n)r();}catch(n){let r=this.subscribers;this.subscribers=[];for(let i of r)i(n);}finally{this.initializing=false;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await Lr(this.config,t.enrichedSchema,t.draftSchema,t.dbHandles)};query=async(t,n)=>{let r=await this.getInitialized(),i={...this.config,query:{...yn.query,...this.config.query,...n}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(Rt)(s,r.enrichedSchema,r.draftSchema,i,r.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,n)=>{let r=await this.getInitialized(),i={...this.config,mutation:{...yn.mutation,...this.config.mutation,...n}},[o,s]=await tryit(ks)(t,r.enrichedSchema,r.draftSchema,i,r.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:n})=>{n.isOpen()&&await n.close(),await t.close();})),await Promise.all([...this.initialized.dbHandles.surrealDB?.values()??[]].map(async({client:t})=>{await t.close();}));}finally{this.initialized=null;}}},ly=Fr;//! 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
134
+ `)},dr=(e,t,n)=>{let r=[],i=[],o=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||r.push(e[c].$dbPath),e[c][ze].contentType==="FLEX"&&o.push({path:e[c][ze].dbPath}),i.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=r.join(", "),l=`$metadata:{as:[${i.join(",")}]}`,d=[N(`$${t} as "${t}.${l}.$dataFields": ${s};`,n)];return o.length>0&&o.forEach(c=>{d.push(N(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,n));}),d},ur=(e,t,n,r,i)=>{let o=r+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:p,$filterByUnique:u,$thing:f,$sort:m,$offset:h,$limit:y}=a,$=a[Oe],g=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${p},filterByUnique:${u}}`;s.push(N(`"${n}.${g}.${a.$var}": {`,r)),s.push(N("match",o));let B=`${t}${cr}${a.$var}`;if(s.push(N(`$${B} isa ${a.$thing};`,o)),s.push(N(`$${t} (${a.$var}: $${t}${cr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let T=Yt(i,a),A=a.$id?{[T]:a.$id}:{},k={...a.$filter,...A};s.push(pn({$filter:k,$var:B,$thing:a.$thing,schema:i,depth:o}));}let E=fr({schema:i,$thing:f,$var:B,$sort:m,depth:o});if(E&&s.push(E.match),l){let T=`M_${v4()}`;s.push(N(`
135
+ ?queryPath${T} = "${$}";`,o)),s.push(N("fetch",o)),s.push(N(`?queryPath${T} as "queryPath";`,o));let A=l?.filter(D=>D.$fieldType==="data");A&&A.length>0&&s.push(...dr(A,B,o));let k=l?.filter(D=>D.$fieldType==="link");k&&k.length>0&&s.push(...pr(k,B,`${t}.${a.$var}`,o,i));let R=l?.filter(D=>D.$fieldType==="role");R&&R.length>0&&s.push(...ur(R,B,`${t}.${a.$var}`,o,i));}E&&s.push(E.sort),typeof h=="number"&&s.push(N(`offset ${h};`,o)),typeof y=="number"&&s.push(N(`limit ${y};`,o)),s.push(N("};",r));}return s},pr=(e,t,n,r,i)=>{let o=r+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:p,$filterByUnique:u,$playedBy:f,$thing:m,$sort:h,$offset:y,$limit:$}=a,g=a[Oe],B=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${p},filterByUnique:${u}}`;s.push(N(`"${n}.${B}.${a.$var}": {`,r)),s.push(N("match",o));let E=`${t}${cr}${a.$var}`;if(s.push(N(`$${E} isa ${a.$thing};`,o)),a.$filter||a.$id){let A=Yt(i,a),k=a.$id?{[A]:a.$id}:{},R={...a.$filter,...k};s.push(pn({$filter:R,$var:E,$thing:a.$thing,schema:i,depth:o}));}let T=fr({schema:i,$thing:m,$var:E,$sort:h,depth:o});if(T&&s.push(T.match),a.$target==="role"?s.push(N(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${E}) isa ${a.$intermediary};`,o)):s.push(N(`$${E} (${a.$plays}: $${t});`,o)),l){let A=`M_${v4()}`;s.push(N(`?queryPath${A} = "${g}";`,o)),s.push(N("fetch",o)),s.push(N(`?queryPath${A} as "queryPath";`,o));let k=l?.filter(I=>I.$fieldType==="data");k&&k.length>0&&s.push(...dr(k,E,o));let R=l?.filter(I=>I.$fieldType==="link");R&&R.length>0&&s.push(...pr(R,E,`${t}.${a.$var}`,o,i));let D=l?.filter(I=>I.$fieldType==="role");D&&D.length>0&&s.push(...ur(D,E,`${t}.${a.$var}`,o,i));}T&&s.push(T.sort),typeof y=="number"&&s.push(N(`offset ${y};`,o)),typeof $=="number"&&s.push(N(`limit ${$};`,o)),s.push(N("};",r));}return s},ld=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},fr=e=>{let{$var:t,$thing:n,schema:r,$sort:i,depth:o}=e,s=oe(r,n),a=[],l=[];if(i?.forEach(d=>{let c=ld(d),p=s.dataFields?.find(m=>m.path===c.field);if(!p)throw new Error(`"${n}" does not have data field "${c.field}"`);let u=`${c.field}_${v4()}`;a.push(N("{",o)),a.push(N(`$${t} has ${p.dbPath} $${u}_1;`,o+1)),a.push(N("not {",o+1)),a.push(N(`$${t} has ${p.dbPath} $${u}_2;`,o+2)),a.push(N(`$${u}_2 < $${u}_1;`,o+2)),a.push(N("};",o+1)),a.push(N(`?${u}_ = $${u}_1;`,o+1)),a.push(N("} or {",o)),a.push(N(`not { $${t} has ${p.dbPath} $${u}_1; };`,o+1)),a.push(N(`?${u}_ = "~";`,o+1)),a.push(N("};",o)),a.push(N(`?${u} = ?${u}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${u} ${f}`);}),a.length!==0)return {match:a.join(""),sort:N(`sort ${l.join(", ")};`,o)}};var us=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:n,schema:r,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=n[a],d=t[a];return dd(s,l,d,r,i)})},dd=(e,t,n,r,i)=>e.length===0?null:n.$filterByUnique?ds(e[0],t,r,i):e.map(o=>ds(o,t,r,i)),ds=(e,t,n,r)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=hr(e,n),d=mr(i,o,r),c=yr(s,n,r),p=$r(a,n,r),u=t?.$fields?.every(m=>!o?.idFields?.includes(typeof m=="string"?m:m.$path));return {...c,...p,...l,...!r.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?d.id:t.$id}:{},...u?Object.fromEntries(Object.entries(d).filter(([m])=>!o?.idFields?.includes(m))):d}},hr=(e,t)=>{let n=Object.keys(e),r=n.find(f=>f.endsWith(".$dataFields")),i=n.filter(f=>f.endsWith(".$multiVal"));if(!r)throw new Error("No dataFields");if(i?.length>0)for(let f of i){let m=f.replace(/\.\$multiVal$/,""),h=e[f][0][m].attribute;e[r][m]=h;}let o=e[r],s=r.split(".")[r.split(".").length-2];if(o.$metaData=s,o.length===0)throw new Error("No dataFields");let a=o.type,l={$thing:a.label,$thingType:a.root,[Oe]:e.queryPath.value},d={[`$${l.$thingType}`]:l.$thing},c=z(t,d),p=n.filter(f=>{let m=Ae(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some(h=>h.path===m)}).map(f=>{let m=Ae(f.split(".").pop()),h=Ae(c.linkFields?.find(y=>y.path===m));return {$linkFields:e[f],$key:m,$metaData:f.split(".")[f.split(".").length-2],$cardinality:h.cardinality}}),u=n.filter(f=>{let m=f.split(".").pop();return m&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[m]}).map(f=>{let m=Ae(f.split(".").pop());return {$roleFields:e[f],$key:m,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[m].cardinality}});return {dataFields:o,schemaValue:l,currentSchema:c,linkFields:p,roleFields:u}},mr=(e,t,n)=>{let{$metaData:r}=e,{as:i}=ud(r),o=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).flatMap(([s,a])=>{let l=t.dataFields?.find(u=>u.path===s||u.dbPath===s),d=s==="id",c=Array.isArray(i)?i.find(u=>u[s])?.[s]:s,p;if(l?.cardinality==="ONE"){if(p=a[0]?a[0].value:n.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&a[0].type.value_type==="datetime"?p=p&&`${p}Z`:l.contentType==="JSON"&&(p=p&&JSON.parse(p)),d)return [[c,p],["$id",p]].filter(([u,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 n.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?p=a.map(u=>`${u.value}Z`):l.contentType==="FLEX"?p=a.map(u=>u.type.value_type==="datetime"?`${u.value}Z`:u.value):l.contentType==="JSON"?p=a.map(u=>u.value&&JSON.parse(u.value)):p=a.map(u=>u.value);}return [[c,p]].filter(([u,f])=>f!==void 0)});return Object.fromEntries([...o])},$r=(e,t,n)=>{let r={};for(let i of e){let{$roleFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:p}=ps(s);if(l===null)continue;let u=o.map(f=>{let{dataFields:m,currentSchema:h,linkFields:y,roleFields:$,schemaValue:g}=hr(f,t),B=mr(m,h,n);if(d==="T")return B.id;let E=yr(y,t,n),T=$r($,t,n),A={...B};if(c==="true"&&h?.idFields)for(let k of h.idFields)delete A[k];return {...A,...E,...T,...g}});u.length>0?r[l]=a==="MANY"&&p==="false"?u:u[0]:n.query?.returnNulls&&(r[l]=null);}return r},yr=(e,t,n)=>{let r={};for(let i of e){let{$linkFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:p}=ps(s);if(l===null)continue;let u=o.map(f=>{let{dataFields:m,currentSchema:h,linkFields:y,roleFields:$,schemaValue:g}=hr(f,t),B=mr(m,h,n);if(d==="T")return B.id;let E=yr(y,t,n),T=$r($,t,n),A={...B};if(c==="true")for(let k of h.idFields??[])delete A[k];return {...A,...E,...T,...g}});r[l]=u.length>0?a==="MANY"&&p==="false"?u:u[0]:n.query?.returnNulls?null:void 0;}return r},ps=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,r=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,o=e.match(t),s=e.match(n),a=e.match(r),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}},ud=e=>{try{let n=(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(n)}catch(t){return console.error(t),{as:[]}}};var fs=async e=>{let{tqlRequest:t,dbHandles:n,config:r}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await on(n,r),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 $d=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,gr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,yd=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,gd=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Rt=U("error","error",W((e,t)=>({...e,error:t.error}))),Ed=Ce("enrich",{enrich:te(async e=>(ce(`originalBQLQuery[${de}]`,JSON.stringify(e.bql.raw)),an(e.bql.raw,e.schema)),U("done","build",W($d)),Rt),build:te(async e=>cs({queries:e.bql.queries??[],schema:e.schema}),U("done","run",W(yd)),Rt),run:te(async e=>fs({dbHandles:e.handles,tqlRequest:Ae(e.tql.queries),config:e.config}),U("done","parse",W(gd)),Rt),parse:te(async e=>us({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:Ae(e.tql.res)}),U("done","postHooks",W(gr)),Rt),postHooks:te(async e=>ss(e.schema,Ae(e.bql.queries),Ae(e.bql.res)),U("done","clean",W(gr)),Rt),clean:te(async e=>os(e.config,Ae(e.bql.res)),U("done","success",W(gr)),Rt),success:Re(),error:Re()},e=>e),Bd=async e=>new Promise((t,n)=>{_e(Ed,r=>{r.machine.state.name==="success"&&t(r.context.bql.res),r.machine.state.name==="error"&&n(r.context.error);},e);}),hs=async(e,t,n,r)=>Bd({bql:{raw:e},tql:{},schema:t,config:n,handles:r,error:null});var Fd=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,bd=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ms=U("error","error",W((e,t)=>({...e,error:t.error}))),Rd=Ce("enrich",{enrich:te(async e=>(ce(`originalBQLQuery[${de}]`,JSON.stringify(e.bql.raw)),an(e.bql.raw,e.schema)),U("done","adapter",W(Fd)),ms),adapter:te(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 p=oe(e.schema,c),{id:u}=p.defaultDBConnector;if(p.db==="typeDB"){if(!t[u]){let m=e.handles.typeDB?.get(u)?.client;if(!m)throw new Error(`TypeDB client with id "${p.defaultDBConnector.id}" does not exist`);t[u]={db:"typeDB",client:m,rawBql:[],indices:[]};}}else if(p.db==="surrealDB"){if(!t[u]){let m=e.handles.surrealDB?.get(u)?.client;if(!m)throw new Error(`SurrealDB client with id "${p.defaultDBConnector.id}" does not exist`);t[u]={db:"surrealDB",client:m,rawBql:[],indices:[]};}}else throw new Error(`Unsupported DB "${p.db}"`);let f=t[u];f.rawBql.push(d),f.indices.push(l);});let n=Object.values(t),r=n.map(a=>{if(a.db==="typeDB")return hs(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return ts(a.rawBql,e.draftSchema,e.config,a.client);throw new Error(`Unsupported DB "${JSON.stringify(a,null,2)}"`)}),i=await Promise.all(r),o=n.flatMap((a,l)=>{let d=i[l];return a.indices.map((c,p)=>({index:c,result:d[p]}))});return o.sort((a,l)=>a.index<l.index?-1:a.index>l.index?1:0),o.map(({result:a})=>a)},U("done","success",W(bd)),ms),success:Re(),error:Re()},e=>e),Td=async e=>new Promise((t,n)=>{_e(Rd,r=>{r.machine.state.name==="success"&&t(r.context),r.machine.state.name==="error"&&n(r.context);},e);}),Tt=async(e,t,n,r,i)=>Td({bql:{raw:e},schema:t,draftSchema:n,config:r,handles:i,error:null});var Es=async(e,t,n,r,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(d=>Er(d,true)),l=(await Tt(s,t,n,r,i)).bql.res;return o.map((d,c)=>{let p=oe(t,d.$thing);return Fs({mut:d,node:l[c],schema:t,thing:p})})},Bs=new Set(["$op","$bzId","$parentKey"]),Sd=new Set(["$relation","$entity","$id",...Bs]),Er=(e,t)=>{let n={};e.$fields?.forEach(i=>{typeof i=="string"?n[i]=i:n[i.$path]=i;});let r={};for(let i in e){if(Bs.has(i)||Sd.has(i)&&!t)continue;let o=e[i];i.startsWith("$")?r[i]=o:Array.isArray(o)?o[0]&&typeof o[0]=="object"&&(n[i]={$path:i,...Er(o[0],false)}):isObject(o)&&(n[i]={$path:i,...Er(o,false)});}return r.$fields=Object.values(n),r},Fs=e=>{let{mut:t,node:n,schema:r,thing:i}=e,o=Rs(i),s=Ad(n);if(Array.isArray(t))return t.map(l=>{let d=s[l.$id];return d?$s({mut:l,node:d,schema:r,thing:i,...o}):l});let a=s[t.$id];return $s({mut:t,node:a,schema:r,thing:i,...o})},$s=e=>{let{mut:t,node:n,schema:r,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,{$fields:l,...d}=t;if(!n)return d;let c=bs({$fields:t.$fields,node:n,schema:r,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),p={...d,[ft]:c};for(let u in t){if(u.startsWith("$"))continue;let f=t[u];if(o[u]||!f||typeof f!="object"){p[u]=f;continue}let h=s[u]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[u]?.playedBy?.[0]?.thing;if(!h)throw new Error(`"${i.name}" does not have field "${u}"`);let y=oe(r,h);p[u]=Fs({mut:f,schema:r,node:n[u],thing:y});}return p},bs=e=>{let{$fields:t,node:n,schema:r,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Md(i),d={$id:n.$id};return l.forEach(c=>{let p=typeof c!="string",u=p?c.$path:c,f=n[u];if(o[u]){d[u]=f;return}let h=s[u]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[u]?.playedBy?.[0]?.thing;if(!h)throw new Error(`"${i.name}" does not have field "${u}"`);if(!p){f&&(d[u]=Array.isArray(f)?f.map(ys):ys(f));return}let y=oe(r,h),$=Rs(y);d[u]=Array.isArray(f)?f.map(g=>gs({...$,$fields:c.$fields,value:g,schema:r,thing:y})):gs({...$,$fields:c.$fields,value:f,schema:r,thing:y});}),d},Md=e=>{let t=[];return e.dataFields?.forEach(n=>{t.push(n.path);}),e.linkFields?.forEach(n=>{t.push(n.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},ys=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},gs=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 bs({...e,node:t})},Rs=e=>{let t=Object.fromEntries(e.dataFields?.map(i=>[i.path,i])||[]),n=Object.fromEntries(e.linkFields?.map(i=>[i.path,i])||[]),r=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:n,roleFieldMap:r}},Ad=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(n=>{!n||typeof n!="object"||!n.$id||(t[n.$id]=n);}),t};var Ts=(e,t)=>{let n={things:[],edges:[],arcs:[],references:[]},r=(s,a)=>{if(!s?.$thing)return;let{$op:l,$bzId:d,$tempId:c}=s,p=t.relations[s.$thing]||t.entities[s.$thing];if(!p)throw new Error(`[Internal] No schema found for ${s.$thing}`);let u=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:m,usedRoleFields:h,usedRefFields:y}=$e(p,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let g={...me(s,B=>![...h,...m,...y].includes(B)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[ht]:u}};n.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=me(s,B=>isSymbol(B)||B.startsWith("$"));for(let B of h){if(isArray(s[B]))for(let T of s[B])r(T,{bzId:d,edgeField:B,tempId:c});else r(s[B],{bzId:d,edgeField:B,tempId:c});let E=(isArray(s[B])?s[B]:[s[B]]).filter(Boolean);for(let[T,A]of Object.entries($)){let k=E.filter(R=>A.includes(R.$op)).map(R=>R.$bzId);k.length>0&&n.edges.push({...g,[B]:k,$op:T});}}}if(m)for(let g of m){if(isArray(s[g]))for(let T of s[g])r(T,{bzId:d,edgeField:g,tempId:c});else r(s[g],{bzId:d,edgeField:g,tempId:c});let B=p.linkFields?.find(T=>T.path===g),E=isArray(s[g])?s[g]:[s[g]];if(B.target==="relation")for(let[T,A]of Object.entries($)){let k=E.filter(R=>A.includes(R.$op));for(let R of k){let D=me(R,I=>isSymbol(I)||I.startsWith("$"));n.edges.push({...D,[B.plays]:d,$op:T});}}if(B.target==="role"){let T={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[A,k]of Object.entries(T)){let R=E.filter(D=>k.includes(D.$op));if(R.length!==0)for(let D of R){let I={$thing:B.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[B.plays]:d,[B.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:A};n.arcs.push(I);}}}}if(y)for(let g of y){if(isArray(s[g]))for(let A of s[g])r(A,{bzId:d,edgeField:g,tempId:c});else r(s[g],{bzId:d,edgeField:g,tempId:c});let B=(isArray(s[g])?s[g]:[s[g]]).filter(A=>A!=null),E=me(s,A=>isSymbol(A)||A.startsWith("$")),T=B.map(A=>A.$op?`$\u27E8${A.$bzId}\u27E9`:pt(A,"FLEX"));T.length>0&&n.references.push({...E,[g]:T,$op:"replace"});}},i=Array.isArray(e)?e:[e];for(let s of i)r(s);let o=[...n.edges].sort((s,a)=>{let l=["unlink","link"];return l.indexOf(s.$op)-l.indexOf(a.$op)});return {...n,edges:o}};var As=async(e,t)=>{let n=c=>{let p=[],u=[],f=$=>{if($.$id)return $.$id;let g=z(t,$),{idFields:B}=g;if(!B)throw new Error(`no idFields: ${JSON.stringify($)}`);let[E]=B;if(!E)throw new Error(`no idField: ${JSON.stringify($)}`);let T=g.dataFields?.find(R=>R.path===E),A=Ft({currentThing:$,fieldSchema:T,mandatoryDependencies:true}),k=$[E]||$.$id||A;if(!k)throw new Error(`no idValue: ${JSON.stringify($)}`);return k},m=$=>{if($.$op==="create"){let g=f($);if(p.find(B=>B.$id===g&&B.$op==="create"))throw new Error(`Duplicate id ${g} for node ${JSON.stringify($)}`);p.push({...$,$id:g});return}$.$tempId&&$.$op==="match"||p.push($);},h=$=>{if($.$op==="create"){let g=f($);if(p.find(B=>B.$id===g&&B.$op==="create"))throw new Error(`Duplicate id ${g} for edge ${JSON.stringify($)}`);u.push({...$,$id:g});return}u.push($);};return traverse(c,({value:$,parent:g,meta:B})=>{if(!isObject($))return;let E=$;if(!B.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 T=z(t,E),{dataFields:A,roleFields:k,linkFields:R,refFields:D,usedFields:I}=$e(T,E),q=()=>{if(E.$op==="create"||E.$op==="delete")return E.$op;if(E.$op==="update"){let O=I.filter(S=>A?.includes(S)),v=I.filter(S=>k?.includes(S)),M=I.filter(S=>R?.includes(S)),w=I.filter(S=>D?.includes(S));if(O.length>0)return "update";if(v.length>0||M.length>0||w.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(E)}`)}return "match"},ne={...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,A||[""])),$op:q(),$bzId:E.$bzId};m(ne);let L=E[Ne];if(L?.[Z].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");p.push({...E,$op:"match"});}let O=L.$things.includes(E.$thing),v=O?E.$bzId:`LT_${v4()}`,w=Bi(c,g,B).$bzId;if(!w)throw new Error("No parent id found");let S=()=>E.$op==="delete"?O?"match":"delete":E.$op==="unlink"?O?"unlink":"delete":E.$op==="link"||E.$op==="create"?O?"link":"create":E.$op==="replace"?"replace":"match",F=z(t,{$thing:L.relation,$thingType:"relation"});if(!Object.keys(F.roles).includes(L.plays))throw new Error(`[Wrong format] Field ${L.plays} is not a role of relation ${L.relation}`);let Q={$bzId:v,$thing:O?E.$thing:L.relation,$thingType:"relation",...E.$tempId?{$tempId:E.$tempId}:{},$op:S(),...O?{}:{[L.path]:E.$bzId},[L.plays]:w,[Ne]:L,[tt]:"linkField"};h(Q),(E.$op==="unlink"||S()==="unlink")&&O&&h({$thing:L.relation,$thingType:"relation",$bzId:v,$op:"match",[L.plays]:w,[Ne]:L,[tt]:"linkField"});}if(E.$thingType==="relation"){let O=me(E,(w,S)=>k.includes(w)),v=mapEntries(O,(w,S)=>isArray(S)?[w,S]:isObject(S)?[w,S.$bzId]:[w,S]),M=me($,(w,S)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(O).filter(w=>!w.startsWith("$")).length>0){if(E.$op==="create"||E.$op==="delete"){let w=()=>{if(E.$op==="create")return "link";if(E.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=z(t,E).roles,F=mapEntries(v,(Q,C)=>{let H=S[Q]?.cardinality;if(!H)throw new Error(`Role ${Q} not found in schema`);return Array.isArray(C)?H==="ONE"?C.length>1?[Q,C.map(j=>j.$bzId||j)]:[Q,C[0].$bzId||C[0]]:[Q,C.map(j=>j.$bzId||j)]:[Q,C.$bzId||C]}),b={...M,$thing:E.$thing,$thingType:"relation",$op:w(),...F,$bzId:E.$bzId,[tt]:"roleField"};h(b);return}if(E.$op==="match"||E.$op==="update"&&Object.keys(O).length>0){Object.entries(O).forEach(([S,F])=>{let b=isArray(F)?F:[F],Q=C=>C==="create"||C==="replace"?"link":C;b.forEach(C=>{if(!C)return;let H=Q(C.$op);if(H==="replace")throw new Error("Not supported yet: replace on roleFields");let j={...M,$thing:E.$thing,$thingType:"relation",$op:H==="delete"?"unlink":H,[S]:C.$bzId,$bzId:E.$bzId,[tt]:"roleField"};h(j);});});}}}}}),[p,u]},[r,i]=n(e),o=r.reduce((c,p)=>{if(!p.$bzId)return [...c,p];let u=c.findIndex(f=>f.$bzId===p.$bzId);if(u===-1)return [...c,p];if(c[u].$op==="create"&&p.$op==="match")return c;if(c[u].$op==="match"&&(p.$op==="create"||p.$op==="match"))return [...c.slice(0,u),p,...c.slice(u+1)];if(c[u].$op==="update"&&p.$op==="update")return [...c.slice(0,u),{...c[u],...p},...c.slice(u+1)];if(c[u].$op==="update"&&p.$op==="match"||c[u].$op==="match"&&p.$op==="update")return [...c.slice(0,u),{...c[u],...p,$op:"update"},...c.slice(u+1)];if(c[u].$op==="delete"&&p.$op==="delete"){if(JSON.stringify(c[u].$filter)===JSON.stringify(p.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[u].$filter}. Current: ${p.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${p.$tempId||p.$id}". Existing: ${c[u].$op}. Current: ${p.$op}`)},[]),s=i.reduce((c,p)=>{let u=c.find(f=>(f.$id&&f.$id===p.$id||f.$bzId&&f.$bzId===p.$bzId)&&f.$thing===p.$thing&&f.$op===p.$op);if(u){let f={...u};return Object.keys(p).forEach(h=>{if(typeof h=="symbol"||h.startsWith("$"))return;let y=u[h],$=p[h];Array.isArray(y)&&Array.isArray($)?f[h]=Array.from(new Set([...y,...$])):!Array.isArray(y)&&Array.isArray($)?y!==void 0?f[h]=Array.from(new Set([y,...$])):f[h]=$:Array.isArray(y)&&!Array.isArray($)?$!==void 0&&(f[h]=Array.from(new Set([...y,$]))):y!==null&&$!==null&&y!==void 0&&$!==void 0?f[h]=Array.from(new Set([y,$])):y==null&&(f[h]=$);}),[...c.filter(h=>!((h.$id&&h.$id===p.$id||h.$bzId&&h.$bzId===p.$bzId)&&h.$thing===p.$thing&&h.$op===p.$op)),f]}return [...c,p]},[]),a=[...o,...s],l=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),d=Array.from(l).filter(c=>!a.some(p=>p.$tempId===c&&p.$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 Fr="___",Nd=Symbol.for("grandChildOfCreate"),Ls=async(e,t,n,r,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(M,w)=>Object.keys(M).filter(S=>!S.startsWith("$")&&!o.includes(S)&&M[S]!==void 0?w?!z(t,M).dataFields?.find(b=>b.path===S):true:false);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===false)return;let a=[];if(traverse(e,({parent:M,key:w,value:S})=>{M&&w&&!w.includes("$")&&!o.includes(w)&&isObject(M)?(Array.isArray(M[w])?M[w]:[M[w]]).forEach(b=>{if(isObject(b)){if(M.$op!=="create")a.includes(b.$op)||a.push(b.$op);else if(b.$op==="delete"||b.$op==="unlink")throw new Error(`Cannot ${b.$op} under a create`)}}):!M&&isObject(S)&&(a.includes(S.$op)||a.push(S.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(M=>{let w=(S,F)=>{let b=[],Q={},C=["$op","$bzId","$parentKey"],H=["$relation","$entity","$id",...C];for(let j in S)if(!C.includes(j)&&!(H.includes(j)&&!F))if(!j.includes("$")&&(isObject(S[j])||Array.isArray(S[j]))){let le=Id(S[j]);if(Array.isArray(le)&&le.length>0)le.forEach(ke=>{let Qe={$path:j,...w(ke),...ke.$filter&&{$as:ke.$bzId}};b.find(re=>re.$path===Qe.$path&&!re.$filter)||(b=[...b,Qe]);});else {let ke={$path:j,...w(le),...!le.$filter&&{$as:le.$bzId}};b=[...b,ke];}}else Q[j]=S[j];return {...Q,$fields:b}};return M.map(S=>w(S,true))})(Array.isArray(e)?e:[e]),p=(await Tt(d,t,n,{...r,query:{...r.query,returnNulls:true}},i)).bql.res,u=(M,w)=>{let S=M.$id||M.id||M.$bzId;if(M.$objectPath){let{$objectPath:F}=M,b=F?.beforePath||"root",Q=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${b}.${Q}___${F.key}`,ids:S,key:w}}return {beforePath:"root",ids:S,key:w}},f=(M,w)=>{let S=M?.beforePath||"root";if(typeof S!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let F=(Array.isArray(M?.ids)?`[${M?.ids}]`:M?.ids);return `${S}.${F}___${M?.key}`},m=M=>{if(M.includes("[")&&M.includes("]")){let[w,S,F]=M.split(/[[\]]/);return S.split(",").map(Q=>`${w}${Q}${F}`)}return [M]},h={};(M=>produce(M,w=>traverse(w,({key:S,parent:F})=>{if(F&&S&&F.$id&&!S.includes("$")){let b=u(F,S),Q=f(b);if(Array.isArray(F[S])){let C=[];F[S].forEach(H=>{isObject(H)?(H.$objectPath=b,C.push(H.$id.toString())):H&&C.push(H.toString());}),h[Q]={$objectPath:b,$ids:C};}else {let C=F[S];isObject(C)?(h[Q]={$objectPath:b,$ids:[C.$id.toString()]},C.$objectPath=b):C?h[Q]={$objectPath:b,$ids:[C.toString()]}:C===null&&(h[Q]=null);}}})))(p||{});let $=M=>produce(M,w=>traverse(w,({key:S,value:F,parent:b})=>{b&&S&&!S.includes("$")&&(Array.isArray(F)||isObject(F))&&!Array.isArray(b)&&(Array.isArray(b[S])?b[S].forEach(Q=>{typeof Q!="string"&&(Q.$objectPath=u(b,S),Q.$parentIsCreate=b.$op==="create",Q[Nd]=b.$parentIsCreate||b[Symbol.for("grandChildOfCreate")]);}):isObject(b[S])&&(b[S].$parentIsCreate=b.$op==="create",b[S][Symbol.for("grandChildOfCreate")]=b.$parentIsCreate||b[Symbol.for("grandChildOfCreate")],b[S].$objectPath=u(b,S)));})),g=$(e),B=M=>{let w=[];return M.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let b=f({...F.$objectPath,key:F.$bzId}),Q=h[b];Q&&(Array.isArray(Q.$ids)?Q.$ids:[Q.$ids]).forEach(H=>{let j={...F,$id:H,$bzId:`T4_${v4()}`,$filterBzId:F.$bzId};w.push(j);});}else {let b=f(F.$objectPath),Q=h[b];Q?Q?.$ids?.forEach(C=>{let H={...F,$id:C,$bzId:`T4_${v4()}`};w.push(H);}):w.push(F);}else w.push(F);}),w.map(F=>{let b={...F};return s(b,true).forEach(Q=>{let C=Array.isArray(b[Q])?b[Q]:[b[Q]],H=B(C);b[Q]=H;}),b})},E=B(Array.isArray(g)?g:[g]),T=$(E),k=(M=>{let w=S=>{let F=re=>{let se=[],G=[],V=[];return re.forEach(K=>{let he=s(K,true);if(he.length>0){let P=false;he.forEach(X=>{(Array.isArray(K[X])?K[X]:[K[X]]).filter(ue=>!ue.$id&&!ue.id&&typeof K=="object").length&&(P=true);}),P?se.push(K):G.push(K);}else K.$id?V.push({...K,$bzId:K.$tempId||K.$bzId}):V.push({...K,$bzId:K.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:se,operationWithoutMultiples:G,otherOps:V}},{operationWithMultiples:b,operationWithoutMultiples:Q,otherOps:C}=F(S),H=re=>{let G=(()=>{let X={};for(let ge in re){let ie=z(t,re);!ge.startsWith("$")&&ie.dataFields?.find(ue=>ue.path===ge)&&(X[ge]=re[ge]);}return X})(),V=Object.keys(re),K=s(re,true),he=[],P=(X,ge)=>{if(X===K.length){let ue={...ge};V.forEach(Ee=>{Ee.startsWith("$")&&(ue[Ee]=re[Ee]);}),he.push({...ue,...G});return}let ie={...ge,[K[X]]:re[K[X]],...Ue(ge),...G};P(X+1,ie),P(X+1,ge);};return P(0,{...Ue(re)}),he},j=[];return b.forEach(re=>{let se=H(re),G=[];se.forEach(V=>{let K=s(V,true);if(V.$op==="create")G.push(V);else if(V.$id){let he=f(V.$objectPath),P=[];if(K.forEach(X=>{let ge=`${he.includes("undefined")?"root":he}.${V.$id}${Fr}${X}`,ie=h[ge];V[X].filter(Ee=>Ee.$op==="unlink"||Ee.$op==="delete"||Ee.$op==="update").length>0?ie?.$ids&&P.push({key:X,ids:ie.$ids}):P.push({key:X,ids:[""]});}),P.length===K.length&&!G.find(X=>X.$id===V.$id))G.push(V);else {let X={...V,$bzId:V.$tempId||`T4_${v4()}`};K.forEach(ie=>{let ue=V[ie].filter(Ee=>Ee.$id);ue.length>0?X[ie]=ue:X[ie]=void 0;}),s(X,true).length>0&&G.push(X);}}else if(V.$objectPath){let he=f(V.$objectPath),P=h[he]?.$ids||[];P.forEach(X=>{let ge=[];K.forEach(ie=>{let ue=`${he}.${X}${Fr}${ie}`,Ee=h[ue];Ee&&ge.push({key:ie,ids:Ee.$ids});}),K.length===0?P.filter(ue=>!G.find(Ee=>Ee.$id===ue)).forEach(ue=>{G.push({...V,$id:ue,$bzId:V.$tempId||`PQT2_${v4()}`});}):ge.length===K.length&&!G.find(ie=>ie.$id===X)&&(K.forEach(ie=>{let ue=`${f(V.$objectPath)}.${X}${Fr}${ie}`,Ee=h[ue]?.$ids||[],Is=V[ie].find(ut=>!ut.$id),Rr=[...Ee.map(ut=>({...Is,$id:ut,$objectPath:{beforePath:V.$objectPath.beforePath,ids:ut,key:ie}})),...V[ie].filter(ut=>ut.$id)];Rr.length>0&&(V[ie]=Rr);}),G.push({...V,$id:X,$bzId:V.$tempId||`PQ3_${v4()}`}));});}else G.push(V);}),G.forEach(V=>{j.push(V);});}),[...j,...Q,...C].filter(re=>s(re).length>0?true:re.$op!=="update").map(re=>{let se={...re};return s(se,true).forEach(G=>{let V=Array.isArray(se[G])?se[G]:[se[G]],K=w(V);se[G]=K;}),se})};return w(M)})(Array.isArray(T)?T:[T]),R=M=>M.map(w=>{let S=s(w,true),F={...w};return S.forEach(b=>{let Q=Array.isArray(w[b])?w[b]:[w[b]],C=[],H=[],j=[],le={},ke=jn(t,w,b);Q.filter(P=>P).forEach(P=>{P.$op==="replace"&&P.$id?(le=P,Array.isArray(P.$id)?H=[...H,...P.$id]:H.push(P.$id)):P.$op==="create"&&ke==="ONE"&&P.id?(le=P,Array.isArray(P.id)?j=[...H,...P.id]:j.push(P.id)):C.push(P);});let Qe=f(le.$objectPath),se=m(Qe).map(P=>h[P]),G=[];se.filter(P=>P!=null).forEach(P=>{G=[...G,...P?.$ids||[]];});let V=G.filter(P=>!H.includes(P)),K=H.filter(P=>!G.includes(P)),he=Ue(le);V.length>0&&C.push({...le,$op:"unlink",$id:V,$bzId:le.$tempId||`T4_${v4()}`,id:void 0,...he}),K.length>0&&K.forEach(P=>{C.push({...le,$op:"link",$id:P,$bzId:le.$tempId||`T5_${v4()}`,...he});}),j.length>0&&j.forEach(P=>{C.push({...le,$op:"create",id:P,$bzId:le.$tempId||`T6_${v4()}`,...he});}),F[b]=R(C);}),F}),D=$(R($(k)));(M=>produce(M,w=>traverse(w,S=>{let{key:F,value:b,parent:Q,meta:C}=S;F&&Q&&!F?.includes("$")&&F!=="$filter"&&!C.nodePath?.includes(".$filter.")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(Q)&&(Array.isArray(b)?b:[b]).forEach(j=>{let le=j.$filter?{...j.$objectPath,key:j.$filterBzId}:j.$objectPath,ke=f(le),Qe=h[ke],re=(V,K)=>V.every(he=>K.includes(he)),se=j.$id?Array.isArray(j.$id)?re(j.$id,Qe?.$ids?Qe.$ids:[]):Qe?.$ids?.includes(j.$id):Qe,G=jn(t,Q,j.$objectPath.key);if(j.$op==="link"&&se&&G==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(j.$objectPath)}" because it is already occupied.`);if(j.$op)switch(j.$op){case "delete":if(!se&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${j.$id}" because it is not linked to $id:"${Q.$id}"`);break;case "update":if(!se&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${j.$id}" because it is not linked to $id:"${Q.$id}"`);break;case "unlink":if(!se&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${j.$id}" because it is not linked to $id:"${Q.$id}"`);break;case "link":if(se)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${j.$id}" because it is already linked to $id:"${Q.$id}"`);break;}});})))(D);let ne=(M=>produce(M,w=>traverse(w,S=>{let{value:F,meta:b}=S;isObject(F)&&(F[Symbol.for("path")]=b.nodePath,F.$objectPath=void 0,F.$parentIsCreate=void 0);})))(D);return [...Array.isArray(ne)?ne:[ne]].sort((M,w)=>M.$op==="create"&&w.$op!=="create"?-1:M.$op!=="create"&&w.$op==="create"?1:0)},Id=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Ds=(e,t)=>produce(e,r=>mn(t,r)),mn=(e,t,n)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)mn(e,i,n);return}let r=oe(e,n||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||_d(e,t,i,r);},_d=(e,t,n,r)=>{let i=t[n];if(!i)return;let o=r.dataFields?.find(l=>l.path===n);if(o){o.contentType==="JSON"&&i!=null&&(t[n]=JSON.stringify(i));return}let s=r.linkFields?.find(l=>l.path===n);if(s){let l=s.oppositeLinkFieldsPlayedBy[0]?.thing;mn(e,i,l);return}if(!("refFields"in r&&r.refFields[n])&&r.thingType==="relation"){let l=r.roles[n];if(!l)throw new Error(`[Schema] Role ${n} in ${r.name} is not defined`);let[d]=l.playedBy||[];if(!d)throw new Error(`Role ${l.path} in ${r} is not played by anything`);mn(e,i,d.thing);}};var ks=Re,ct=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,jd=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Pd=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),qd=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),xd=async e=>(ce(`>>> mutationMachine/enrich[${de}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?sr(e.bql.enriched,e.schema,e.config):sr(e.bql.raw,e.schema,e.config)),Vd=async e=>(ce(`>>> mutationMachine/preQuery[${de}]`,JSON.stringify(e.bql.enriched)),Ls(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),zd=async e=>(ce(`>>> mutationMachine/preQueryDependencies[${de}]`,JSON.stringify(e.bql.enriched)),Es(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),Wd=async e=>(ce(`>>> mutationMachine/parseBQL[${de}]`,JSON.stringify(e.bql.enriched)),As(e.bql.enriched,e.schema)),Ud=async e=>(ce(`>>> mutationMachine/flattenBQL[${de}]`,JSON.stringify(e.bql.enriched)),Ts(e.bql.enriched,e.schema)),vd=e=>{let{dbConnectors:t}=e.config;return t.length!==1||t[0].provider!=="surrealDB"?false:process.env.BLITZ_ORM_OLD_SURREALDB_MUTATION!=="true"},Hd=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:n}]=t;if(n==="typeDB")return true;if(n==="surrealDB")return false;throw new Error(`Unsupported provider ${n}.`)},Yd=e=>bt(e.bql.enriched),dt=U("error","error",W((e,t)=>({...e,error:t.error}))),Kd=Ce("stringify",{stringify:te(async e=>(ce(`>>> mutationMachine/stringify[${de}]`,JSON.stringify(e.bql.raw)),Ds(e.bql.raw,e.schema)),U("done","adapter",nn(vd),W(ct)),U("done","enrich",W(ct)),dt),enrich:te(xd,U("done","preQuery",nn(Hd),W(ct)),U("done","parseBQL",W(ct)),dt),preQuery:te(Vd,U("done","preHookDependencies",nn(Yd),W(ct)),U("done","parseBQL",W(ct)),dt),preHookDependencies:te(zd,U("done","enrich",W(ct)),dt),parseBQL:te(Wd,U("done","flattenBQL",W(jd)),dt),flattenBQL:te(Ud,U("done","adapter",W(Pd)),dt),adapter:te(async e=>{ce(`>>> mutationMachine/adapter[${de}]`,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:n}]=t;if(n==="typeDB")return wo(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(n==="surrealDB")return process.env.BLITZ_ORM_OLD_SURREALDB_MUTATION==="true"?Bo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles):Ji(e.bql.raw,e.draftSchema,e.config,e.handles);throw new Error(`Unsupported provider ${n}.`)},U("done","success",W(qd)),dt),success:ks(),error:ks()},e=>e),Jd=async e=>new Promise((t,n)=>{_e(Kd,r=>{r.machine.state.name==="success"&&t(r.context),r.machine.state.name==="error"&&n(r.context);},e);}),Qs=async(e,t,n,r,i)=>Jd({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,draftSchema:n,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var br=class{schema;config;initializing=false;subscribers=[];initialized=null;constructor({schema:t,config:n}){this.schema=t,this.config=n;}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((n,r)=>{this.subscribers.push(i=>{i?r(i):n();});});this.initializing=true;let t={typeDB:new Map,surrealDB:new Map};try{await Promise.all(this.config.dbConnectors.map(async r=>{if(r.provider==="surrealDB"){let i=new jt({url:r.url,username:r.username,password:r.password,namespace:r.namespace,database:r.dbName});await i.connect(),t.surrealDB.set(r.id,{client:i});}else if(r.provider==="typeDB"&&r.dbName){let[i,o]=await tryit(TypeDB.coreDriver)(r.url);if(i){let s=`[BORM:${r.provider}:${r.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await o.session(r.dbName,SessionType.DATA);t.typeDB.set(r.id,{client:o,session:s});}catch(s){let a=`[BORM:${r.provider}:${r.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}else if(r.provider==="typeDBCluster"&&r.dbName){let i=new TypeDBCredential(r.username,r.password,r.tlsRootCAPath),[o,s]=await tryit(TypeDB.cloudDriver)(r.addresses,i);if(o){let a=`[BORM:${r.provider}:${r.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(r.dbName,SessionType.DATA);t.typeDB.set(r.id,{client:s,session:a});}catch(a){let l=`[BORM:${r.provider}:${r.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={draftSchema:qr(this.schema),enrichedSchema:Ir(this.schema,t),dbHandles:t};let n=this.subscribers;this.subscribers=[];for(let r of n)r();}catch(n){let r=this.subscribers;this.subscribers=[];for(let i of r)i(n);}finally{this.initializing=false;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await Dr(this.config,t.enrichedSchema,t.draftSchema,t.dbHandles)};query=async(t,n)=>{let r=await this.getInitialized(),i={...this.config,query:{...gn.query,...this.config.query,...n}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(Tt)(s,r.enrichedSchema,r.draftSchema,i,r.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,n)=>{let r=await this.getInitialized(),i={...this.config,mutation:{...gn.mutation,...this.config.mutation,...n}},[o,s]=await tryit(Qs)(t,r.enrichedSchema,r.draftSchema,i,r.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:n})=>{n.isOpen()&&await n.close(),await t.close();})),await Promise.all([...this.initialized.dbHandles.surrealDB?.values()??[]].map(async({client:t})=>{await t.close();}));}finally{this.initialized=null;}}},cy=br;//! 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
135
136
  //! Todo: delete when this works with the new $thing and $thingType fields
136
137
  //! reads all the insertions and gets the first match. This means each id must be unique
137
138
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
138
139
  //!old
139
- export{ly as default};//# sourceMappingURL=index.mjs.map
140
+ export{cy as default};//# sourceMappingURL=index.mjs.map
140
141
  //# sourceMappingURL=index.mjs.map