@blitznocode/blitz-orm 0.11.9 → 0.11.11

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
@@ -100,7 +100,7 @@ ${o}`}).join(`
100
100
  DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
101
101
  RETURN (type::is::array($var) AND $var) OR [$var]
102
102
  };
103
- `,mr=e=>gi(e);var yr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([c])=>[c,await ur(c,e,t,r)]))).map(c=>[c[0],c[1]]),o=(await Promise.all([...r.surrealDB||[]].map(async([c])=>[c,mr(t)]))).map(c=>[c[0],c[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(o)}})();var ie=Symbol.for("queryPath"),et=Symbol.for("stepPrint"),Ce=Symbol.for("edgeType"),Fe=Symbol.for("edgeSchema"),qe=Symbol.for("dbNode"),wt=Symbol.for("isTransformed"),tt=Symbol.for("parent"),oe=Symbol.for("fieldSchema"),Te=Symbol.for("sharedMetadata"),Se=Symbol.for("suqlMetadata");var gr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Er=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let s=r.relations[e.relation].subTypes||[],i=[e.relation,...s],a=`<-\u27E8${t}_${e.plays}\u27E9<-(\u27E8${i.join("\u27E9,\u27E8")}\u27E9)`;if(e.target==="relation"){if(n==="edges")return a;if(n==="refs")return e.cardinality==="MANY"?`$parent.[\`${e.path}\`]`:`$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[o]=e.oppositeLinkFieldsPlayedBy,c=r.entities[o.thing]?.subTypes||r.relations[o.thing]?.subTypes||[],p=[o.thing,...c],u=`->\u27E8${t}_${o.plays}\u27E9->(\u27E8${p.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${u}`:n==="refs"?e.cardinality==="MANY"?`$parent.[\`${o.plays}\`]`:`$parent.\`${o.plays}\``:`${a}${u}`}else throw new Error("Unsupported linkField target")};var br=(e,t,r)=>r?t:`${e}\xB7${t}`;var wr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ce=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,s])=>{let[i,a]=tryit(()=>t(n,s))();return i?!1:a}))},Mr=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:o,meta:c})=>{if(c.depth===2&&(a&&(o.dataFields=o.dataFields?.map(p=>({...p,...o.idFields?.includes(p.path)?{isIdField:!0}:{isIdField:!1},cardinality:p.cardinality||"ONE",dbPath:"dbPath"in p?p.dbPath:br(a,p.path,p.shared)}))),o.extends)){if(!o.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${c.nodePath}`);let p=i.entities[o.extends]||i.relations[o.extends],u=[o.extends,...p.allExtends||[]];if(o.allExtends=u,u.forEach(d=>{if(i.entities[d])i.entities[d].subTypes=[a,...i.entities[d].subTypes||[]];else if(i.relations[d])i.relations[d].subTypes=[a,...i.relations[d].subTypes||[]];else throw new Error(`[Schema] ${a} is extending a thing that does not exist in the schema: ${d}`)}),o.idFields=p.idFields?Array.from(new Set((o.idFields||[]).concat(p.idFields))):o.idFields,o.dataFields=p.dataFields?(o.dataFields||[]).concat(p.dataFields.map(d=>{let l=o.extends,f=e.entities[l]||e.relations[l];for(;!f.dataFields?.find(h=>h.path===d.path);)l="extends"in f?f.extends:void 0,f=e.entities[l]||e.relations[l];return {...d,inherited:!0,dbPath:"dbPath"in d?d.dbPath:br(l,d.path,d.shared),[Te]:{inheritanceOrigin:d[Te]?.inheritanceOrigin||o.extends}}})):o.dataFields,"roles"in p){let d=o,l=p;if(l.roles){let f=mapEntries(l.roles,(h,$)=>[h,{...$,inherited:!0,[Te]:{inheritanceOrigin:$[Te]?.inheritanceOrigin||o.extends}}]);d.roles={...d.roles||{},...f};}}o.linkFields=p.linkFields?(o.linkFields||[]).concat(p.linkFields.map(d=>({...d,inherited:!0,[Te]:{inheritanceOrigin:d[Te]?.inheritanceOrigin||o.extends}}))):o.linkFields,p?.hooks?.pre&&(o.hooks=o.hooks||{},o.hooks.pre=o.hooks.pre||[],o.hooks.pre=[...p?.hooks?.pre||[],...o?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:a,meta:o})=>{if(i==="linkFields"){let p=(()=>{if(!o.nodePath)throw new Error("No path");let[d,l]=o.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),u=Array.isArray(a)?a.map(d=>({...d,...p})):[{...a,...p}];r.push(...u);}}),produce(n,i=>traverse(i,({value:a,key:o,meta:c})=>{if(c.depth===2&&a.idFields&&!a.id){a.name=o;let p=()=>{if(c.nodePath?.split(".")[0]==="entities")return "entity";if(c.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=p();let u=Object.keys(t).find(d=>t[d]?.get(a.defaultDBConnector.id));if(a.db=u,a.dbContext=gr[u],a.dbProviderConfig=u==="surrealDB"?t[u]?.get(a.defaultDBConnector.id)?.providerConfig:void 0,a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"linkFields"in a&&a.linkFields){let d=a;d.linkFields?.forEach(l=>{l.fieldType="linkField";let f=n.relations[l.relation];if(!l.isVirtual){if(!f)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(f.roles?.[l.plays]===void 0)throw new Error(`The role ${l.plays} is not defined in the relation ${l.relation} (linkField: ${l.path})`)}if(l.target==="relation"){if(l.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.$things=[l.relation,...f.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){if(l.oppositeLinkFieldsPlayedBy=r.filter(h=>h.relation===l.relation&&h.plays!==l.plays&&h.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.pathToRelation=d.linkFields?.find(h=>h.target==="relation"&&h.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(h=>[h.thing,...v(n,h.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(h=>h.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(a.db==="surrealDB"){let h=f?.roles?.[l.plays][Te]?.inheritanceOrigin??l.relation,$=Er({linkField:l,originalRelation:h,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Se]={queryPath:$};}});}if("roles"in a){let d=a;Object.entries(d.roles).forEach(([l,f])=>{f.fieldType="roleField";let h=r.filter(y=>y.relation===o&&y.plays===l)||[];f.playedBy=h.map(y=>({...y,pathToRelation:y.target==="relation"?y.path:d.linkFields?.find(R=>R.target==="relation"&&R.relation===o&&R.plays===l)?.path??y.relation.toLocaleLowerCase()}));let $=r.filter(y=>y.target==="relation"&&y.plays===l&&d.allExtends?.includes(y.relation));f.impactedLinkFields=$,f.path=l;let g=[...new Set(h.flatMap(y=>[...v(n,y.thing).subTypes||[],y.thing]).flat().filter(Boolean))];f.$things=g;let m=f[Te]?.inheritanceOrigin||a.name,F=g.flatMap(y=>{let L=v(e,y)?.subTypes||[];return [y,...L]}),b=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${m}_${l}\`->(\`${F.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.[\`${l}\`]`;if(f.cardinality==="ONE")return `$parent.\`${l}\``}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let y=b();f[Se]={queryPath:y};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let p=[...new Set(a.playedBy.map(u=>u.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${o}, path:${c.nodePath}, played by: ${p.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${o}, path:${c.nodePath}`)}if(c.depth===4){let[p,u]=c.nodePath?.split(".")||[],d=i[p][u];!isArray(a)&&typeof a=="object"&&(a.validations&&(a.validations.required&&d.requiredFields.push(a.path),a.validations.enum&&d.enumFields.push(a.path),a.validations.fn&&d.fnValidatedFields.push(a.path)),a.default?a.isVirtual?d.virtualFields.push(a.path):d.computedFields.push(a.path):a.isVirtual&&d.virtualFields.push(a.path));}}))},v=(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`)},x=(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)}`)},nt=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(e.idFields?.includes(t)){if(!r)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",r]}if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];let s="roles"in e?e.roles[t]:void 0;if(s)return ["roleField",s];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},it=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[n]=r.idFields;return n},Sr=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},Lt=(e,t,r)=>{let n=x(e,t),s=n.linkFields?.find(o=>o.path===r);if(s)return s;let i=n.dataFields?.find(o=>o.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},Qt=(e,t,r)=>Lt(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],n=e.linkFields?.map(h=>h.path)||[],s="roles"in e?listify(e.roles,h=>h):[],i=[...r||[],...n||[],...s||[]],o=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!t)return {fields:i,dataFields:r,roleFields:s,linkFields:n};let c=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!i.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!i.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),p=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],u=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...s||[],...n||[]].includes(h)):[],d=[...c,...p].filter(h=>!h?.startsWith("%")).filter(h=>!o.includes(h)).filter(h=>h),l=t.$filter?ce(t.$filter,(h,$)=>p.includes(h)):{},f=t.$filter?ce(t.$filter,(h,$)=>u.includes(h)):{};return {fields:i,dataFields:r,roleFields:s,linkFields:n,usedFields:c,usedLinkFields:n.filter(h=>c.includes(h)),usedRoleFields:s.filter(h=>c.includes(h)),usedDataFields:r.filter(h=>c.includes(h)),unidentifiedFields:d,...p.length?{localFilters:l}:{},...u.length?{nestedFilters:f}:{}}};var Lr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Qr=(e,t,r)=>{let s=(r.nodePath||"").split("."),i=isArray(t)?s.slice(0,-2).join("."):s.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},Le=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var ot=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),be=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([n,s])=>{r[n]=isDraft(s)?current(s):s;}),r}else return e},he=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ie=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var xe=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Dr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(s=>typeof s=="object"))if(n.every(s=>typeof s=="string")){let s=xe(t,r),[i]=s,a=e.$op==="create"?"link":"replace",o=i.thing,c=i.thingType,p={$op:a,$thing:o,$thingType:c},u=n.filter(l=>l.startsWith("_:")),d=n.filter(l=>!l.startsWith("_:"));u.length&&!d.length?e[t]=u.map(l=>({...p,$tempId:l,$bzId:l})):u.length&&d.length?e[t]=[...u.map(l=>({...p,$tempId:l,$bzId:l})),{...p,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...p,$id:e[t],$bzId:`S_${nanoid()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(n)} Parent: ${JSON.stringify(e,null,2)})`)};var Ae=(e,t,r)=>{let n=x(r,t),{usedDataFields:s}=de(n,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&s.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&s.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var st=(e,t,r)=>{let n=x(r,t),{usedFields:s}=de(n,t);return t.$op?(Ae(e,t,r),t.$op):t.$id||t.$filter?s.length>0?(Ae(e,{...t,$op:"update"},r),"update"):(Ae(e,{...t,$op:"link"},r),"link"):t.$tempId?s.length>0?(Ae(e,{...t,$op:"create"},r),"create"):(Ae(e,{...t,$op:"create"},r),"link"):(Ae(e,{...t,$op:"create"},r),"create")};var Ir=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(s=>{let i=st(s,s,t);return {...{...s.$thing?{}:{$thing:s.$entity||s.$relation},...s.$thingType?{}:{$thingType:Sr(s,t)},...s.$op?{}:{$op:i},...s.$bzId?{}:{$bzId:`R_${Ie()}`}},...s}});e.$root=isArray(e.$root)?n:n[0];};var at=(e,t)=>{let r=t[et];return isSet(r)?r.has("clean")?(Reflect.set(t,et,r.add("clean")),!0):!1:(Reflect.set(t,et,new Set(["clean"])),!0)};var Ar=(e,t,r)=>{if(at("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(s=>{if(isObject(s)&&"$id"in s&&isArray(s.$id)){let i=s;if(x(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,o)=>({...be(i),$id:a,$bzId:`${i.$bzId}_${o}`,...Le(i)}))}return s});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Or=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=xe(t,r),[o]=a,c=st(e,{...i,$thing:o.thing,$thingType:o.thingType},n),u=i.$bzId?i.$bzId:i.$tempId?i.$tempId:i.$id&&!isArray(i.$id)?`SN_ONE_${o.thing}_${i.$id}`:i.$id&&isArray(i.$id)?`SN_MANY_${o.thing}_${Ie()}`:`SM_${Ie()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Fe]:r,$thing:o.thing,$thingType:o.thingType,$op:c,$bzId:u}});e[t]=isArray(e[t])?s:s[0];};var Pi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,ki=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Pr=e=>{let r=e.toString().replace(Pi,"").trim().split("=>")[0].split("{")[0].replace(ki,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(o=>o.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var Ne=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:n}=t.default,i=Pr(n).filter(a=>!(a in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var kr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(s=>{let i=x(r,s),{unidentifiedFields:a}=de(i,s),{computedFields:o,virtualFields:c}=i,p=listify(s,(l,f)=>f!==void 0?l:void 0),u=p.filter(l=>c?.includes(l));if(u.length>0)throw new Error(`Virtual fields can't be sent to DB: "${u.join(",")}"`);if(o.filter(l=>!p.includes(l)).forEach(l=>{let f=i.dataFields?.find(F=>F.path===l),$=i.linkFields?.find(F=>F.path===l)?.oppositeLinkFieldsPlayedBy[0],g="roles"in i?wr(i.roles,(F,b)=>F===l):void 0,m=f||$||g;if(!m)throw new Error(`no field Def for ${l}`);if(s.$op==="create"&&!s[l]){let F=Ne({currentThing:s,fieldSchema:m,mandatoryDependencies:!0});s[l]=F;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(s)}`)}),e};var ct=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let n=`on${Lr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var xr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){if(i.$fields)return i;let{requiredFields:a,enumFields:o,fnValidatedFields:c,dataFields:p}=x(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(u=>{if(!(u in i))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&o.forEach(u=>{if(u in i){let d=p?.find(l=>l.path===u)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(i[u]))i[u].some(l=>{if(!d.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(d&&!d.includes(i[u]))throw new Error(`[Validations] Option "${i[u]}" is not a valid option for field "${u}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&c.forEach(u=>{if(u in i)try{let d=p?.find(l=>l.path===u)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(i[u]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${u}] ${d.message}`)}}),isObject(i)&&"$thing"in i){let u=i.$thing,d=i,l=clone(be(e)),f=clone(be(d)),h=n.mutation?.context||{},$=clone(be(i[qe]||{}));ct(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let F=m.fn(f,l,h,$);if(F===!1)throw new Error(`${m.message}.`);if(F!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(F){throw new Error(`[Validations:thing:${u}] ${F.message}`)}}});}}});};var jr=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(ot(i)){if(i.$fields||i[wt])return i;let a=ct(i,r).filter(d=>d.type==="transform"),o=clone(be(e)),c=clone(be(i)),p=n.mutation?.context||{},u=clone(be(i[qe]||i.$dbNode));return a.forEach(d=>{let l=d.fn(c,o,p,u||{});Object.keys(l).length!==0&&(i={...c,...l,...Le(i),[wt]:!0});}),i}});e[t]=isArray(e[t])?s:s[0];};var _r=(e,t,r)=>{let n=xe(t,r),[s]=n;e[t]={$thing:s.thing,$thingType:s.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Fe]:r};};var je=e=>{if(Array.isArray(e)){for(let t of e)if(je(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&je(e[t]))return !0}return !1};var Wr=(e,t)=>{for(let s of e)if(!("$entity"in s)&&!("$relation"in s)&&(!("$thing"in s)||!("$thingType"in s)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,s=>traverse(s,i=>{let{value:a,meta:o}=i,c=a;if(isObject(c)){if(c.$id){if(o.nodePath?.includes(".$filter"))return;let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},u=x(t,p);if(!u?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=u.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),u?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let p=x(t,c);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=p.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c&&c.$thing){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[ie]=o.nodePath;let u=x(t,p);if(c.$filter&&(c.$filter=Qe(c.$filter,c.$thing,t),c.$filterByUnique=At(c.$filter,u)),c.$fields){c.$fields.some(f=>u?.idFields?.includes(f?.$path||f))||(c.$fields=[...c.$fields,...Array.isArray(u.idFields)?u.idFields:[]],c.$idNotIncluded=!0);let l=c.$fields?.flatMap(f=>{let h=Ur(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}else {let l=It(u)?.flatMap(f=>{let h=Ur(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}c.$excludedFields&&(c.$fields=c.$fields.filter(d=>dt(u,d)?!0:!c.$excludedFields.includes(d.$path)));}}}))},It=e=>{let t=e.dataFields?.map(i=>i.path)||[],r=e.linkFields?.map(i=>i.path)||[],n=Object.keys(e.roles||{})||[];return [...t,...r,...n]},At=(e,t)=>Object.keys(e||{}).some(n=>{let s=e[n];if(s!==null&&typeof s<"u"){let i=t.idFields?.includes(n),a=t.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique),o=n==="$id"&&!Array.isArray(s);if(i||a||o){if(typeof s!="object"||s===null||Array.isArray(s))return !Array.isArray(s);{let p=Object.keys(s);if(p.length===1&&p[0]==="$eq"){let u=s.$eq;if(typeof u!="object"||u===null||!Array.isArray(u))return !0}return !1}}}return !1}),dt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Wi=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:s,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:s,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[oe]:a}},zi=e=>{let{field:t,fieldStr:r,linkField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e,{target:c,oppositeLinkFieldsPlayedBy:p}=n;return p.map(u=>{let d=c==="role"?u.thingType:"relation",l=c==="role"?u.thing:n.relation,f={[`$${d}`]:l},h=x(a,f),$=t?.$fields?.filter(F=>dt(h,F)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let F=h.idFields||[];g=[...t.$fields,...F];}else g=t.$fields;else g=It(h);else g=["id"];t.$excludedFields&&(g=g.filter(F=>dt(h,F)?!0:!t.$excludedFields.includes(F.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:{...u,oppositeLinkFieldsPlayedBy:void 0},$path:u.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:c,$intermediary:u.relation,$justId:s,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:At(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[oe]:o}})},Vi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e;return n.playedBy.map(c=>{let{thing:p,thingType:u,relation:d}=c,l={[`$${u}`]:p},f=x(a,l),h=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=It(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>dt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:s,$id:t.$id,$filter:g,$idNotIncluded:h,$filterByUnique:At(t.$filter,f),$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[oe]:o}})},Ur=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,s=typeof e=="string",i=t.dataFields?.find(c=>c.path===n),a=t.linkFields?.find(c=>c.path===n),o=t.roles?.[n];if(i){let c=!!i.isVirtual&&!!i.default;return Wi({field:e,fieldStr:n,$justId:s,dbPath:i.dbPath,isVirtual:c,fieldSchema:i})}else {if(a)return zi({field:e,fieldStr:n,linkField:a,$justId:s,dbPath:a.path,schema:r,fieldSchema:a});if(o)return Vi({field:e,fieldStr:n,roleField:o,$justId:s,dbPath:n,schema:r,fieldSchema:o})}return null},Qe=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce((p,u)=>{let d=a[u],l=isArray(d)?d:[d];if(u.startsWith("$"))if(["$id","$thing"].includes(u))p[u]=d;else if(["$not","$or","$and"].includes(u))p[u]=Qe(d,t,r);else if(["$eq","$in","$exists"].includes(u))p[u]=d;else throw new Error(`[Internal] Unknown filter operator ${u}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=nt(f,u);if(h==="idField")p[u]=d;else if(h==="dataField")isObject(d)||isArray(d)&&d.some(isObject)?p[u]=isArray(d)?{$or:Qe(d,t,r)}:Qe(d,t,r):isArray(d)?p[u]={$in:d}:p[u]={$eq:d};else if(h==="linkField"||h==="roleField"){let g=$,[m]=g.$things;l.every(F=>typeof F=="string")?p[u]={$id:l,$thing:m}:l.every(F=>isObject(F))&&(p[u]=isArray(d)?{$or:Qe(d,m,r)}:Qe(d,m,r));}else throw new Error(`Field ${u} not found in schema of ${t}`)}return p},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var Gi=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(at("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Xi=(e,t)=>{},Pt=(e,t,r)=>{let n={$rootWrap:{$root:e}},s=je(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:o,parent:c,key:p,meta:u})=>{if(!(!c||!p)&&isObject(o)){let d=u.nodePath?.split(".")||[];if(!("$root"in o)){if(!("$thing"in o||"$entity"in o||"$relation"in o)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],g=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(g))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(o)?current(o):o)}`)}}let l=o,f=d.includes("$filter");"$filter"in l&&l.$filter&&(l.$filter=Qe(l.$filter,l.$thing,t)),Object.keys(l).forEach(h=>{if(Gi(l,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?Lt(t,l,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Xi();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(l[h]===null?_r(l,h,$):Dr(l,h,$)),$.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Ir(l,t);}let g=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");g.forEach(b=>{if(b){if($?.cardinality==="ONE"&&!b.$op&&!b.$id&&!b.$filter&&!b.$tempId&&l.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(b.$tempId&&!(b.$op===void 0||b.$op==="link"||b.$op==="create"||b.$op==="update"))throw new Error(`Invalid op ${b.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&Or(l,h,$,t),Ar(l,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&kr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(b=>{let y=x(t,b),{unidentifiedFields:R,usedLinkFields:L,usedFields:D,fields:C}=de(y,b);if(D.forEach(_=>{if(!C.includes(_))throw new Error(`[Schema] Field ${_} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(o)}`);if(L.length>1){let _=y.linkFields?.filter(J=>L.includes(J.path));_?.some((J,ue)=>_.some((K,I)=>{if(ue!==I&&J.target!==K.target&&J.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),s||(jr(l,h,t,r),xr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var zr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var vr=async(e,t)=>{let r=u=>{let d=[],l=[],f=m=>{if(m.$id)return m.$id;let F=x(t,m),{idFields:b}=F;if(!b)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[y]=b;if(!y)throw new Error(`no idField: ${JSON.stringify(m)}`);let R=F.dataFields?.find(C=>C.path===y),L=Ne({currentThing:m,fieldSchema:R,mandatoryDependencies:!0}),D=m[y]||m.$id||L;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},h=m=>{if(m.$op==="create"){let F=f(m);if(d.find(b=>b.$id===F&&b.$op==="create"))throw new Error(`Duplicate id ${F} for node ${JSON.stringify(m)}`);d.push({...m,$id:F});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let F=f(m);if(d.find(b=>b.$id===F&&b.$op==="create"))throw new Error(`Duplicate id ${F} for edge ${JSON.stringify(m)}`);l.push({...m,$id:F});return}l.push(m);};return traverse(u,({value:m,parent:F,meta:b})=>{if(!isObject(m))return;let y=m;if(!b.nodePath?.includes(".$filter")&&y.$thing){if(!y.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(y)}`);if(!y.$bzId)throw new Error("[internal error] BzId not found");let R=x(t,y),{dataFields:L,roleFields:D,linkFields:C,usedFields:_}=de(R,y),J=()=>{if(y.$op==="create"||y.$op==="delete")return y.$op;if(y.$op==="update"){let I=_.filter(B=>L?.includes(B)),q=_.filter(B=>D?.includes(B)),E=_.filter(B=>C?.includes(B));if(I.length>0)return "update";if(q.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(y)}`)}return "match"},ue={...y.$id&&{$id:y.$id},...y.$tempId&&{$tempId:y.$tempId},...y.$filter&&{$filter:y.$filter},$thing:y.$thing,...y.$thingType&&{$thingType:y.$thingType},...shake(pick(y,L||[""])),$op:J(),$bzId:y.$bzId};h(ue);let K=y[Fe];if(K?.fieldType==="linkField"){if((y.$op==="link"||y.$op==="unlink")&&(y.$id||y.$filter)){if(y.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...y,$op:"match"});}let I=K.relation===y.$thing,q=I?y.$bzId:`LT_${v4()}`,B=Qr(u,F,b).$bzId;if(!B)throw new Error("No parent id found");let T=()=>y.$op==="delete"?I?"match":"delete":y.$op==="unlink"?I?"unlink":"delete":y.$op==="link"||y.$op==="create"?I?"link":"create":y.$op==="replace"?"replace":"match",S=x(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(S.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let Q={$bzId:q,$thing:K.relation,$thingType:"relation",...y.$tempId?{$tempId:y.$tempId}:{},$op:T(),...I?{}:{[K.path]:y.$bzId},[K.plays]:B,[Fe]:K,[Ce]:"linkField"};$(Q),(y.$op==="unlink"||T()==="unlink")&&I&&$({$thing:K.relation,$thingType:"relation",$bzId:q,$op:"match",[K.plays]:B,[Fe]:K,[Ce]:"linkField"});}if(y.$thingType==="relation"){let I=ce(y,(B,T)=>D.includes(B)),q=mapEntries(I,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),E=ce(m,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(I).filter(B=>!B.startsWith("$")).length>0){if(y.$op==="create"||y.$op==="delete"){let B=()=>{if(y.$op==="create")return "link";if(y.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=x(t,y).roles,S=mapEntries(q,(Q,A)=>{let U=T[Q]?.cardinality;if(!U)throw new Error(`Role ${Q} not found in schema`);if(Array.isArray(A)){if(U==="ONE"){if(A.length>1)throw new Error(`[Error] Role ${Q} is not a MANY relation`);return [Q,A[0].$bzId||A[0]]}return [Q,A.map(P=>P.$bzId||P)]}return [Q,A.$bzId||A]}),w={...E,$thing:y.$thing,$thingType:"relation",$op:B(),...S,$bzId:y.$bzId,[Ce]:"roleField"};$(w);return}if(y.$op==="match"||y.$op==="update"&&Object.keys(I).length>0){let B=0;Object.entries(I).forEach(([T,S])=>{let w=isArray(S)?S:[S],Q=A=>A==="create"||A==="replace"?"link":A;w.forEach(A=>{if(!A)return;let U=Q(A.$op);if(U==="replace")throw new Error("Not supported yet: replace on roleFields");if(U==="unlink"&&B>0)throw B+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let P={...E,$thing:y.$thing,$thingType:"relation",$op:U==="delete"?"unlink":U,[T]:A.$bzId,$bzId:y.$bzId,[Ce]:"roleField"};$(P);});});}}}}}),[d,l]},[n,s]=r(e),i=n.reduce((u,d)=>{if(!d.$bzId)return [...u,d];let l=u.findIndex(f=>f.$bzId===d.$bzId);if(l===-1)return [...u,d];if(u[l].$op==="create"&&d.$op==="match")return u;if(u[l].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...u.slice(0,l),d,...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d},...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="match"||u[l].$op==="match"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d,$op:"update"},...u.slice(l+1)];if(u[l].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(u[l].$filter)===JSON.stringify(d.$filter))return u;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${u[l].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${u[l].$op}. Current: ${d.$op}`)},[]),a=s.reduce((u,d)=>{let l=u.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(l){let f={...l};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=l[$],m=d[$];Array.isArray(g)&&Array.isArray(m)?f[$]=Array.from(new Set([...g,...m])):!Array.isArray(g)&&Array.isArray(m)?g!==void 0?f[$]=Array.from(new Set([g,...m])):f[$]=m:Array.isArray(g)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...g,m]))):g!==null&&m!==null&&g!==void 0&&m!==void 0?f[$]=Array.from(new Set([g,m])):g==null&&(f[$]=m);}),[...u.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...u,d]},[]);i.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&a.filter(d=>d.$bzId===u.$bzId||d.$tempId&&d.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(zr(u))}`)}});let o=[...i,...a],c=new Set(o.filter(u=>u.$tempId).map(u=>u.$tempId)),p=Array.from(c).filter(u=>!o.some(d=>d.$tempId===u&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var Ue={};function re(e){return {enumerable:!0,value:e}}function Jr(e){return {enumerable:!0,writable:!0,value:e}}var oo=()=>!0,Yr=()=>({}),Xr=e=>e,so=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),ao=(e,t,r,[n,s])=>t.call(r,e.call(r,n,s),s),Re=(e,t)=>Object.freeze(Object.create(e,t));function Gr(e,t,r){return e.reduce((n,s)=>function(...i){return r(n,s,this,i)},t)}function Zr(e){return Re(this,{fn:re(e)})}var en={},N=Zr.bind(en);var tn={},kt=Zr.bind(tn);function ut(e,t){return t.filter(r=>e.isPrototypeOf(r))}function rn(e,t,...r){let n=Gr(ut(tn,r).map(i=>i.fn),oo,so),s=Gr(ut(en,r).map(i=>i.fn),Xr,ao);return Re(this,{from:re(e),to:re(t),guards:re(n),reducers:re(s)})}var nn={},on={},j=rn.bind(nn);rn.bind(on,null);function lo(e,t,r){return xt(t,e,r,this.immediates)||e}function sn(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var co={enter:Xr};function se(...e){let t=ut(nn,e),r=ut(on,e),n={final:re(e.length===0),transitions:re(sn(t))};return r.length&&(n.immediates=re(r),n.enter=re(lo)),Re(co,n)}var uo={enter(e,t,r){let n=this.fn.call(t,t.context,r);return qt.isPrototypeOf(n)?Re(an,{machine:re(n),transitions:re(this.transitions)}).enter(e,t,r):(n.then(s=>t.send({type:"done",data:s})).catch(s=>t.send({type:"error",error:s})),e)}},an={enter(e,t,r){if(t.child=fe(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,xt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function V(e,...t){let r=re(sn(t));return qt.isPrototypeOf(e)?Re(an,{machine:re(e),transitions:r}):Re(uo,{fn:re(e),transitions:r})}var qt={get state(){return {name:this.current,value:this.states[this.current]}}};function me(e,t,r=Yr){return typeof e!="string"&&(r=t||Yr,t=e,e=Object.keys(t)[0]),Ue._create&&Ue._create(e,t),Re(qt,{context:re(r),current:re(e),states:re(t)})}function xt(e,t,r,n){let{context:s}=e;for(let{to:i,guards:a,reducers:o}of n)if(a(s,r)){e.context=o.call(e,s,r);let c=t.original||t,p=Re(c,{current:re(i),original:{value:c}});Ue._onEnter&&Ue._onEnter(t,i,e.context,s,r);let u=p.state.value;return e.machine=p,e.onChange(e),u.enter(p,e,r)}}function ho(e,t){let r=t.type||t,{machine:n}=e,{value:s,name:i}=n.state;return s.transitions.has(r)?xt(e,n,t,s.transitions.get(r))||n:(Ue._send&&Ue._send(r,i),n)}var po={send(e){ho(this,e);}};function fe(e,t,r,n){let s=Object.create(po,{machine:Jr(e),context:Jr(e.context(r,n)),onChange:re(t)});return s.send=s.send.bind(s),s.machine=s.machine.state.value.enter(s.machine,s,n),s}var un=(e,t)=>{if(!t)return;let r=$o(t);return mo(r,e.query)},$o=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),mo=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let s=n;Object.keys(s).forEach(i=>{(s[i]===void 0||s[i]===null||isArray(s[i])&&s[i].length===0)&&(t?.returnNulls?s[i]=null:delete s[i]),s[i]===void 0&&delete s[i];}),Object.getOwnPropertySymbols(s).forEach(i=>{delete s[i];}),t?.noMetadata===!0&&Object.keys(s).forEach(i=>{i.startsWith("$")&&delete s[i];});}}));var hn=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:o})=>{if(isObject(o)){let c=o;if(!c.$thing)return;if(c.$thing){let p=x(e,c),{virtualFields:u}=p,d=c[ie];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),f=l.$fields.map($=>$.$path),h=l.$excludedFields;u.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(m=>m.path===$);if(g?.default){let m=Ne({currentThing:c,fieldSchema:g,mandatoryDependencies:!0});c[$]=m;}else if(c[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete c[$];});}}})))(r):void 0;var Ke={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},ye=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let c=Object.keys(a).reduce((p,u)=>{let d=a[u];if(u.startsWith("$")){if(["$or","$and","$not"].includes(u))return {...p,[u]:void 0,[Ke[u]]:ye(d,t,r)};if(u==="$id")return {...p,$id:void 0,[Ke[u]]:{$IN:isArray(d)?d:[d]}};if(u==="$thing")return p;if(u==="$exists")return {...p,$exists:void 0,[Ke[u]]:d};if(u==="$eq")return {...p,$eq:void 0,[Ke[u]]:d};if(u==="$in")return {...p,$in:void 0,[Ke[u]]:d};throw new Error(`Unknown filter operator ${u}`)}let l=t in r.entities?r.entities[t]:r.relations[t],[f,h]=nt(l,u);if(f==="idField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return {...p,"record::id(id)":{$IN:isArray(d)?d:[d]}}}if(f==="dataField")return {...p,[u]:ye(d,t,r)};if(f==="linkField"||f==="roleField"){let g=h[Se].queryPath;return {...p,[g]:ye(d,t,r)}}throw new Error(`Field ${u} not found in schema, Defined in $filter`)},{});return shake(c)});return n?i:i[0]},pe=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,s])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(s)?s.map(o=>pe(o)):[pe(s)];i==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(s))if(n.includes("<-")||n.includes("->")){let i=pe(s);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=pe(s),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=pe(s),a=n.replace("$parent.","");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let i=Object.keys(s);if(i.length===1&&i[0].startsWith("$")){let[a]=i,o=s[a];if(a==="$exists")if(o===!0)r.push(`${n} IS NOT NONE`);else if(o===!1)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${o}`);else {let c=a.replace("$","");if(Array.isArray(o))r.push(`${n} ${c} [${o.map(p=>p===null?"NONE":`'${p}'`).join(", ")}]`);else if(isObject(o)){let p=pe(o);r.push(`${n} ${c} ${p}`);}else r.push(`${n} ${c} ${o===null?"NONE":`'${o}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(s)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${s.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${s===null?"NONE":`'${s}'`}`);}}),r.join(" AND ")},We=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:s}=r;return `${n}${s?" DESC":" ASC"}`}).join(", ")}`;var fn=e=>{let{queries:t,schema:r}=e;return t.map(n=>To({query:n,schema:r}))},To=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push("SELECT");let u=jt({parentQuery:t,queries:s,level:1,schema:r});u&&p.push(u);let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let f=(d.subTypes?[n,...d.subTypes]:[n]).map(h=>ee(h));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(g=>h?.map(m=>`${g}:\u27E8${m}\u27E9`));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(i){let h=ye(i,n,r),$=pe(h);p.push(`WHERE ${$}`);}return c&&p.push(We(c)),typeof o=="number"&&p.push(`LIMIT ${o}`),typeof a=="number"&&p.push(`START ${a}`),p.join(`
103
+ `,mr=e=>gi(e);var yr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([c])=>[c,await ur(c,e,t,r)]))).map(c=>[c[0],c[1]]),o=(await Promise.all([...r.surrealDB||[]].map(async([c])=>[c,mr(t)]))).map(c=>[c[0],c[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(o)}})();var ie=Symbol.for("queryPath"),et=Symbol.for("stepPrint"),Ce=Symbol.for("edgeType"),Fe=Symbol.for("edgeSchema"),qe=Symbol.for("dbNode"),wt=Symbol.for("isTransformed"),tt=Symbol.for("parent"),oe=Symbol.for("fieldSchema"),Te=Symbol.for("sharedMetadata"),Se=Symbol.for("suqlMetadata");var gr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Er=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let s=r.relations[e.relation].subTypes||[],i=[e.relation,...s],a=`<-\u27E8${t}_${e.plays}\u27E9<-(\u27E8${i.join("\u27E9,\u27E8")}\u27E9)`;if(e.target==="relation"){if(n==="edges")return a;if(n==="refs")return e.cardinality==="MANY"?`$parent.[\`${e.path}\`]`:`$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[o]=e.oppositeLinkFieldsPlayedBy,c=r.entities[o.thing]?.subTypes||r.relations[o.thing]?.subTypes||[],p=[o.thing,...c],u=`->\u27E8${t}_${o.plays}\u27E9->(\u27E8${p.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${u}`:n==="refs"?e.cardinality==="MANY"?`$parent.[\`${o.plays}\`]`:`$parent.\`${o.plays}\``:`${a}${u}`}else throw new Error("Unsupported linkField target")};var br=(e,t,r)=>r?t:`${e}\xB7${t}`;var wr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ce=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,s])=>{let[i,a]=tryit(()=>t(n,s))();return i?!1:a}))},Mr=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:o,meta:c})=>{if(c.depth===2&&(a&&(o.dataFields=o.dataFields?.map(p=>({...p,...o.idFields?.includes(p.path)?{isIdField:!0}:{isIdField:!1},cardinality:p.cardinality||"ONE",dbPath:"dbPath"in p?p.dbPath:br(a,p.path,p.shared)}))),o.extends)){if(!o.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${c.nodePath}`);let p=i.entities[o.extends]||i.relations[o.extends],u=[o.extends,...p.allExtends||[]];if(o.allExtends=u,u.forEach(d=>{if(i.entities[d])i.entities[d].subTypes=[a,...i.entities[d].subTypes||[]];else if(i.relations[d])i.relations[d].subTypes=[a,...i.relations[d].subTypes||[]];else throw new Error(`[Schema] ${a} is extending a thing that does not exist in the schema: ${d}`)}),o.idFields=p.idFields?Array.from(new Set((o.idFields||[]).concat(p.idFields))):o.idFields,o.dataFields=p.dataFields?(o.dataFields||[]).concat(p.dataFields.map(d=>{let l=o.extends,f=e.entities[l]||e.relations[l];for(;!f.dataFields?.find(h=>h.path===d.path);)l="extends"in f?f.extends:void 0,f=e.entities[l]||e.relations[l];return {...d,inherited:!0,dbPath:"dbPath"in d?d.dbPath:br(l,d.path,d.shared),[Te]:{inheritanceOrigin:d[Te]?.inheritanceOrigin||o.extends}}})):o.dataFields,"roles"in p){let d=o,l=p;if(l.roles){let f=mapEntries(l.roles,(h,$)=>[h,{...$,inherited:!0,[Te]:{inheritanceOrigin:$[Te]?.inheritanceOrigin||o.extends}}]);d.roles={...d.roles||{},...f};}}o.linkFields=p.linkFields?(o.linkFields||[]).concat(p.linkFields.map(d=>({...d,inherited:!0,[Te]:{inheritanceOrigin:d[Te]?.inheritanceOrigin||o.extends}}))):o.linkFields,p?.hooks?.pre&&(o.hooks=o.hooks||{},o.hooks.pre=o.hooks.pre||[],o.hooks.pre=[...p?.hooks?.pre||[],...o?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:a,meta:o})=>{if(i==="linkFields"){let p=(()=>{if(!o.nodePath)throw new Error("No path");let[d,l]=o.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),u=Array.isArray(a)?a.map(d=>({...d,...p})):[{...a,...p}];r.push(...u);}}),produce(n,i=>traverse(i,({value:a,key:o,meta:c})=>{if(c.depth===2&&a.idFields&&!a.id){a.name=o;let p=()=>{if(c.nodePath?.split(".")[0]==="entities")return "entity";if(c.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=p();let u=Object.keys(t).find(d=>t[d]?.get(a.defaultDBConnector.id));if(a.db=u,a.dbContext=gr[u],a.dbProviderConfig=u==="surrealDB"?t[u]?.get(a.defaultDBConnector.id)?.providerConfig:void 0,a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"linkFields"in a&&a.linkFields){let d=a;d.linkFields?.forEach(l=>{l.fieldType="linkField";let f=n.relations[l.relation];if(!l.isVirtual){if(!f)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(f.roles?.[l.plays]===void 0)throw new Error(`The role ${l.plays} is not defined in the relation ${l.relation} (linkField: ${l.path})`)}if(l.target==="relation"){if(l.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.$things=[l.relation,...f.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){if(l.oppositeLinkFieldsPlayedBy=r.filter(h=>h.relation===l.relation&&h.plays!==l.plays&&h.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.pathToRelation=d.linkFields?.find(h=>h.target==="relation"&&h.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(h=>[h.thing,...v(n,h.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(h=>h.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(a.db==="surrealDB"){let h=f?.roles?.[l.plays][Te]?.inheritanceOrigin??l.relation,$=Er({linkField:l,originalRelation:h,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Se]={queryPath:$};}});}if("roles"in a){let d=a;Object.entries(d.roles).forEach(([l,f])=>{f.fieldType="roleField";let h=r.filter(y=>y.relation===o&&y.plays===l)||[];f.playedBy=h.map(y=>({...y,pathToRelation:y.target==="relation"?y.path:d.linkFields?.find(R=>R.target==="relation"&&R.relation===o&&R.plays===l)?.path??y.relation.toLocaleLowerCase()}));let $=r.filter(y=>y.target==="relation"&&y.plays===l&&d.allExtends?.includes(y.relation));f.impactedLinkFields=$,f.path=l;let g=[...new Set(h.flatMap(y=>[...v(n,y.thing).subTypes||[],y.thing]).flat().filter(Boolean))];f.$things=g;let m=f[Te]?.inheritanceOrigin||a.name,F=g.flatMap(y=>{let L=v(e,y)?.subTypes||[];return [y,...L]}),b=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${m}_${l}\`->(\`${F.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.[\`${l}\`]`;if(f.cardinality==="ONE")return `$parent.\`${l}\``}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let y=b();f[Se]={queryPath:y};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let p=[...new Set(a.playedBy.map(u=>u.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${o}, path:${c.nodePath}, played by: ${p.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${o}, path:${c.nodePath}`)}if(c.depth===4){let[p,u]=c.nodePath?.split(".")||[],d=i[p][u];!isArray(a)&&typeof a=="object"&&(a.validations&&(a.validations.required&&d.requiredFields.push(a.path),a.validations.enum&&d.enumFields.push(a.path),a.validations.fn&&d.fnValidatedFields.push(a.path)),a.default?a.isVirtual?d.virtualFields.push(a.path):d.computedFields.push(a.path):a.isVirtual&&d.virtualFields.push(a.path));}}))},v=(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`)},x=(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)}`)},nt=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(e.idFields?.includes(t)){if(!r)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",r]}if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];let s="roles"in e?e.roles[t]:void 0;if(s)return ["roleField",s];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},it=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[n]=r.idFields;return n},Sr=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},Lt=(e,t,r)=>{let n=x(e,t),s=n.linkFields?.find(o=>o.path===r);if(s)return s;let i=n.dataFields?.find(o=>o.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},Qt=(e,t,r)=>Lt(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],n=e.linkFields?.map(h=>h.path)||[],s="roles"in e?listify(e.roles,h=>h):[],i=[...r||[],...n||[],...s||[]],o=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!t)return {fields:i,dataFields:r,roleFields:s,linkFields:n};let c=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!i.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!i.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),p=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],u=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...s||[],...n||[]].includes(h)):[],d=[...c,...p].filter(h=>!h?.startsWith("%")).filter(h=>!o.includes(h)).filter(h=>h),l=t.$filter?ce(t.$filter,(h,$)=>p.includes(h)):{},f=t.$filter?ce(t.$filter,(h,$)=>u.includes(h)):{};return {fields:i,dataFields:r,roleFields:s,linkFields:n,usedFields:c,usedLinkFields:n.filter(h=>c.includes(h)),usedRoleFields:s.filter(h=>c.includes(h)),usedDataFields:r.filter(h=>c.includes(h)),unidentifiedFields:d,...p.length?{localFilters:l}:{},...u.length?{nestedFilters:f}:{}}};var Lr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Qr=(e,t,r)=>{let s=(r.nodePath||"").split("."),i=isArray(t)?s.slice(0,-2).join("."):s.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},Le=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var ot=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),be=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([n,s])=>{r[n]=isDraft(s)?current(s):s;}),r}else return e},he=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ie=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var xe=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Dr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(s=>typeof s=="object"))if(n.every(s=>typeof s=="string")){let s=xe(t,r),[i]=s,a=e.$op==="create"?"link":"replace",o=i.thing,c=i.thingType,p={$op:a,$thing:o,$thingType:c},u=n.filter(l=>l.startsWith("_:")),d=n.filter(l=>!l.startsWith("_:"));u.length&&!d.length?e[t]=u.map(l=>({...p,$tempId:l,$bzId:l})):u.length&&d.length?e[t]=[...u.map(l=>({...p,$tempId:l,$bzId:l})),{...p,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...p,$id:e[t],$bzId:`S_${nanoid()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(n)} Parent: ${JSON.stringify(e,null,2)})`)};var Ae=(e,t,r)=>{let n=x(r,t),{usedDataFields:s}=de(n,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&s.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&s.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var st=(e,t,r)=>{let n=x(r,t),{usedFields:s}=de(n,t);return t.$op?(Ae(e,t,r),t.$op):t.$id||t.$filter?s.length>0?(Ae(e,{...t,$op:"update"},r),"update"):(Ae(e,{...t,$op:"link"},r),"link"):t.$tempId?s.length>0?(Ae(e,{...t,$op:"create"},r),"create"):(Ae(e,{...t,$op:"create"},r),"link"):(Ae(e,{...t,$op:"create"},r),"create")};var Ir=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(s=>{let i=st(s,s,t);return {...{...s.$thing?{}:{$thing:s.$entity||s.$relation},...s.$thingType?{}:{$thingType:Sr(s,t)},...s.$op?{}:{$op:i},...s.$bzId?{}:{$bzId:`R_${Ie()}`}},...s}});e.$root=isArray(e.$root)?n:n[0];};var at=(e,t)=>{let r=t[et];return isSet(r)?r.has("clean")?(Reflect.set(t,et,r.add("clean")),!0):!1:(Reflect.set(t,et,new Set(["clean"])),!0)};var Ar=(e,t,r)=>{if(at("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(s=>{if(isObject(s)&&"$id"in s&&isArray(s.$id)){let i=s;if(x(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,o)=>({...be(i),$id:a,$bzId:`${i.$bzId}_${o}`,...Le(i)}))}return s});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Or=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=xe(t,r),[o]=a,c=st(e,{...i,$thing:o.thing,$thingType:o.thingType},n),u=i.$bzId?i.$bzId:i.$tempId?i.$tempId:i.$id&&!isArray(i.$id)?`SN_ONE_${o.thing}_${i.$id}`:i.$id&&isArray(i.$id)?`SN_MANY_${o.thing}_${Ie()}`:`SM_${Ie()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Fe]:r,$thing:o.thing,$thingType:o.thingType,$op:c,$bzId:u}});e[t]=isArray(e[t])?s:s[0];};var Pi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,ki=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Pr=e=>{let r=e.toString().replace(Pi,"").trim().split("=>")[0].split("{")[0].replace(ki,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(o=>o.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var Ne=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:n}=t.default,i=Pr(n).filter(a=>!(a in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var kr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(s=>{let i=x(r,s),{unidentifiedFields:a}=de(i,s),{computedFields:o,virtualFields:c}=i,p=listify(s,(l,f)=>f!==void 0?l:void 0),u=p.filter(l=>c?.includes(l));if(u.length>0)throw new Error(`Virtual fields can't be sent to DB: "${u.join(",")}"`);if(o.filter(l=>!p.includes(l)).forEach(l=>{let f=i.dataFields?.find(F=>F.path===l),$=i.linkFields?.find(F=>F.path===l)?.oppositeLinkFieldsPlayedBy[0],g="roles"in i?wr(i.roles,(F,b)=>F===l):void 0,m=f||$||g;if(!m)throw new Error(`no field Def for ${l}`);if(s.$op==="create"&&!s[l]){let F=Ne({currentThing:s,fieldSchema:m,mandatoryDependencies:!0});s[l]=F;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(s)}`)}),e};var ct=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let n=`on${Lr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var xr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){if(i.$fields)return i;let{requiredFields:a,enumFields:o,fnValidatedFields:c,dataFields:p}=x(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(u=>{if(!(u in i))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&o.forEach(u=>{if(u in i){let d=p?.find(l=>l.path===u)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(i[u]))i[u].some(l=>{if(!d.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(d&&!d.includes(i[u]))throw new Error(`[Validations] Option "${i[u]}" is not a valid option for field "${u}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&c.forEach(u=>{if(u in i)try{let d=p?.find(l=>l.path===u)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(i[u]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${u}] ${d.message}`)}}),isObject(i)&&"$thing"in i){let u=i.$thing,d=i,l=clone(be(e)),f=clone(be(d)),h=n.mutation?.context||{},$=clone(be(i[qe]||{}));ct(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let F=m.fn(f,l,h,$);if(F===!1)throw new Error(`${m.message}.`);if(F!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(F){throw new Error(`[Validations:thing:${u}] ${F.message}`)}}});}}});};var jr=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(ot(i)){if(i.$fields||i[wt])return i;let a=ct(i,r).filter(d=>d.type==="transform"),o=clone(be(e)),c=clone(be(i)),p=n.mutation?.context||{},u=clone(be(i[qe]||i.$dbNode));return a.forEach(d=>{let l=d.fn(c,o,p,u||{});Object.keys(l).length!==0&&(i={...c,...l,...Le(i),[wt]:!0});}),i}});e[t]=isArray(e[t])?s:s[0];};var _r=(e,t,r)=>{let n=xe(t,r),[s]=n;e[t]={$thing:s.thing,$thingType:s.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Fe]:r};};var je=e=>{if(Array.isArray(e)){for(let t of e)if(je(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&je(e[t]))return !0}return !1};var Wr=(e,t)=>{for(let s of e)if(!("$entity"in s)&&!("$relation"in s)&&(!("$thing"in s)||!("$thingType"in s)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,s=>traverse(s,i=>{let{value:a,meta:o}=i,c=a;if(isObject(c)){if(c.$id){if(o.nodePath?.includes(".$filter"))return;let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},u=x(t,p);if(!u?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=u.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),u?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let p=x(t,c);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=p.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c&&c.$thing){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[ie]=o.nodePath;let u=x(t,p);if(c.$filter&&(Object.keys(c.$filter).length===0?c.$filter=void 0:(c.$filter=Qe(c.$filter,c.$thing,t),c.$filterByUnique=At(c.$filter,u))),c.$fields){c.$fields.some(f=>u?.idFields?.includes(f?.$path||f))||(c.$fields=[...c.$fields,...Array.isArray(u.idFields)?u.idFields:[]],c.$idNotIncluded=!0);let l=c.$fields?.flatMap(f=>{let h=Ur(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}else {let l=It(u)?.flatMap(f=>{let h=Ur(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}c.$excludedFields&&(c.$fields=c.$fields.filter(d=>dt(u,d)?!0:!c.$excludedFields.includes(d.$path)));}}}))},It=e=>{let t=e.dataFields?.map(i=>i.path)||[],r=e.linkFields?.map(i=>i.path)||[],n=Object.keys(e.roles||{})||[];return [...t,...r,...n]},At=(e,t)=>Object.keys(e||{}).some(n=>{let s=e[n];if(s!==null&&typeof s<"u"){let i=t.idFields?.includes(n),a=t.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique),o=n==="$id"&&!Array.isArray(s);if(i||a||o){if(typeof s!="object"||s===null||Array.isArray(s))return !Array.isArray(s);{let p=Object.keys(s);if(p.length===1&&p[0]==="$eq"){let u=s.$eq;if(typeof u!="object"||u===null||!Array.isArray(u))return !0}return !1}}}return !1}),dt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Wi=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:s,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:s,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[oe]:a}},zi=e=>{let{field:t,fieldStr:r,linkField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e,{target:c,oppositeLinkFieldsPlayedBy:p}=n;return p.map(u=>{let d=c==="role"?u.thingType:"relation",l=c==="role"?u.thing:n.relation,f={[`$${d}`]:l},h=x(a,f),$=t?.$fields?.filter(F=>dt(h,F)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let F=h.idFields||[];g=[...t.$fields,...F];}else g=t.$fields;else g=It(h);else g=["id"];t.$excludedFields&&(g=g.filter(F=>dt(h,F)?!0:!t.$excludedFields.includes(F.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:{...u,oppositeLinkFieldsPlayedBy:void 0},$path:u.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:c,$intermediary:u.relation,$justId:s,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:At(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[oe]:o}})},Vi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e;return n.playedBy.map(c=>{let{thing:p,thingType:u,relation:d}=c,l={[`$${u}`]:p},f=x(a,l),h=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=It(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>dt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:s,$id:t.$id,$filter:g,$idNotIncluded:h,$filterByUnique:At(t.$filter,f),$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[oe]:o}})},Ur=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,s=typeof e=="string",i=t.dataFields?.find(c=>c.path===n),a=t.linkFields?.find(c=>c.path===n),o=t.roles?.[n];if(i){let c=!!i.isVirtual&&!!i.default;return Wi({field:e,fieldStr:n,$justId:s,dbPath:i.dbPath,isVirtual:c,fieldSchema:i})}else {if(a)return zi({field:e,fieldStr:n,linkField:a,$justId:s,dbPath:a.path,schema:r,fieldSchema:a});if(o)return Vi({field:e,fieldStr:n,roleField:o,$justId:s,dbPath:n,schema:r,fieldSchema:o})}return null},Qe=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce((p,u)=>{let d=a[u],l=isArray(d)?d:[d];if(u.startsWith("$"))if(["$id","$thing"].includes(u))p[u]=d;else if(["$not","$or","$and"].includes(u))p[u]=Qe(d,t,r);else if(["$eq","$in","$exists"].includes(u))p[u]=d;else throw new Error(`[Internal] Unknown filter operator ${u}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=nt(f,u);if(h==="idField")p[u]=d;else if(h==="dataField")isObject(d)||isArray(d)&&d.some(isObject)?p[u]=isArray(d)?{$or:Qe(d,t,r)}:Qe(d,t,r):isArray(d)?p[u]={$in:d}:p[u]={$eq:d};else if(h==="linkField"||h==="roleField"){let g=$,[m]=g.$things;l.every(F=>typeof F=="string")?p[u]={$id:l,$thing:m}:l.every(F=>isObject(F))&&(p[u]=isArray(d)?{$or:Qe(d,m,r)}:Qe(d,m,r));}else throw new Error(`Field ${u} not found in schema of ${t}`)}return p},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var Gi=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(at("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified");t==="$filter"&&e.$filter&&Object.keys(e.$filter).length===0&&(e.$filter=void 0);},Xi=(e,t)=>{},Pt=(e,t,r)=>{let n={$rootWrap:{$root:e}},s=je(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:o,parent:c,key:p,meta:u})=>{if(!(!c||!p)&&isObject(o)){let d=u.nodePath?.split(".")||[];if(!("$root"in o)){if(!("$thing"in o||"$entity"in o||"$relation"in o)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],g=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(g))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(o)?current(o):o)}`)}}let l=o,f=d.includes("$filter");"$filter"in l&&l.$filter&&(l.$filter=Qe(l.$filter,l.$thing,t)),Object.keys(l).forEach(h=>{if(Gi(l,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?Lt(t,l,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Xi();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(l[h]===null?_r(l,h,$):Dr(l,h,$)),$.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Ir(l,t);}let g=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");g.forEach(b=>{if(b){if($?.cardinality==="ONE"&&!b.$op&&!b.$id&&!b.$filter&&!b.$tempId&&l.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(b.$tempId&&!(b.$op===void 0||b.$op==="link"||b.$op==="create"||b.$op==="update"))throw new Error(`Invalid op ${b.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&Or(l,h,$,t),Ar(l,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&kr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(b=>{let y=x(t,b),{unidentifiedFields:R,usedLinkFields:L,usedFields:D,fields:C}=de(y,b);if(D.forEach(_=>{if(!C.includes(_))throw new Error(`[Schema] Field ${_} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(o)}`);if(L.length>1){let _=y.linkFields?.filter(J=>L.includes(J.path));_?.some((J,ue)=>_.some((K,I)=>{if(ue!==I&&J.target!==K.target&&J.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),s||(jr(l,h,t,r),xr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var zr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var vr=async(e,t)=>{let r=u=>{let d=[],l=[],f=m=>{if(m.$id)return m.$id;let F=x(t,m),{idFields:b}=F;if(!b)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[y]=b;if(!y)throw new Error(`no idField: ${JSON.stringify(m)}`);let R=F.dataFields?.find(C=>C.path===y),L=Ne({currentThing:m,fieldSchema:R,mandatoryDependencies:!0}),D=m[y]||m.$id||L;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},h=m=>{if(m.$op==="create"){let F=f(m);if(d.find(b=>b.$id===F&&b.$op==="create"))throw new Error(`Duplicate id ${F} for node ${JSON.stringify(m)}`);d.push({...m,$id:F});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let F=f(m);if(d.find(b=>b.$id===F&&b.$op==="create"))throw new Error(`Duplicate id ${F} for edge ${JSON.stringify(m)}`);l.push({...m,$id:F});return}l.push(m);};return traverse(u,({value:m,parent:F,meta:b})=>{if(!isObject(m))return;let y=m;if(!b.nodePath?.includes(".$filter")&&y.$thing){if(!y.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(y)}`);if(!y.$bzId)throw new Error("[internal error] BzId not found");let R=x(t,y),{dataFields:L,roleFields:D,linkFields:C,usedFields:_}=de(R,y),J=()=>{if(y.$op==="create"||y.$op==="delete")return y.$op;if(y.$op==="update"){let I=_.filter(B=>L?.includes(B)),q=_.filter(B=>D?.includes(B)),E=_.filter(B=>C?.includes(B));if(I.length>0)return "update";if(q.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(y)}`)}return "match"},ue={...y.$id&&{$id:y.$id},...y.$tempId&&{$tempId:y.$tempId},...y.$filter&&{$filter:y.$filter},$thing:y.$thing,...y.$thingType&&{$thingType:y.$thingType},...shake(pick(y,L||[""])),$op:J(),$bzId:y.$bzId};h(ue);let K=y[Fe];if(K?.fieldType==="linkField"){if((y.$op==="link"||y.$op==="unlink")&&(y.$id||y.$filter)){if(y.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...y,$op:"match"});}let I=K.relation===y.$thing,q=I?y.$bzId:`LT_${v4()}`,B=Qr(u,F,b).$bzId;if(!B)throw new Error("No parent id found");let T=()=>y.$op==="delete"?I?"match":"delete":y.$op==="unlink"?I?"unlink":"delete":y.$op==="link"||y.$op==="create"?I?"link":"create":y.$op==="replace"?"replace":"match",S=x(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(S.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let Q={$bzId:q,$thing:K.relation,$thingType:"relation",...y.$tempId?{$tempId:y.$tempId}:{},$op:T(),...I?{}:{[K.path]:y.$bzId},[K.plays]:B,[Fe]:K,[Ce]:"linkField"};$(Q),(y.$op==="unlink"||T()==="unlink")&&I&&$({$thing:K.relation,$thingType:"relation",$bzId:q,$op:"match",[K.plays]:B,[Fe]:K,[Ce]:"linkField"});}if(y.$thingType==="relation"){let I=ce(y,(B,T)=>D.includes(B)),q=mapEntries(I,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),E=ce(m,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(I).filter(B=>!B.startsWith("$")).length>0){if(y.$op==="create"||y.$op==="delete"){let B=()=>{if(y.$op==="create")return "link";if(y.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=x(t,y).roles,S=mapEntries(q,(Q,A)=>{let U=T[Q]?.cardinality;if(!U)throw new Error(`Role ${Q} not found in schema`);if(Array.isArray(A)){if(U==="ONE"){if(A.length>1)throw new Error(`[Error] Role ${Q} is not a MANY relation`);return [Q,A[0].$bzId||A[0]]}return [Q,A.map(P=>P.$bzId||P)]}return [Q,A.$bzId||A]}),w={...E,$thing:y.$thing,$thingType:"relation",$op:B(),...S,$bzId:y.$bzId,[Ce]:"roleField"};$(w);return}if(y.$op==="match"||y.$op==="update"&&Object.keys(I).length>0){let B=0;Object.entries(I).forEach(([T,S])=>{let w=isArray(S)?S:[S],Q=A=>A==="create"||A==="replace"?"link":A;w.forEach(A=>{if(!A)return;let U=Q(A.$op);if(U==="replace")throw new Error("Not supported yet: replace on roleFields");if(U==="unlink"&&B>0)throw B+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let P={...E,$thing:y.$thing,$thingType:"relation",$op:U==="delete"?"unlink":U,[T]:A.$bzId,$bzId:y.$bzId,[Ce]:"roleField"};$(P);});});}}}}}),[d,l]},[n,s]=r(e),i=n.reduce((u,d)=>{if(!d.$bzId)return [...u,d];let l=u.findIndex(f=>f.$bzId===d.$bzId);if(l===-1)return [...u,d];if(u[l].$op==="create"&&d.$op==="match")return u;if(u[l].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...u.slice(0,l),d,...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d},...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="match"||u[l].$op==="match"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d,$op:"update"},...u.slice(l+1)];if(u[l].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(u[l].$filter)===JSON.stringify(d.$filter))return u;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${u[l].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${u[l].$op}. Current: ${d.$op}`)},[]),a=s.reduce((u,d)=>{let l=u.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(l){let f={...l};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=l[$],m=d[$];Array.isArray(g)&&Array.isArray(m)?f[$]=Array.from(new Set([...g,...m])):!Array.isArray(g)&&Array.isArray(m)?g!==void 0?f[$]=Array.from(new Set([g,...m])):f[$]=m:Array.isArray(g)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...g,m]))):g!==null&&m!==null&&g!==void 0&&m!==void 0?f[$]=Array.from(new Set([g,m])):g==null&&(f[$]=m);}),[...u.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...u,d]},[]);i.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&a.filter(d=>d.$bzId===u.$bzId||d.$tempId&&d.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(zr(u))}`)}});let o=[...i,...a],c=new Set(o.filter(u=>u.$tempId).map(u=>u.$tempId)),p=Array.from(c).filter(u=>!o.some(d=>d.$tempId===u&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var Ue={};function re(e){return {enumerable:!0,value:e}}function Jr(e){return {enumerable:!0,writable:!0,value:e}}var oo=()=>!0,Yr=()=>({}),Xr=e=>e,so=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),ao=(e,t,r,[n,s])=>t.call(r,e.call(r,n,s),s),Re=(e,t)=>Object.freeze(Object.create(e,t));function Gr(e,t,r){return e.reduce((n,s)=>function(...i){return r(n,s,this,i)},t)}function Zr(e){return Re(this,{fn:re(e)})}var en={},N=Zr.bind(en);var tn={},kt=Zr.bind(tn);function ut(e,t){return t.filter(r=>e.isPrototypeOf(r))}function rn(e,t,...r){let n=Gr(ut(tn,r).map(i=>i.fn),oo,so),s=Gr(ut(en,r).map(i=>i.fn),Xr,ao);return Re(this,{from:re(e),to:re(t),guards:re(n),reducers:re(s)})}var nn={},on={},j=rn.bind(nn);rn.bind(on,null);function lo(e,t,r){return xt(t,e,r,this.immediates)||e}function sn(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var co={enter:Xr};function se(...e){let t=ut(nn,e),r=ut(on,e),n={final:re(e.length===0),transitions:re(sn(t))};return r.length&&(n.immediates=re(r),n.enter=re(lo)),Re(co,n)}var uo={enter(e,t,r){let n=this.fn.call(t,t.context,r);return qt.isPrototypeOf(n)?Re(an,{machine:re(n),transitions:re(this.transitions)}).enter(e,t,r):(n.then(s=>t.send({type:"done",data:s})).catch(s=>t.send({type:"error",error:s})),e)}},an={enter(e,t,r){if(t.child=fe(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,xt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function V(e,...t){let r=re(sn(t));return qt.isPrototypeOf(e)?Re(an,{machine:re(e),transitions:r}):Re(uo,{fn:re(e),transitions:r})}var qt={get state(){return {name:this.current,value:this.states[this.current]}}};function me(e,t,r=Yr){return typeof e!="string"&&(r=t||Yr,t=e,e=Object.keys(t)[0]),Ue._create&&Ue._create(e,t),Re(qt,{context:re(r),current:re(e),states:re(t)})}function xt(e,t,r,n){let{context:s}=e;for(let{to:i,guards:a,reducers:o}of n)if(a(s,r)){e.context=o.call(e,s,r);let c=t.original||t,p=Re(c,{current:re(i),original:{value:c}});Ue._onEnter&&Ue._onEnter(t,i,e.context,s,r);let u=p.state.value;return e.machine=p,e.onChange(e),u.enter(p,e,r)}}function ho(e,t){let r=t.type||t,{machine:n}=e,{value:s,name:i}=n.state;return s.transitions.has(r)?xt(e,n,t,s.transitions.get(r))||n:(Ue._send&&Ue._send(r,i),n)}var po={send(e){ho(this,e);}};function fe(e,t,r,n){let s=Object.create(po,{machine:Jr(e),context:Jr(e.context(r,n)),onChange:re(t)});return s.send=s.send.bind(s),s.machine=s.machine.state.value.enter(s.machine,s,n),s}var un=(e,t)=>{if(!t)return;let r=$o(t);return mo(r,e.query)},$o=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),mo=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let s=n;Object.keys(s).forEach(i=>{(s[i]===void 0||s[i]===null||isArray(s[i])&&s[i].length===0)&&(t?.returnNulls?s[i]=null:delete s[i]),s[i]===void 0&&delete s[i];}),Object.getOwnPropertySymbols(s).forEach(i=>{delete s[i];}),t?.noMetadata===!0&&Object.keys(s).forEach(i=>{i.startsWith("$")&&delete s[i];});}}));var hn=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:o})=>{if(isObject(o)){let c=o;if(!c.$thing)return;if(c.$thing){let p=x(e,c),{virtualFields:u}=p,d=c[ie];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),f=l.$fields.map($=>$.$path),h=l.$excludedFields;u.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(m=>m.path===$);if(g?.default){let m=Ne({currentThing:c,fieldSchema:g,mandatoryDependencies:!0});c[$]=m;}else if(c[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete c[$];});}}})))(r):void 0;var Ke={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},ye=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let c=Object.keys(a).reduce((p,u)=>{let d=a[u];if(u.startsWith("$")){if(["$or","$and","$not"].includes(u))return {...p,[u]:void 0,[Ke[u]]:ye(d,t,r)};if(u==="$id")return {...p,$id:void 0,[Ke[u]]:{$IN:isArray(d)?d:[d]}};if(u==="$thing")return p;if(u==="$exists")return {...p,$exists:void 0,[Ke[u]]:d};if(u==="$eq")return {...p,$eq:void 0,[Ke[u]]:d};if(u==="$in")return {...p,$in:void 0,[Ke[u]]:d};throw new Error(`Unknown filter operator ${u}`)}let l=t in r.entities?r.entities[t]:r.relations[t],[f,h]=nt(l,u);if(f==="idField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return {...p,"record::id(id)":{$IN:isArray(d)?d:[d]}}}if(f==="dataField")return {...p,[u]:ye(d,t,r)};if(f==="linkField"||f==="roleField"){let g=h[Se].queryPath;return {...p,[g]:ye(d,t,r)}}throw new Error(`Field ${u} not found in schema, Defined in $filter`)},{});return shake(c)});return n?i:i[0]},pe=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,s])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(s)?s.map(o=>pe(o)):[pe(s)];i==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(s))if(n.includes("<-")||n.includes("->")){let i=pe(s);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=pe(s),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=pe(s),a=n.replace("$parent.","");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let i=Object.keys(s);if(i.length===1&&i[0].startsWith("$")){let[a]=i,o=s[a];if(a==="$exists")if(o===!0)r.push(`${n} IS NOT NONE`);else if(o===!1)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${o}`);else {let c=a.replace("$","");if(Array.isArray(o))r.push(`${n} ${c} [${o.map(p=>p===null?"NONE":`'${p}'`).join(", ")}]`);else if(isObject(o)){let p=pe(o);r.push(`${n} ${c} ${p}`);}else r.push(`${n} ${c} ${o===null?"NONE":`'${o}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(s)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${s.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${s===null?"NONE":`'${s}'`}`);}}),r.join(" AND ")},We=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:s}=r;return `${n}${s?" DESC":" ASC"}`}).join(", ")}`;var fn=e=>{let{queries:t,schema:r}=e;return t.map(n=>To({query:n,schema:r}))},To=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push("SELECT");let u=jt({parentQuery:t,queries:s,level:1,schema:r});u&&p.push(u);let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let f=(d.subTypes?[n,...d.subTypes]:[n]).map(h=>ee(h));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(g=>h?.map(m=>`${g}:\u27E8${m}\u27E9`));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(i){let h=ye(i,n,r),$=pe(h);p.push(`WHERE ${$}`);}return c&&p.push(We(c)),typeof o=="number"&&p.push(`LIMIT ${o}`),typeof a=="number"&&p.push(`START ${a}`),p.join(`
104
104
  `)},jt=e=>{let{queries:t,schema:r,level:n,parentQuery:s}=e,i=[],a=s[ie];return i.push(M(`"${a}" as \`$$queryPath\``,n)),i.push(M("record::id(id) as `$id`",n)),i.push(M("record::tb(id) as `$thing`",n)),t.forEach(o=>{let c=wo({query:o,level:n,schema:r});c&&i.push(c);}),i.length===0?null:i.join(`,
105
105
  `)},wo=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?Mo({query:t,level:n}):t.$fieldType==="link"?So({query:t,level:n,schema:r}):t.$fieldType==="role"?Lo({query:t,level:n,schema:r}):null},Mo=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},So=e=>{let{query:t,schema:r,level:n}=e,{$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push(M("(",n));let u=n+1;p.push(M("SELECT",u));let d=jt({parentQuery:t,queries:s,level:u+1,schema:r});d&&p.push(d);let l=t[oe][Se].queryPath;if(p.push(M(`FROM ${l}`,u)),i){let f=ye(i,t.$thing,r),h=pe(f);p.push(`WHERE ${h}`);}return c&&p.push(M(We(c),u)),typeof o=="number"&&p.push(M(`LIMIT ${o}`,u)),typeof a=="number"&&p.push(M(`START ${a}`,u)),p.push(M(`) AS \`${t.$as}\``,n)),p.join(`
106
106
  `)},Lo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let s=[];s.push(M("(",n));let i=n+1;s.push(M("SELECT",i));let a=i+1,o=jt({parentQuery:t,queries:t.$fields,level:a,schema:r});o&&s.push(o);let c=t[oe][Se].queryPath;if(s.push(M(`FROM ${c}`,i)),t.$filter){let p=ye(t.$filter,t.$playedBy.thing,r),u=pe(p);s.push(`WHERE ${u}`);}return s.push(M(`) AS \`${t.$as}\``,n)),s.join(`
@@ -110,7 +110,7 @@ ${o}`}).join(`
110
110
  COMMIT TRANSACTION;
111
111
  `;return n.query?.debugger&&console.log("batchedQuery",s),await t.query(s)};var yn=e=>{let{res:t,queries:r}=e;return t.map((s,i)=>gn(r[i],s))},gn=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return _t(e,t[0])}if(t.length>=1)return t.map(r=>_t(e,r))}else throw new Error("res is unexpectedly not an array")},_t=(e,t)=>{let r={[ie]:t.$$queryPath,$id:t.$id,$thing:hr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(n=>{let s=n.$as,i=t[s];n.$path==="id"&&e.$idNotIncluded||(r[s]=Ro(n,i));}),r},Ro=(e,t)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:r}=e[oe];return e[oe].cardinality==="ONE"&&mn(t,r),mn(t,r)??null}return e.$justId?e.$filterByUnique||e[oe].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[oe].cardinality==="ONE"?_t(e,t[0]):gn(e,t)},mn=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(s=>new Date(s).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(s=>isDate(s)?new Date(s).toISOString():s);return isArray(e)?n:n[0]}return e};var En=e=>{let{queries:t,schema:r}=e;return t.map(n=>Do({query:n,schema:r}))},Do=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=r.entities[n]||r.relations[n];if(!p)throw new Error(`Schema for ${n} not found`);let u=t[ie],d=Bn(u),l=Fn(s.filter(y=>y.$fieldType==="data")),f=bn(s.filter(y=>y.$fieldType==="link"||y.$fieldType==="role"),r),h=[...d,...l,...f].join(`,
112
112
  `),$=Co(t,p),g=i?`WHERE id AND (${pe(ye(i,n,r))})`:"WHERE id",m=c?We(c):"",F=typeof o=="number"?`LIMIT ${o}`:"",b=typeof a=="number"?`START ${a}`:"";return `SELECT ${h} ${$} ${g} ${m} ${F} ${b}`},Co=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>ee(a)),s=(a,o)=>`${a}:\`${o}\``,i=a=>n.flatMap(o=>a.map(c=>s(o,c))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${i([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${i(e.$id)}`;throw new Error("Invalid $id")},Bn=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],Fn=e=>e.map(t=>t.$path==="id"?`record::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),bn=(e,t)=>e.map(r=>{let n=Bn(r[ie]),s=Fn(r.$fields.filter(l=>l.$fieldType==="data")),i=bn(r.$fields.filter(l=>l.$fieldType==="link"||l.$fieldType==="role"),t),a=[...n,...s,...i].join(`,
113
- `),o=`FROM $parent.\`${r[oe].path}\`[*]`,c=r.$filter?`WHERE id AND(${pe(ye(r.$filter,r.$thing,t))})`:"WHERE id",p=r.$sort?We(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${o} ${c} ${p} ${u} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var Ut=j("error","error",N((e,t)=>({...e,error:t.error}))),Io=me("build",{build:V(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return fn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return En({queries:e.bql.queries,schema:e.schema})},j("done","run",N((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Ut),run:V(async e=>$n({client:e.client,queries:he(e.surql.queries),config:e.config}),j("done","parse",N((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Ut),parse:V(async e=>yn({res:he(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),j("done","success",N((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Ut),success:se(),error:se()},e=>e),Ao=async e=>new Promise((t,r)=>{fe(Io,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Tn=async(e,t,r,n)=>Ao({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var ht=e=>{let{$filter:t,$var:r,$thing:n,schema:s,depth:i}=e,a=qo(t,v(s,n)),{$not:o,...c}=a,p=[];if(zt(o)){let d=Wt(o,r,n,s,i,!0);p.push(...d);}else if(o!==void 0)throw new Error("$not must be a PositiveFilter object");let u=Wt(c,r,n,s,i,!1);return p.push(...u),p.join(`
113
+ `),o=`FROM $parent.\`${r[oe].path}\`[*]`,c=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${pe(ye(r.$filter,r.$thing,t))})`:"WHERE id",p=r.$sort?We(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${o} ${c} ${p} ${u} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var Ut=j("error","error",N((e,t)=>({...e,error:t.error}))),Io=me("build",{build:V(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return fn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return En({queries:e.bql.queries,schema:e.schema})},j("done","run",N((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Ut),run:V(async e=>$n({client:e.client,queries:he(e.surql.queries),config:e.config}),j("done","parse",N((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Ut),parse:V(async e=>yn({res:he(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),j("done","success",N((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Ut),success:se(),error:se()},e=>e),Ao=async e=>new Promise((t,r)=>{fe(Io,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Tn=async(e,t,r,n)=>Ao({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var ht=e=>{let{$filter:t,$var:r,$thing:n,schema:s,depth:i}=e,a=qo(t,v(s,n)),{$not:o,...c}=a,p=[];if(zt(o)){let d=Wt(o,r,n,s,i,!0);p.push(...d);}else if(o!==void 0)throw new Error("$not must be a PositiveFilter object");let u=Wt(c,r,n,s,i,!1);return p.push(...u),p.join(`
114
114
  `)},Wt=(e,t,r,n,s,i)=>{let a=v(n,r),o=[];for(let[c,p]of Object.entries(e)){if(c.startsWith("$")){let l=c.toLowerCase();if(l==="$and"||l==="$or"){let h=(isArray(p)?p:[p]).map(g=>{if(zt(g))return Wt(g,t,r,n,s+1,i).join(`
115
115
  `);throw new Error(`Invalid subfilter in ${l}: ${JSON.stringify(g)}`)}),$=h.join(l==="$and"?`
116
116
  `:" } or { ");l==="$or"&&h.length>1?o.push(M(`{ ${$} };`,s)):o.push(M($,s));continue}continue}if(a.dataFields?.find(l=>l.dbPath===c||l.path===c)){let l=Oo(c,p,t,s,i);o.push(...l);continue}let d=a.linkFields?.find(l=>l.path===c);if(d){let l=Po(d,p,t,n,s,i);o.push(...l);continue}if(a.thingType==="relation"){let l=a.roles[c];if(l){let f=ko(l,p,t,r,n,s,i);o.push(...f);continue}}throw new Error(`"${r}" does not have property "${c}"`)}return o},Oo=(e,t,r,n,s)=>{let i=[];if(isObject(t)&&!isArray(t))for(let[a,o]of Object.entries(t)){let c=a.toLowerCase(),p="";switch(c){case"$eq":p=`$${r} has ${e} ${$e(o)};`;break;case"$ne":p=`not { $${r} has ${e} ${$e(o)}; };`;break;case"$in":{if(!isArray(o))throw new Error("Value for $in operator must be an array");let u=o.map(d=>`$${r} has ${e} ${$e(d)};`);p=Ye(u),s&&(p=`not { ${p} };`);break}case"$nin":if(!isArray(o))throw new Error("Value for $nin operator must be an array");for(let u of o){let d=`not { $${r} has ${e} ${$e(u)}; };`;i.push(M(d,n));}continue;case"$exists":if(o===!0)p=`$${r} has ${e} $${e}_${v4()};`;else if(o===!1)p=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${o}`);break;default:throw new Error(`Unsupported operator "${a}" for data field "${e}"`)}s&&(p=`not { ${p} };`),i.push(M(p,n));}else if(isArray(t)){let a=t.map(c=>`$${r} has ${e} ${$e(c)};`),o=Ye(a);o&&(s&&(o=`not { ${o} };`),i.push(M(o,n)));}else {let a=`$${r} has ${e} ${$e(t)};`;s&&(a=`not { ${a} };`),i.push(M(a,n));}return i},Po=(e,t,r,n,s,i)=>{let a=[],[o]=e.oppositeLinkFieldsPlayedBy,p=v(n,o.thing).idFields?.[0];if(!p)throw new Error(`"${o.thing}" does not have an id field`);let u=`${o.thing}_${v4()}`,d="";if(e.target==="relation")if(t===null)d=i?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${$e(f)};`);d=Ye(l),i&&(d=`not { ${d} };`);}else d=`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${$e(t)};`,i&&(d=`not { ${d} };`);else if(t===null)d=i?`$${u} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`:`not { $${u} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(f=>`$${u} isa ${o.thing}, has ${p} ${$e(f)}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`);d=Ye(l),i&&(d=`not { ${d} };`);}else d=`$${u} isa ${o.thing}, has ${p} ${$e(t)}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`,i&&(d=`not { ${d} };`);return a.push(M(d,s)),a},ko=(e,t,r,n,s,i,a)=>{let o=[],[c]=e.playedBy||[],u=v(s,c.thing).idFields?.[0];if(!u)throw new Error(`"${c.thing}" does not have an id field`);let d=`${c.thing}_${v4()}`,l=v4(),f=`${r}_${l}`;o.push(M(`$${f} isa ${n};`,i));let h="";if(t===null)h=`$${f} (${c.plays}: ${d});`,a?o.push(M(h,i)):o.push(M(`not { ${h} };`,i));else if(isArray(t)){let $=t.map(g=>`$${d} isa ${c.thing}, has ${u} ${$e(g)}; $${f} (${c.plays}: $${d});`);h=Ye($),a?o.push(M(`not { ${h} };`,i)):o.push(M(h,i));}else h=`$${d} isa ${c.thing}, has ${u} ${$e(t)}; $${f} (${c.plays}: $${d});`,a?o.push(M(`not { ${h} };`,i)):o.push(M(h,i));return o.push(M(`$${r} is $${f};`,i)),o},Ye=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},$e=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("|")})$"`:$e(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},qo=(e,t)=>{let r={};if(t.dataFields?.forEach(a=>{a.path!==a.dbPath&&(r[a.path]=a.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...s}=e,i=wn(s,r);return n&&zt(n)&&(i.$not=wn(n,r)),i},wn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,s])=>{let i=t[n]||n;r[i]=s;}),r},zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Vt="___",Sn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>xo({query:n,schema:r}))},xo=e=>{let{query:t,schema:r}=e,{$path:n,$thing:s,$filter:i,$fields:a,$sort:o,$offset:c,$limit:p,$id:u}=t;if(!n)throw new Error("Path is not defined");let d=[],l=t[ie];if(d.push("match"),d.push(`$${n} isa ${s};`),i||u){let $=it(r,t),g={...i,...u?{[$]:u}:{}},m=ht({$filter:g,$var:n,$thing:s,schema:r,depth:0});d.push(`
@@ -129,7 +129,7 @@ limit ${p};`),d.join(`
129
129
  LET $LOGS = SELECT * FROM LOG;
130
130
  RETURN $LOGS;
131
131
  COMMIT TRANSACTION;
132
- `;r.mutation?.debugger&&console.log("batchedMutation",n);try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Xn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Yn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Yn(s,r)})},Yn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(s,i=>!i.startsWith("$")):s};var Fs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),bs=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},Ts=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},ar=j("error","error",N((e,t)=>({...e,error:t.error}))),ws=me("buildMutation",{buildMutation:V(async e=>Kn(e.bql.flat,e.schema),j("done","runMutation",N(bs)),ar),runMutation:V(async e=>vn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config),j("done","parseMutation",N(Ts)),ar),parseMutation:V(async e=>Xn({res:e.surql.res,config:e.config,schema:e.schema}),j("done","success",N(Fs)),ar),success:se(),error:se()},e=>e),Ms=async e=>new Promise((t,r)=>{fe(ws,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ei=async(e,t,r,n,s,i)=>Ms({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ri=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=de(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...ce(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[tt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=ce(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(b=>n(b,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let F=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([b,y])=>{let R=F.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:b});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(b=>n(b,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(b=>b.path===g),F=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([b,y])=>{F.filter(L=>y.includes(L.$op)).forEach(L=>{let D=ce(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:b});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{F.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ni=se,Ve=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ss=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ls=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Qs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Rs=async e=>Object.keys(e.bql.enriched).length?Pt(e.bql.enriched,e.schema,e.config):Pt(e.bql.raw,e.schema,e.config),Ds=async e=>In(e.bql.enriched,e.schema,e.config,e.handles),Cs=async e=>qn(e.bql.enriched,e.schema,e.config,e.handles),Is=async e=>vr(e.bql.enriched,e.schema),As=async e=>ri(e.bql.enriched,e.schema),Os=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},Ps=e=>je(e.bql.enriched),Pe=j("error","error",N((e,t)=>({...e,error:t.error}))),ks=me("stringify",{stringify:V(async e=>An(e.bql.raw,e.schema),j("done","enrich",N(Ve)),Pe),enrich:V(Rs,j("done","preQuery",kt(Os),N(Ve)),j("done","parseBQL",N(Ve)),Pe),preQuery:V(Ds,j("done","preHookDependencies",kt(Ps),N(Ve)),j("done","parseBQL",N(Ve)),Pe),preHookDependencies:V(Cs,j("done","enrich",N(Ve)),Pe),parseBQL:V(Is,j("done","flattenBQL",N(Ss)),Pe),flattenBQL:V(As,j("done","adapter",N(Ls)),Pe),adapter:V(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Hn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ei(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",N(Qs)),Pe),success:ni(),error:ni()},e=>e),qs=async e=>new Promise((t,r)=>{fe(ks,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ii=async(e,t,r,n)=>qs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var xs=5e3,Ns=3e5,js=2e3,_s=1e3,Us=6e4,lr=class{db;url;username;password;namespace;database;isConnecting;reconnectInterval;constructor(t){this.db=new oi,this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database,this.isConnecting=!1,this.reconnectInterval=null;}async _connect(){if(this.isConnecting||this.db.status===ConnectionStatus.Connecting||this.db.status===ConnectionStatus.Connected)return;this.isConnecting=!0,this.db=new oi;let t=Math.max(_s,1);for(;;){let r=!1;try{await this.db.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1});break}catch{if(r=!0,this.close(),this.isClosed)break}r&&(await Ws((1+Math.random()*.1)*t),t=Math.min(2*t,Us),await this._connect());}this.isConnecting=!1;}async connect(){return this.isClosed&&(this.reconnectInterval=setInterval(()=>this._connect(),js)),this._connect()}close(){this.reconnectInterval!==null&&(clearInterval(this.reconnectInterval),this.reconnectInterval=null,this.db.close());}get isClosed(){return this.reconnectInterval===null}async run(t){return new Promise((r,n)=>{let s=setTimeout(()=>{this.close(),this.connect(),n(new Error("Timeout"));},Ns);this.connect().then(()=>{t(this.db).then(r).catch(n).finally(()=>{clearTimeout(s);});}).catch(n);})}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}},Ws=async e=>new Promise(t=>{setTimeout(t,e);}),Bt=class{queue;connections;constructor(t){let{totalConnections:r,...n}=t;this.queue=[],this.connections=new Array(r).fill(0).map(()=>{let s=new lr(n);return s.connect(),s});}async dequeue(){if(this.queue.length===0||this.connections.length===0)return;let t=this.queue[0];if(this.queue=this.queue.slice(1),t.timeout()){t.cb(new Error("Timeout"),void 0),this.dequeue();return}let r=this.connections.pop();try{t.cb(void 0,r);}catch(n){t.cb(n,void 0);}finally{this.connections.push(r),this.dequeue();}}async run(t){return new Promise((r,n)=>{let s=!1,i=setTimeout(()=>{s=!0,n(new Error("Timeout"));},xs);this.queue.push({cb:(a,o)=>{clearTimeout(i),t(a,o).then(c=>r(c)).catch(c=>n(c));},timeout:()=>s}),this.dequeue();})}async query(...t){return this.run((r,n)=>{if(n)return n.query(...t);throw r})}async query_raw(...t){return this.run((r,n)=>{if(n)return n.query_raw(...t);throw r})}};enableMapSet();var cr=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let s=new Bt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName,totalConnections:100});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Mr(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await yr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...bt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...bt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(ii)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Ku=cr;//! Todo: delete when this works with the new $thing and $thingType fields
132
+ `;r.mutation?.debugger&&console.log("batchedMutation",n);try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Xn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Yn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Yn(s,r)})},Yn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(s,i=>!i.startsWith("$")):s};var Fs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),bs=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},Ts=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},ar=j("error","error",N((e,t)=>({...e,error:t.error}))),ws=me("buildMutation",{buildMutation:V(async e=>Kn(e.bql.flat,e.schema),j("done","runMutation",N(bs)),ar),runMutation:V(async e=>vn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config),j("done","parseMutation",N(Ts)),ar),parseMutation:V(async e=>Xn({res:e.surql.res,config:e.config,schema:e.schema}),j("done","success",N(Fs)),ar),success:se(),error:se()},e=>e),Ms=async e=>new Promise((t,r)=>{fe(ws,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ei=async(e,t,r,n,s,i)=>Ms({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ri=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=de(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...ce(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[tt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=ce(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(b=>n(b,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let F=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([b,y])=>{let R=F.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:b});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(b=>n(b,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(b=>b.path===g),F=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([b,y])=>{F.filter(L=>y.includes(L.$op)).forEach(L=>{let D=ce(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:b});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{F.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ni=se,Ve=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ss=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ls=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Qs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Rs=async e=>Object.keys(e.bql.enriched).length?Pt(e.bql.enriched,e.schema,e.config):Pt(e.bql.raw,e.schema,e.config),Ds=async e=>In(e.bql.enriched,e.schema,e.config,e.handles),Cs=async e=>qn(e.bql.enriched,e.schema,e.config,e.handles),Is=async e=>vr(e.bql.enriched,e.schema),As=async e=>ri(e.bql.enriched,e.schema),Os=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},Ps=e=>je(e.bql.enriched),Pe=j("error","error",N((e,t)=>({...e,error:t.error}))),ks=me("stringify",{stringify:V(async e=>An(e.bql.raw,e.schema),j("done","enrich",N(Ve)),Pe),enrich:V(Rs,j("done","preQuery",kt(Os),N(Ve)),j("done","parseBQL",N(Ve)),Pe),preQuery:V(Ds,j("done","preHookDependencies",kt(Ps),N(Ve)),j("done","parseBQL",N(Ve)),Pe),preHookDependencies:V(Cs,j("done","enrich",N(Ve)),Pe),parseBQL:V(Is,j("done","flattenBQL",N(Ss)),Pe),flattenBQL:V(As,j("done","adapter",N(Ls)),Pe),adapter:V(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Hn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ei(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",N(Qs)),Pe),success:ni(),error:ni()},e=>e),qs=async e=>new Promise((t,r)=>{fe(ks,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ii=async(e,t,r,n)=>qs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var xs=5e3,Ns=18e4,js=2e3,_s=1e3,Us=6e4,lr=class{db;url;username;password;namespace;database;isConnecting;reconnectInterval;constructor(t){this.db=new oi,this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database,this.isConnecting=!1,this.reconnectInterval=null;}async _connect(){if(this.isConnecting||this.db.status===ConnectionStatus.Connecting||this.db.status===ConnectionStatus.Connected)return;this.isConnecting=!0,this.db=new oi;let t=Math.max(_s,1);for(;;){let r=!1;try{await this.db.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1});break}catch{if(r=!0,await this.close(),this.isClosed)break}r&&(await Ws((1+Math.random()*.1)*t),t=Math.min(2*t,Us),await this._connect());}this.isConnecting=!1;}async connect(){return this.isClosed&&(this.reconnectInterval=setInterval(()=>this._connect(),js)),this._connect()}async close(){if(this.reconnectInterval!==null){clearInterval(this.reconnectInterval),this.reconnectInterval=null;try{await this.db.close();}catch(t){console.error("Trying to close an already closed connection:",t);}}}get isClosed(){return this.reconnectInterval===null}async run(t){return new Promise((r,n)=>{let s=setTimeout(()=>{this.close(),this.connect(),n(new Error("Timeout"));},Ns);this.connect().then(()=>{t(this.db).then(r).catch(n).finally(()=>{clearTimeout(s);});}).catch(n);})}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}},Ws=async e=>new Promise(t=>{setTimeout(t,e);}),Bt=class{queue;connections;constructor(t){let{totalConnections:r,...n}=t;this.queue=[],this.connections=new Array(r).fill(0).map(()=>{let s=new lr(n);return s.connect(),s});}async dequeue(){if(this.queue.length===0||this.connections.length===0)return;let t=this.queue[0];if(this.queue=this.queue.slice(1),t.timeout()){t.cb(new Error("Timeout"),void 0),this.dequeue();return}let r=this.connections.pop();try{t.cb(void 0,r);}catch(n){t.cb(n,void 0);}finally{this.connections.push(r),this.dequeue();}}async run(t){return new Promise((r,n)=>{let s=!1,i=setTimeout(()=>{s=!0,n(new Error("Timeout"));},xs);this.queue.push({cb:(a,o)=>{clearTimeout(i),t(a,o).then(c=>r(c)).catch(c=>n(c));},timeout:()=>s}),this.dequeue();})}async query(...t){return this.run((r,n)=>{if(n)return n.query(...t);throw r})}async query_raw(...t){return this.run((r,n)=>{if(n)return n.query_raw(...t);throw r})}};enableMapSet();var cr=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let s=new Bt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName,totalConnections:8});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Mr(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await yr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...bt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...bt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(ii)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Ku=cr;//! Todo: delete when this works with the new $thing and $thingType fields
133
133
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
134
134
  //! Todo: Sandbox the function in computeFunction()
135
135
  //! reads all the insertions and gets the first match. This means each id must be unique