@blitznocode/blitz-orm 0.10.31 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -661
- package/dist/index.d.mts +26 -6
- package/dist/index.mjs +121 -44
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -5
- package/readme.md +50 -11
package/dist/index.mjs
CHANGED
|
@@ -1,61 +1,138 @@
|
|
|
1
|
-
import { isObject, isArray,
|
|
1
|
+
import { isObject, isArray, tryit, parallel, shake, clone, mapEntries, listify, pick, isDate, isSymbol } from 'radash';
|
|
2
2
|
import { TypeDBOptions, TransactionType, SessionType, TypeDB, TypeDBCredential } from 'typedb-driver';
|
|
3
3
|
import { Surreal } from 'surrealdb.js';
|
|
4
4
|
import { enableMapSet, produce, isDraft, current } from 'immer';
|
|
5
5
|
import { traverse, getNodeByPath } from 'object-traversal';
|
|
6
|
-
import { nanoid } from 'nanoid';
|
|
7
|
-
import { v4 } from 'uuid';
|
|
6
|
+
import { nanoid, customAlphabet } from 'nanoid';
|
|
8
7
|
import { isSet } from 'util/types';
|
|
9
8
|
import 'acorn';
|
|
9
|
+
import { v4 } from 'uuid';
|
|
10
|
+
|
|
11
|
+
var $t={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Zn=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:o,contentType:i}=n,a=`${o}-${i}`;r.has(a)||(r.set(a,!0),t.push(n));}),t},Xn=(e="default",t)=>{let r="",n=[];r+=`
|
|
12
|
+
`,Object.keys(t.entities).filter(s=>t.entities[s].defaultDBConnector.id===e).forEach(s=>{let u=t.entities[s],{dataFields:$,linkFields:c,name:d}=u;if(r+=`${d} sub ${"extends"in u?u.extends:"entity"},
|
|
13
|
+
`,$&&$.length>0&&$.forEach(l=>{l.inherited||(l.isIdField?r+=` owns ${l.dbPath} @key,
|
|
14
|
+
`:r+=` owns ${l.dbPath},
|
|
15
|
+
`,n.push({dbPath:l.dbPath,contentType:l.contentType}));}),c&&c.length>0){let l=[];c.forEach(p=>{let{relation:h,plays:f,inherited:y}=p;if(y)return;!t.relations[h].roles[f].inherited&&!l.includes(`${h}:${f}`)&&(r+=` plays ${h}:${f},
|
|
16
|
+
`,l.push(`${h}:${f}`));});}r=r.replace(/,\s*$/,`;
|
|
17
|
+
`),r+=`
|
|
18
|
+
`;}),Object.keys(t.relations).filter(s=>t.relations[s].defaultDBConnector.id===e).forEach(s=>{let u=t.relations[s],{dataFields:$,roles:c,name:d,linkFields:l}=u;if(r+=`${d} sub ${"extends"in u?u.extends:"relation"},
|
|
19
|
+
`,$&&$.length>0&&$.forEach(p=>{p.inherited||(p.isIdField?r+=` owns ${p.dbPath} @key,
|
|
20
|
+
`:r+=` owns ${p.dbPath},
|
|
21
|
+
`,n.push({dbPath:p.dbPath,contentType:p.contentType}));}),c&&Object.keys(c).forEach(p=>{c[p].inherited||(r+=` relates ${p},
|
|
22
|
+
`);}),l&&l.length>0){let p=[];l.forEach(h=>{let{plays:f,relation:y}=h;!t.relations[y].roles[f].inherited&&!h.inherited&&!p.includes(`${y}:${f}`)&&(r+=` plays ${h.relation}:${f},
|
|
23
|
+
`,p.push(`${y}:${f}`));});}r=r.replace(/,\s*$/,`;
|
|
24
|
+
`),r+=`
|
|
25
|
+
`;});let o=`define
|
|
26
|
+
|
|
27
|
+
`;return Zn(n).forEach(s=>{if(s.contentType==="TEXT"||s.contentType==="ID"||s.contentType==="JSON")o+=`${s.dbPath} sub attribute, value string;
|
|
28
|
+
`;else if(s.contentType==="EMAIL")o+=`${s.dbPath} sub attribute, value string,
|
|
29
|
+
`,o+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
|
|
30
|
+
`;else if(s.contentType==="DATE")o+=`${s.dbPath} sub attribute, value datetime;
|
|
31
|
+
`;else if(s.contentType==="BOOLEAN")o+=`${s.dbPath} sub attribute, value boolean;
|
|
32
|
+
`;else if(s.contentType==="NUMBER")o+=`${s.dbPath} sub attribute, value long;
|
|
33
|
+
`;else if(s.contentType==="FLEX")o+=`${s.dbPath} sub flexAttribute;
|
|
34
|
+
`;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${s.contentType}" is not implemented`)}),`${o}
|
|
35
|
+
|
|
36
|
+
${r}
|
|
37
|
+
#Tools, reserved for every schema using borm
|
|
10
38
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
`);
|
|
23
|
-
|
|
24
|
-
`),
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
`,
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
${y}`})(),n=e.dbConnectors[0].id,c=r.typeDB.get(n)?.session,a=r.typeDB.get(n)?.client;if(!c){console.log("Session Status: ","NO SESSION");return}await c.close();let[{dbName:h}]=e.dbConnectors;await(await a.databases.get(h)).delete(),await a.databases.create(h);let l=await a.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await l.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let s=await l.transaction(TransactionType.READ);(await(await s.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await s.close();};var te=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Se=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ae=Symbol.for("dbNode"),dt=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),me=Symbol.for("suqlMetadata");var Yt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Gt=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],c=`<-\`${t}_${e.plays}\`<-(\`${n.join("`,`")}\`)`;if(e.target==="relation"){if(i==="edges")return c;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[a]=e.oppositeLinkFieldsPlayedBy,h=r.entities[a.thing]?.subTypes||r.relations[a.thing]?.subTypes||[],p=[a.thing,...h],l=`->\`${t}_${a.plays}\`->(\`${p.join("`,`")}\`)`;return i==="edges"?`${c}${l}`:i==="refs"?`$parent.\`${a.plays}\``:`${c}${l}`}else throw new Error("Unsupported linkField target")};var tr=(e,t,r)=>r?t:`${e}\xB7${t}`;var nr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],We=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),ir=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:c,value:a,meta:h})=>{if(h.depth===2&&(c&&(a.dataFields=a.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:"dbPath"in p?p.dbPath:tr(c,p.path,p.shared)}))),a.extends)){if(!a.defaultDBConnector.as)throw new Error(`[Schema] ${c} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${h.nodePath}`);let p=n.entities[a.extends]||n.relations[a.extends],l=[a.extends,...p.allExtends||[]];if(a.allExtends=l,l.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[c,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[c,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${c} is extending a thing that does not exist in the schema: ${d}`)}),a.idFields=p.idFields?Array.from(new Set((a.idFields||[]).concat(p.idFields))):a.idFields,a.dataFields=p.dataFields?(a.dataFields||[]).concat(p.dataFields.map(d=>{let s=a.extends,f=e.entities[s]||e.relations[s];for(;!f.dataFields?.find(u=>u.path===d.path);)s="extends"in f?f.extends:void 0,f=e.entities[s]||e.relations[s];return {...d,dbPath:"dbPath"in d?d.dbPath:tr(s,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||a.extends}}})):a.dataFields,"roles"in p){let d=a,s=p;if(s.roles){let f=mapEntries(s.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||a.extends}}]);d.roles={...d.roles||{},...f};}}a.linkFields=p.linkFields?(a.linkFields||[]).concat(p.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||a.extends}}))):a.linkFields,p?.hooks?.pre&&(a.hooks=a.hooks||{},a.hooks.pre=a.hooks.pre||[],a.hooks.pre=[...p?.hooks?.pre||[],...a?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:c,meta:a})=>{if(n==="linkFields"){let p=(()=>{if(!a.nodePath)throw new Error("No path");let[d,s]=a.nodePath.split(".");return {thing:s,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),l=Array.isArray(c)?c.map(d=>({...d,...p})):[{...c,...p}];r.push(...l);}}),produce(i,n=>traverse(n,({value:c,key:a,meta:h})=>{if(h.depth===2&&c.idFields&&!c.id){c.name=a;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};c.thingType=p();let l=Object.keys(t).find(d=>t[d]?.get(c.defaultDBConnector.id));if(c.db=l,c.dbContext=Yt[l],c.dbProviderConfig=l==="surrealDB"?t[l]?.get(c.defaultDBConnector.id)?.providerConfig:void 0,c.computedFields=[],c.virtualFields=[],c.requiredFields=[],c.enumFields=[],c.fnValidatedFields=[],"roles"in c&&Object.entries(c.roles).forEach(([s,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===a&&w.plays===s)||[];f.playedBy=u,f.path=s;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||c.name;$.length>1&&console.warn(`Not supported yet: Role ${s} in ${c.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let S=G(e,w)?.subTypes||[];return [w,...S]}),B=()=>{if(c.dbProviderConfig.linkMode==="edges")return `->\`${y}_${s}\`->(\`${m.join("`,`")}\`)`;if(c.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.\`${s}\``;if(f.cardinality==="ONE")return `$parent.[\`${s}\`]`}throw new Error("Unsupported linkMode")};if(c.db==="surrealDB"){let w=B();f[me]={queryPath:w};}}),"linkFields"in c&&c.linkFields){let d=c;d.linkFields?.forEach(s=>{s.fieldType="linkField";let f=i.relations[s.relation];if(!s.isVirtual){if(!f)throw new Error(`The relation ${s.relation} does not exist in the schema`);if(f.roles?.[s.plays]===void 0)throw new Error(`The role ${s.plays} is not defined in the relation ${s.relation} (linkField: ${s.path})`)}if(s.target==="relation"){if(s.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${s.path}. Path:${h.nodePath}."`);s.$things=[s.relation],s.oppositeLinkFieldsPlayedBy=[{plays:s.path,thing:s.relation,thingType:"relation"}];}if(s.target==="role"){let u=r.filter($=>$.relation===s.relation&&$.plays!==s.plays)||[];if(s.oppositeLinkFieldsPlayedBy=u,s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),s.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${s.path}. Path:${h.nodePath}."`);s.$things=s.oppositeLinkFieldsPlayedBy.map($=>$.thing),s.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${s.path} in ${d.name} has multiple candidates ${s.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(c.db==="surrealDB"){let u=f?.roles?.[s.plays][$e]?.inheritanceOrigin??s.relation,$=Gt({linkField:s,originalRelation:u,withExtensionsSchema:i,linkMode:c.dbProviderConfig.linkMode});s[me]={queryPath:$};}});}}if(c&&typeof c=="object"&&"playedBy"in c){let p=[...new Set(c.playedBy.map(l=>l.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${a}, path:${h.nodePath}, played by: ${p.join(", ")}`),c.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${a}, path:${h.nodePath}`)}if(h.depth===4){let[p,l]=h.nodePath?.split(".")||[],d=n[p][l];!isArray(c)&&typeof c=="object"&&(c.validations&&(c.validations.required&&d.requiredFields.push(c.path),c.validations.enum&&d.enumFields.push(c.path),c.validations.fn&&d.fnValidatedFields.push(c.path)),c.default?c.isVirtual?d.virtualFields.push(c.path):d.computedFields.push(c.path):c.isVirtual&&d.virtualFields.push(c.path));}}))},G=(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`)},q=(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)}`)},Ie=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ke=(e,t)=>{let r=q(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},or=(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")},pt=(e,t,r)=>{let i=q(e,t),o=i.linkFields?.find(a=>a.path===r);if(o)return o;let n=i.dataFields?.find(a=>a.path===r);if(n)return n;let c="roles"in i?i.roles?.[r]:void 0;if(c)return c;throw new Error(`Field ${r} not found in schema`)},ft=(e,t,r)=>pt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],a=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],l=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],d=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!a.includes(u)).filter(u=>u),s=t.$filter?We(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?We(t.$filter,(u,$)=>l.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:d,...p.length?{localFilters:s}:{},...l.length?{nestedFilters:f}:{}}};var sr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ar=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},Fe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ue=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=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(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},T=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var ke=(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 cr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=ke(t,r),[n]=o,c=e.$op==="create"?"link":"replace",a=n.thing,h=n.thingType,p={$op:c,$thing:a,$thingType:h},l=i.filter(s=>s.startsWith("_:")),d=i.filter(s=>!s.startsWith("_:"));l.length&&!d.length?e[t]=l.map(s=>({...p,$tempId:s,$bzId:s})):l.length&&d.length?e[t]=[...l.map(s=>({...p,$tempId:s,$bzId:s})),{...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(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=q(r,t),{usedDataFields:o}=ue(i,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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Je=(e,t,r)=>{let i=q(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var hr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Je(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:or(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ve=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var ur=(e,t,r)=>{if(ve("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(q(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((c,a)=>({...pe(n),$id:c,$bzId:`${n.$bzId}_${a}`,...Fe(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var fr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let c=ke(t,r),[a]=c,h=Je(e,{...n,$thing:a.thing,$thingType:a.thingType},i),l=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${a.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${a.thing}_${nanoid()}`:`SM_${nanoid()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:a.thing,$thingType:a.thingType,$op:h,$bzId:l}});e[t]=isArray(e[t])?o:o[0];};var zn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Vn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$r=e=>{let r=e.toString().replace(zn,"").trim().split("=>")[0].split("{")[0].replace(Vn,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Oe=({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:o}=t.default,c=$r(o).filter(a=>!(a in e));if(c.length)throw new Error(`Virtual field: Missing arguments ${c.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var mr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=q(r,o),{unidentifiedFields:c}=ue(n,o),{computedFields:a,virtualFields:h}=n,p=listify(o,(s,f)=>f!==void 0?s:void 0),l=p.filter(s=>h?.includes(s));if(l.length>0)throw new Error(`Virtual fields can't be sent to DB: "${l.join(",")}"`);if(a.filter(s=>!p.includes(s)).forEach(s=>{let f=n.dataFields?.find(B=>B.path===s),$=n.linkFields?.find(B=>B.path===s)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?nr(n.roles,(B,w)=>B===s):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${s}`);if(o.$op==="create"&&!o[s]){let B=Oe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[s]=B;}}),c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(o)}`)});};var Ye=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let i=`on${sr(e.$op)}`;return r.pre.filter(c=>!c.triggers||c.triggers[i]?.()).flatMap(c=>c.actions)}return []};var gr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:c,enumFields:a,fnValidatedFields:h,dataFields:p}=q(r,n);if("$op"in n&&n.$op==="create"&&c.forEach(l=>{if(!(l in n))throw new Error(`[Validations] Required field "${l}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&a.forEach(l=>{if(l in n){let d=p?.find(s=>s.path===l)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${l}" is missing enum options.`);if(isArray(n[l]))n[l].some(s=>{if(!d.includes(s))throw new Error(`[Validations] Option "${s}" is not a valid option for field "${l}".`)});else if(d&&!d.includes(n[l]))throw new Error(`[Validations] Option "${n[l]}" is not a valid option for field "${l}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(l=>{if(l in n)try{let d=p?.find(s=>s.path===l)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[l]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${l}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let l=n.$thing,d=n,s=clone(pe(e)),f=clone(pe(d)),u=i.mutation?.context||{},$=clone(pe(n[Ae]||{}));Ye(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,s,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${l}] ${B.message}`)}}});}}});};var Br=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ue(n)){if(n.$fields||n[dt])return n;let c=Ye(n,r).filter(d=>d.type==="transform"),a=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},l=clone(pe(n[Ae]||n.$dbNode));return c.forEach(d=>{let s=d.fn(h,a,p,l||{});Object.keys(s).length!==0&&(n={...h,...s,...Fe(n),[dt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Fr=(e,t,r)=>{let i=ke(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(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"&&Pe(e[t]))return !0}return !1};var ei=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ve("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")},ti=(e,t)=>{},Et=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,c=>traverse(c,({value:a,parent:h,key:p,meta:l})=>{if(!(!h||!p)&&isObject(a)){let d=l.nodePath?.split(".")||[];if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let u=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let s=a,f=d.includes("$filter");Object.keys(s).forEach(u=>{if(ei(s,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?pt(t,s,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return ti();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(s[u]===null?Fr(s,u,$):cr(s,u,$)),$.fieldType==="rootField"){if(!("$root"in s))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);hr(s,t);}let y=isArray(s[u])?s[u]:[s[u]],m=d.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&s.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$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)&&fr(s,u,$,t),ur(s,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&mr(s,u,t),(isArray(s[u])?s[u]:[s[u]]).forEach(w=>{let g=q(t,w),{unidentifiedFields:S,usedLinkFields:C,usedFields:A,fields:O}=ue(g,w);if(A.forEach(x=>{if(!O.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(a)}`);if(C.length>1){let x=g.linkFields?.filter(W=>C.includes(W.path));x?.some((W,le)=>x.some((K,D)=>{if(le!==D&&W.target!==K.target&&W.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.")}));}}),o||(Br(s,u,t,r),gr(s,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ge=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var br=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:i}=await Ge(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,c=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let a=c&&o.query.insert(c),h=a?await a.collect():void 0;return await o.commit(),{insertions:h}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await o.close();}};var wr=async(e,t,r,i,o)=>{let n=[...t,...r],c=n.map(a=>{let h=e.insertions?.find(d=>d.get(`${a.$bzId}`))?.get(`${a.$bzId}`),p=a.$thing||a.$relation||a.$entity,l=p?G(i,p):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!h&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let d=h?.asThing().iid,s=Object.entries(a).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(l?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(a.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return s;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:d,...a,...s,[a.path]:a.$id,...f}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(c)};var Mr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Lr=async(e,t)=>{let r=l=>{let d=[],s=[],f=m=>{if(m.$id)return m.$id;let B=q(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(O=>O.path===g),C=Oe({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),A=m[g]||m.$id||C;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(s.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B),s.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);s.push({...m,$id:B});return}s.push(m);};return traverse(l,({value:m,parent:B,meta:w})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let S=q(t,g),{dataFields:C,roleFields:A,linkFields:O,usedFields:x}=ue(S,g),W=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=x.filter(E=>C?.includes(E)),F=x.filter(E=>A?.includes(E)),Q=x.filter(E=>O?.includes(E));if(D.length>0)return "update";if(F.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},le={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,C||[""])),$op:W(),$bzId:g.$bzId};u(le);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let D=K.relation===g.$thing,F=D?g.$bzId:`LT_${v4()}`,E=ar(l,B,w).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return D?"match":"delete";if(g.$op==="unlink")return D?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return D?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=q(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let k={$bzId:F,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...D?{}:{[K.path]:g.$bzId},[K.plays]:E,[Be]:K,[Se]:"linkField"};$(k),(g.$op==="unlink"||b()==="unlink")&&D&&$({$thing:K.relation,$thingType:"relation",$bzId:F,$op:"match",[K.plays]:E,[Be]:K,[Se]:"linkField"});}if(g.$thingType==="relation"){let D=We(g,(E,b)=>A.includes(E)),F=mapEntries(D,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),Q=We(m,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(D).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},b=q(t,g).roles,M=mapEntries(F,(k,L)=>{let N=b[k]?.cardinality;if(!N)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(L)){if(N==="ONE"){if(L.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,L[0].$bzId||L[0]]}return [k,L.map(J=>J.$bzId||J)]}return [k,L.$bzId||L]}),R={...Q,$thing:g.$thing,$thingType:"relation",$op:E(),...M,$bzId:g.$bzId,[Se]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){let E=0;Object.entries(D).forEach(([b,M])=>{let R=isArray(M)?M:[M],k=L=>L==="create"||L==="replace"?"link":L;R.forEach(L=>{if(!L)return;let N=k(L.$op);if(N==="replace")throw new Error("Not supported yet: replace on roleFields");if(N==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:N==="delete"?"unlink":N,[b]:L.$bzId,$bzId:g.$bzId,[Se]:"roleField"};$(J);});});}}}}}),[d,s]},[i,o]=r(e),n=i.reduce((l,d)=>{if(!d.$bzId)return [...l,d];let s=l.findIndex(f=>f.$bzId===d.$bzId);if(s===-1)return [...l,d];if(l[s].$op==="create"&&d.$op==="match")return l;if(l[s].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...l.slice(0,s),d,...l.slice(s+1)];if(l[s].$op==="update"&&d.$op==="update")return [...l.slice(0,s),{...l[s],...d},...l.slice(s+1)];if(l[s].$op==="update"&&d.$op==="match"||l[s].$op==="match"&&d.$op==="update")return [...l.slice(0,s),{...l[s],...d,$op:"update"},...l.slice(s+1)];if(l[s].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(l[s].$filter)===JSON.stringify(d.$filter))return l;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${l[s].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${l[s].$op}. Current: ${d.$op}`)},[]),c=o.reduce((l,d)=>{let s=l.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(s){let f={...s};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=s[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...l.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...l,d]},[]);n.forEach(l=>{if((l.$thingType==="relation"||"relation"in l)&&c.filter(d=>d.$bzId===l.$bzId||d.$tempId&&d.$tempId===l.$tempId).length===0){if(l.$op==="delete"||l.$op==="match"||l.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Mr(l))}`)}});let a=[...n,...c],h=new Set(a.filter(l=>l.$tempId).map(l=>l.$tempId)),p=Array.from(h).filter(l=>!a.some(d=>d.$tempId===l&&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:n,mergedEdges:c}};var Bt=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Cr=async(e,t,r)=>{let i=s=>{let f=s.$op,u=`$${s.$bzId}`,$=q(r,s),{idFields:y,defaultDBConnector:m}=$,B=m?.path||s.$thing,w=s.$id,g=y?.[0],S=listify(s,(D,F)=>{if(D.startsWith("$")||D.startsWith("%")||D===g||F===void 0||F===null)return "";let Q=$.dataFields?.find(M=>M.path===D);if(!Q?.path)return "";let b=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${b} ${F}`;if(Q.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${b} ${F.toISOString().replace("Z","")}`:`has ${b} ${new Date(F).toISOString().replace("Z","")}`}if(Q.contentType==="FLEX"){let M=`bza${nanoid()}`,R=isArray(F)?F.map(k=>Bt(k)):Bt(F);if(Array.isArray(R))throw new Error("Array in FLEX fields not supported yet");return `has ${b} $${M}; $${M} '${M}' isa ${b}, has ${R.type}Attribute ${R.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(D=>D),C=`${u}-atts`,A=listify(s,D=>{if(D.startsWith("$")||D.startsWith("%")||D===g)return "";let F=$.dataFields?.find(b=>b.path===D);if(!F?.path)return "";let E=F.dbPath;return `{${C} isa ${E};}`}).filter(D=>D),O=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,x=w?[`has ${g} ${O}`]:[],W=[...x,...S].filter(D=>D).join(","),le=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...x].filter(D=>D).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...x].filter(D=>D).join(",")}, has ${C};
|
|
37
|
-
${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...x].filter(D=>D).join(",")};`:"";if(Ue(s))return {op:f,deletionMatch:le(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,W].filter(D=>D).join(",")};`:f==="update"&&S.length?`${u} ${S.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${C};`:""};throw new Error("in attributes")},o=s=>{let f=s.$op,u=q(r,s),$=`$${s.$bzId}`,y=s.$id,m=u.defaultDBConnector?.path||s.$thing,B="roles"in u?listify(u.roles,F=>F):[],w="roles"in u?mapEntries(u.roles,(F,Q)=>[F,Q.dbConnector?.path||F]):{},g=listify(s,(F,Q)=>{if(!B.includes(F))return null;if(!("roles"in u))throw new Error("This should have roles! ");let E=w[F];return Array.isArray(Q)?Q.map(b=>({path:E,id:b})):{path:E,id:Q}}).filter(F=>F).flat(),S=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=g.length>0?`( ${S.join(" , ")} )`:"",A=s[Se];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let O=C?`${$} ${C} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",x=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,W=()=>O?f==="link"?`${O};`:f==="create"?`${O}, has id '${y}';`:"":"",le=()=>O&&f==="match"?`${O};`:"",K=()=>O?f==="delete"?`${O};`:f==="match"?`${O};`:"":"",D=()=>O?f==="delete"?`${x};`:f==="unlink"?`${$} ${C};`:"":"";return {deletionMatch:K(),insertionMatch:le(),deletion:D(),insertion:W(),op:""}},n=(s,f)=>{let u=f==="edges"?o:i;if(Array.isArray(s))return s.map(g=>{let{preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x}=u(g);return shake({preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x},W=>!W)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(s);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},c=n(e),a=Array.isArray(c)?c:[c],h=n(t,"edges"),p=Array.isArray(h)?h:[h],l=[...a,...p];return shake({insertionMatches:l.map(s=>s.insertionMatch).join(" ").trim(),deletionMatches:l.map(s=>s.deletionMatch).join(" ").trim(),insertions:l.map(s=>s.insertion).join(" ").trim(),deletions:l.map(s=>s.deletion).join(" ").trim()},s=>!s)};var qe={};function X(e){return {enumerable:!0,value:e}}function Dr(e){return {enumerable:!0,writable:!0,value:e}}var fi=()=>!0,Ar=()=>({}),kr=e=>e,$i=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),mi=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),be=(e,t)=>Object.freeze(Object.create(e,t));function Ir(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Or(e){return be(this,{fn:X(e)})}var Pr={},V=Or.bind(Pr);var qr={},bt=Or.bind(qr);function et(e,t){return t.filter(r=>e.isPrototypeOf(r))}function xr(e,t,...r){let i=Ir(et(qr,r).map(n=>n.fn),fi,$i),o=Ir(et(Pr,r).map(n=>n.fn),kr,mi);return be(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var jr={},Nr={},H=xr.bind(jr);xr.bind(Nr,null);function yi(e,t,r){return Mt(t,e,r,this.immediates)||e}function Wr(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 gi={enter:kr};function he(...e){let t=et(jr,e),r=et(Nr,e),i={final:X(e.length===0),transitions:X(Wr(t))};return r.length&&(i.immediates=X(r),i.enter=X(yi)),be(gi,i)}var Ei={enter(e,t,r){let i=this.fn.call(t,t.context,r);return wt.isPrototypeOf(i)?be(_r,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},_r={enter(e,t,r){if(t.child=ye(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,Mt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=X(Wr(t));return wt.isPrototypeOf(e)?be(_r,{machine:X(e),transitions:r}):be(Ei,{fn:X(e),transitions:r})}var wt={get state(){return {name:this.current,value:this.states[this.current]}}};function we(e,t,r=Ar){return typeof e!="string"&&(r=t||Ar,t=e,e=Object.keys(t)[0]),qe._create&&qe._create(e,t),be(wt,{context:X(r),current:X(e),states:X(t)})}function Mt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:c,reducers:a}of i)if(c(o,r)){e.context=a.call(e,o,r);let h=t.original||t,p=be(h,{current:X(n),original:{value:h}});qe._onEnter&&qe._onEnter(t,n,e.context,o,r);let l=p.state.value;return e.machine=p,e.onChange(e),l.enter(p,e,r)}}function Bi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Mt(e,i,t,o.transitions.get(r))||i:(qe._send&&qe._send(r,n),i)}var Fi={send(e){Bi(this,e);}};function ye(e,t,r,i){let o=Object.create(Fi,{machine:Dr(e),context:Dr(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Kr=(e,t)=>{if(!t)return;let r=wi(t);return Mi(r,e.query)},wi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Mi=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Jr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:c,meta:a}=n,h=c;if(isObject(h)){if(h.$id){if(a.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},l=q(t,p);if(!l?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=l.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),l?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=q(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),isObject(h)&&"$thing"in h&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[te]=a.nodePath;let l=q(t,p);if(h.$filter&&(h.$filterByUnique=Lt(h.$filter,l),h.$filter=xe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>l?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(l.idFields)?l.idFields:[]],h.$idNotIncluded=!0);let s=h.$fields?.flatMap(f=>{let u=Ur(f,l,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=s;}else {let s=St(l)?.flatMap(f=>{let u=Ur(f,l,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=s;}h.$excludedFields&&(h.$fields=h.$fields.filter(d=>tt(l,d)?!0:!h.$excludedFields.includes(d.$path)));}}}))},St=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},Lt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(a=>(a.dbPath===i||a.path===i)&&a?.validations?.unique),c=i==="$id"&&!Array.isArray(e[i]);return o||n||c}return !1}),tt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Si=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:c}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ie]:c}},Li=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:c,fieldSchema:a}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(l=>{let d=h==="role"?l.thingType:"relation",s=h==="role"?l.thing:i.relation,f={[`$${d}`]:s},u=q(c,f),$=t?.$fields?.filter(B=>tt(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=St(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>tt(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,s,c)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:l,$path:l.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:s,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:l.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Lt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:a}})},Ri=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:c,fieldSchema:a}=e;return i.playedBy.map(h=>{let{thing:p,thingType:l,relation:d}=h,s={[`$${l}`]:p},f=q(c,s),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=St(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>tt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,p,c)}:void 0;return {$thingType:l,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:Lt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:a}})},Ur=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),c=t.linkFields?.find(h=>h.path===i),a=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return Si({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(c)return Li({field:e,fieldStr:i,linkField:c,$justId:o,dbPath:c.path,schema:r,fieldSchema:c});if(a)return Ri({field:e,fieldStr:i,roleField:a,$justId:o,dbPath:i,schema:r,fieldSchema:a})}return null},xe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>Object.keys(c).reduce((p,l)=>{let d=c[l],s=isArray(d)?d:[d];if(l.startsWith("$"))["$id","$thing"].includes(l)?p[l]=d:p[l]=xe(d,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=Ie(f,l);if(u==="dataField")p[l]=d;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return s.every(B=>typeof B=="string")?p[l]={$id:s,$thing:m}:s.every(B=>isObject(B))&&(p[l]=isArray(d)?{$or:xe(d,m,r)}:xe(d,m,r)),p}else throw new Error(`Field ${l} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var vr=async(e,t,r)=>r?(n=>produce(n,c=>traverse(c,({value:a})=>{if(isObject(a)){let h=a;if(!h.$thing)return;if(h.$thing){let p=q(e,h),{virtualFields:l}=p,d=h[te];if(!d)throw new Error("[Internal] QueryPath is missing");let s=getNodeByPath(t,d),f=s.$fields.map($=>$.$path),u=s.$excludedFields;l.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Oe({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var Zr=e=>e.replace(/`/g,""),ki=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],rt=e=>ki.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Gr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let l=Rt({parentQuery:t,queries:o,level:1,schema:r});l&&p.push(l);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let f=(d.subTypes?[i,...d.subTypes]:[i]).map(u=>rt(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ge(n,i,r),$=Re(u);p.push(`WHERE ${$}`);}return h&&p.push(Xr(h)),typeof a=="number"&&p.push(`LIMIT ${a}`),typeof c=="number"&&p.push(`START ${c}`),p.join(`
|
|
38
|
-
|
|
39
|
-
`
|
|
40
|
-
`)
|
|
41
|
-
`)}
|
|
39
|
+
stringAttribute sub attribute, value string;
|
|
40
|
+
longAttribute sub attribute, value long;
|
|
41
|
+
doubleAttribute sub attribute, value double;
|
|
42
|
+
booleanAttribute sub attribute, value boolean;
|
|
43
|
+
datetimeAttribute sub attribute, value datetime;
|
|
44
|
+
flexAttribute sub attribute, abstract, value string,
|
|
45
|
+
owns stringAttribute,
|
|
46
|
+
owns longAttribute,
|
|
47
|
+
owns doubleAttribute,
|
|
48
|
+
owns booleanAttribute,
|
|
49
|
+
owns datetimeAttribute;
|
|
50
|
+
`},rr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let o=Xn(e,r),i=n.typeDB.get(e)?.session,a=n.typeDB.get(e)?.client;if(!i){console.log("Session Status: ","NO SESSION");return}if(!a)throw new Error("No TypeDB client found");await i.close();let[{dbName:s}]=t.dbConnectors;await(await a.databases.get(s)).delete(),await a.databases.create(s);let c=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(o),await c.commit(),await c.close(),o};var nr=e=>e.replace(/`/g,""),ei=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],X=e=>ei.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var ti=" ",Qe=e=>ti.repeat(e),Ve=(e,t)=>e.split(`
|
|
51
|
+
`).map(r=>r.trim()?`${Qe(t)}${r}`:r).join(`
|
|
52
|
+
`),ri=e=>{let t=`USE NS test;
|
|
53
|
+
USE DB test;
|
|
54
|
+
|
|
55
|
+
BEGIN TRANSACTION;
|
|
56
|
+
`,r=`-- ENTITIES
|
|
57
|
+
${ir(e.entities)}`,n=`
|
|
58
|
+
-- RELATIONS
|
|
59
|
+
${ir(e.relations)}`,o=ci();return `${t}${r}${n}${o}COMMIT TRANSACTION;`},ir=e=>Object.entries(e).map(([t,r])=>ni(X(t),r,1)).join(`
|
|
60
|
+
|
|
61
|
+
`),ni=(e,t,r)=>{let n=`${Qe(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,o=Ve(`-- DATA FIELDS
|
|
62
|
+
${ii(t.dataFields??[],e,r)}`,r+1),i=Ve(`
|
|
63
|
+
-- LINK FIELDS
|
|
64
|
+
${oi(t.linkFields??[],e,r)}`,r+1),a="roles"in t?Ve(`
|
|
65
|
+
-- ROLES
|
|
66
|
+
${si(t.roles,e,r)}`,r+1):"";return `${n}
|
|
67
|
+
${o}${i}${a}`},ii=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let o=li(n.contentType,n.validations),i=`${Qe(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}return `${i} TYPE ${o};`}).filter(Boolean).join(`
|
|
68
|
+
`),oi=(e,t,r)=>e.map(n=>{let o=n.cardinality==="MANY"?`option<array<record<${n.$things.map(X).join("|")}>>>`:`option<record<${n.$things.map(X).join("|")}>>`,i=`${Qe(r)}DEFINE FIELD ${X(n.path)} ON TABLE ${t}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}if(n.target==="role"){let a=e.find(h=>h.target==="relation"&&h.relation===n.relation),u=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!u||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let $=n.cardinality==="ONE"?`record<${X(n.relation)}>`:`array<record<${X(n.relation)}>>`,c=X(n.pathToRelation||""),d=`${c}.${u}`,l=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${d} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${d} || []) FROM ONLY $this)};`,p=a?.path?"":`${Qe(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${$}>;`;return [l,p].join(`
|
|
69
|
+
`)}if(n.target==="relation")return `${`${Qe(r)}DEFINE FIELD ${X(n.path)} ON TABLE ${t} TYPE ${o};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
|
|
70
|
+
`),si=(e,t,r)=>Object.entries(e).map(([n,o])=>{let i=o.cardinality==="MANY"?`array<record<${o.$things.map(X).join("|")}>>`:`record<${o.$things.map(X).join("|")}>`,a=`${Qe(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,s=ai(n,t,o,r);return `${a}
|
|
71
|
+
${s}`}).join(`
|
|
72
|
+
`),ai=(e,t,r,n)=>{let o=`update_${e}`,i=r.playedBy?.find(B=>B.target==="relation"),a=i?.pathToRelation,s=r.playedBy?.find(B=>B.target==="role"),u=s?.pathToRelation,$=i??s;if(!$)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=X(a??u),d=(B,g)=>B.map(({path:L,cardinality:Q})=>`${L} ${g==="remove"?Q==="ONE"?"=":"-=":Q==="ONE"?"=":"+="} ${g==="remove"?Q==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),l=r.impactedLinkFields?.map(B=>({path:B.path,cardinality:B.cardinality}))||[],h=[{path:c,cardinality:$.cardinality},...l],f=d(h,"remove"),y=d(h,"add"),m=`
|
|
73
|
+
IF ($before.${e}) THEN {UPDATE $before.${e} SET ${f}} END;
|
|
74
|
+
IF ($after.${e}) THEN {UPDATE $after.${e} SET ${y}} END;`,E=`
|
|
75
|
+
LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
|
|
76
|
+
FOR $unlink IN $edges.deletions {UPDATE $unlink SET ${f};};
|
|
77
|
+
FOR $link IN $edges.additions {${$.cardinality==="ONE"?`
|
|
78
|
+
IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
|
|
79
|
+
UPDATE $link SET ${y};
|
|
80
|
+
};`;return Ve(`DEFINE EVENT ${o} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?m:E}
|
|
81
|
+
};`,n+1)},li=(e,t)=>{let r={TEXT:"string",ID:"string",EMAIL:"string",NUMBER:"number",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},n=(i,a)=>{switch(i){case"TEXT":case"ID":case"EMAIL":return `"${a}"`;case"NUMBER":case"BOOLEAN":return a;case"DATE":return `d"${a}"`;case"FLEX":return a;default:return a}},o=t?.enum?`${t.enum.map(i=>n(e,i)).join("|")}`:r[e];if(!o)throw new Error(`Unknown content type: ${e}`);return t?.required?`${o}`:`option<${o}>`},ci=()=>`
|
|
82
|
+
-- BORM TOOLS
|
|
83
|
+
DEFINE FUNCTION fn::get_mutated_edges(
|
|
84
|
+
$before_relation: option<array|record>,
|
|
85
|
+
$after_relation: option<array|record>,
|
|
86
|
+
) {
|
|
87
|
+
LET $notEmptyCurrent = $before_relation ?? [];
|
|
88
|
+
LET $current = array::flatten([$notEmptyCurrent]);
|
|
89
|
+
LET $notEmptyResult = $after_relation ?? [];
|
|
90
|
+
LET $result = array::flatten([$notEmptyResult]);
|
|
91
|
+
LET $links = array::complement($result, $current);
|
|
92
|
+
LET $unlinks = array::complement($current, $result);
|
|
93
|
+
|
|
94
|
+
RETURN {
|
|
95
|
+
additions: $links,
|
|
96
|
+
deletions: $unlinks
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
|
|
101
|
+
RETURN (type::is::array($var) AND $var) OR [$var]
|
|
102
|
+
};
|
|
103
|
+
`,or=e=>ri(e);var sr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([u])=>[u,await rr(u,e,t,r)]))).map(u=>[u[0],u[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([u])=>[u,or(t)]))).map(u=>[u[0],u[1]]);return {typeDB:new Map(i),surrealDB:new Map(s)}})();var re=Symbol.for("queryPath"),He=Symbol.for("stepPrint"),Re=Symbol.for("edgeType"),Te=Symbol.for("edgeSchema"),ke=Symbol.for("dbNode"),ft=Symbol.for("isTransformed"),Ke=Symbol.for("parent"),ne=Symbol.for("fieldSchema"),Fe=Symbol.for("sharedMetadata"),Me=Symbol.for("suqlMetadata");var ar={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var lr=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],i=[e.relation,...o],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 `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[s]=e.oppositeLinkFieldsPlayedBy,u=r.entities[s.thing]?.subTypes||r.relations[s.thing]?.subTypes||[],$=[s.thing,...u],c=`->\u27E8${t}_${s.plays}\u27E9->(\u27E8${$.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${c}`:n==="refs"?`$parent.\`${s.plays}\``:`${a}${c}`}else throw new Error("Unsupported linkField target")};var ur=(e,t,r)=>r?t:`${e}\xB7${t}`;var pr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ae=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,o])=>{let[i,a]=tryit(()=>t(n,o))();return i?!1:a}))},$r=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:s,meta:u})=>{if(u.depth===2&&(a&&(s.dataFields=s.dataFields?.map($=>({...$,...s.idFields?.includes($.path)?{isIdField:!0}:{isIdField:!1},cardinality:$.cardinality||"ONE",dbPath:"dbPath"in $?$.dbPath:ur(a,$.path,$.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${u.nodePath}`);let $=i.entities[s.extends]||i.relations[s.extends],c=[s.extends,...$.allExtends||[]];if(s.allExtends=c,c.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}`)}),s.idFields=$.idFields?Array.from(new Set((s.idFields||[]).concat($.idFields))):s.idFields,s.dataFields=$.dataFields?(s.dataFields||[]).concat($.dataFields.map(d=>{let l=s.extends,p=e.entities[l]||e.relations[l];for(;!p.dataFields?.find(h=>h.path===d.path);)l="extends"in p?p.extends:void 0,p=e.entities[l]||e.relations[l];return {...d,inherited:!0,dbPath:"dbPath"in d?d.dbPath:ur(l,d.path,d.shared),[Fe]:{inheritanceOrigin:d[Fe]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in $){let d=s,l=$;if(l.roles){let p=mapEntries(l.roles,(h,f)=>[h,{...f,inherited:!0,[Fe]:{inheritanceOrigin:f[Fe]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=$.linkFields?(s.linkFields||[]).concat($.linkFields.map(d=>({...d,inherited:!0,[Fe]:{inheritanceOrigin:d[Fe]?.inheritanceOrigin||s.extends}}))):s.linkFields,$?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...$?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:a,meta:s})=>{if(i==="linkFields"){let $=(()=>{if(!s.nodePath)throw new Error("No path");let[d,l]=s.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(a)?a.map(d=>({...d,...$})):[{...a,...$}];r.push(...c);}}),produce(n,i=>traverse(i,({value:a,key:s,meta:u})=>{if(u.depth===2&&a.idFields&&!a.id){a.name=s;let $=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=$();let c=Object.keys(t).find(d=>t[d]?.get(a.defaultDBConnector.id));if(a.db=c,a.dbContext=ar[c],a.dbProviderConfig=c==="surrealDB"?t[c]?.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 p=n.relations[l.relation];if(!l.isVirtual){if(!p)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(p.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:${u.nodePath}."`);l.$things=[l.relation,...p.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){let h=r.filter(f=>f.relation===l.relation&&f.plays!==l.plays)||[];if(l.oppositeLinkFieldsPlayedBy=h,l.oppositeLinkFieldsPlayedBy=l.oppositeLinkFieldsPlayedBy.filter(f=>f.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:${u.nodePath}."`);l.pathToRelation=d.linkFields?.find(f=>f.target==="relation"&&f.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=l.oppositeLinkFieldsPlayedBy.map(f=>f.thing),l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(f=>f.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=p?.roles?.[l.plays][Fe]?.inheritanceOrigin??l.relation,f=lr({linkField:l,originalRelation:h,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Me]={queryPath:f};}});}if("roles"in a){let d=a;Object.entries(d.roles).forEach(([l,p])=>{p.fieldType="roleField";let h=r.filter(g=>g.relation===s&&g.plays===l)||[];p.playedBy=h.map(g=>({...g,pathToRelation:g.target==="relation"?g.path:d.linkFields?.find(L=>L.target==="relation"&&L.relation===s&&L.plays===l)?.path??g.relation.toLocaleLowerCase()}));let f=r.filter(g=>g.target==="relation"&&g.plays===l&&d.allExtends?.includes(g.relation));p.impactedLinkFields=f,p.path=l;let y=[...new Set(h.flatMap(g=>[...Y(n,g.thing).subTypes||[],g.thing]).flat().filter(Boolean))];p.$things=y;let m=p[Fe]?.inheritanceOrigin||a.name;y.length>1&&console.warn(`Not supported yet: Role ${l} in ${a.name} is played by multiple things: ${y.join(", ")}`);let E=y.flatMap(g=>{let Q=Y(e,g)?.subTypes||[];return [g,...Q]}),B=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${m}_${l}\`->(\`${E.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(p.cardinality==="MANY")return `$parent.\`${l}\``;if(p.cardinality==="ONE")return `$parent.[\`${l}\`]`}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let g=B();p[Me]={queryPath:g};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let $=[...new Set(a.playedBy.map(c=>c.thing))];if($.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${u.nodePath}, played by: ${$.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${u.nodePath}`)}if(u.depth===4){let[$,c]=u.nodePath?.split(".")||[],d=i[$][c];!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));}}))},Y=(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`)},q=(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)}`)},ve=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ye=(e,t)=>{let r=q(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},fr=(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")},gt=(e,t,r)=>{let n=q(e,t),o=n.linkFields?.find(s=>s.path===r);if(o)return o;let i=n.dataFields?.find(s=>s.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`)},Et=(e,t,r)=>gt(e,t,r)?.cardinality,le=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],n=e.linkFields?.map(h=>h.path)||[],o="roles"in e?listify(e.roles,h=>h):[],i=[...r||[],...n||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!t)return {fields:i,dataFields:r,roleFields:o,linkFields:n};let u=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),$=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],c=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...n||[]].includes(h)):[],d=[...u,...$].filter(h=>!h?.startsWith("%")).filter(h=>!s.includes(h)).filter(h=>h),l=t.$filter?ae(t.$filter,(h,f)=>$.includes(h)):{},p=t.$filter?ae(t.$filter,(h,f)=>c.includes(h)):{};return {fields:i,dataFields:r,roleFields:o,linkFields:n,usedFields:u,usedLinkFields:n.filter(h=>u.includes(h)),usedRoleFields:o.filter(h=>u.includes(h)),usedDataFields:r.filter(h=>u.includes(h)),unidentifiedFields:d,...$.length?{localFilters:l}:{},...c.length?{nestedFilters:p}:{}}};var mr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},yr=(e,t,r)=>{let o=(r.nodePath||"").split("."),i=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},we=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ge=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Ee=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,o])=>{r[n]=isDraft(o)?current(o):o;}),r}else return e},ue=(e,t)=>{if(e===void 0)throw t?new Error(t):new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},De=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e??21)();var Pe=(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 Er=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(o=>typeof o=="object"))if(n.every(o=>typeof o=="string")){let o=Pe(t,r),[i]=o,a=e.$op==="create"?"link":"replace",s=i.thing,u=i.thingType,$={$op:a,$thing:s,$thingType:u},c=n.filter(l=>l.startsWith("_:")),d=n.filter(l=>!l.startsWith("_:"));c.length&&!d.length?e[t]=c.map(l=>({...$,$tempId:l,$bzId:l})):c.length&&d.length?e[t]=[...c.map(l=>({...$,$tempId:l,$bzId:l})),{...$,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...$,$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 Ie=(e,t,r)=>{let n=q(r,t),{usedDataFields:o}=le(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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Ze=(e,t,r)=>{let n=q(r,t),{usedFields:o}=le(n,t);return t.$op?(Ie(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Ie(e,{...t,$op:"update"},r),"update"):(Ie(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Ie(e,{...t,$op:"create"},r),"create"):(Ie(e,{...t,$op:"create"},r),"link"):(Ie(e,{...t,$op:"create"},r),"create")};var Fr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let i=Ze(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:fr(o,t)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${De()}`}},...o}});e.$root=isArray(e.$root)?n:n[0];};var Xe=(e,t)=>{let r=t[He];return isSet(r)?r.has("clean")?(Reflect.set(t,He,r.add("clean")),!0):!1:(Reflect.set(t,He,new Set(["clean"])),!0)};var br=(e,t,r)=>{if(Xe("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let i=o;if(q(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,s)=>({...Ee(i),$id:a,$bzId:`${i.$bzId}_${s}`,...we(i)}))}return o});(n.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Tr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=Pe(t,r),[s]=a,u=Ze(e,{...i,$thing:s.thing,$thingType:s.thingType},n),c=i.$bzId?i.$bzId:i.$tempId?i.$tempId:i.$id&&!isArray(i.$id)?`SN_ONE_${s.thing}_${i.$id}`:i.$id&&isArray(i.$id)?`SN_MANY_${s.thing}_${De()}`:`SM_${De()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Te]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var Ei=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Bi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Mr=e=>{let r=e.toString().replace(Ei,"").trim().split("=>")[0].split("{")[0].replace(Bi,"").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(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var qe=({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:o}=t.default,a=Mr(o).filter(s=>!(s in e));if(a.length)throw new Error(`Virtual field: Missing arguments ${a.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var wr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(o=>{let i=q(r,o),{unidentifiedFields:a}=le(i,o),{computedFields:s,virtualFields:u}=i,$=listify(o,(l,p)=>p!==void 0?l:void 0),c=$.filter(l=>u?.includes(l));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(l=>!$.includes(l)).forEach(l=>{let p=i.dataFields?.find(E=>E.path===l),f=i.linkFields?.find(E=>E.path===l)?.oppositeLinkFieldsPlayedBy[0],y="roles"in i?pr(i.roles,(E,B)=>E===l):void 0,m=p||f||y;if(!m)throw new Error(`no field Def for ${l}`);if(o.$op==="create"&&!o[l]){let E=qe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[l]=E;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(o)}`)}),e};var tt=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let n=`on${mr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var Lr=(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:s,fnValidatedFields:u,dataFields:$}=q(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(c=>{if(!(c in i))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&s.forEach(c=>{if(c in i){let d=$?.find(l=>l.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(i[c]))i[c].some(l=>{if(!d.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(i[c]))throw new Error(`[Validations] Option "${i[c]}" is not a valid option for field "${c}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&u.forEach(c=>{if(c in i)try{let d=$?.find(l=>l.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(i[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(i)&&"$thing"in i){let c=i.$thing,d=i,l=clone(Ee(e)),p=clone(Ee(d)),h=n.mutation?.context||{},f=clone(Ee(i[ke]||{}));tt(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let E=m.fn(p,l,h,f);if(E===!1)throw new Error(`${m.message}.`);if(E!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(E){throw new Error(`[Validations:thing:${c}] ${E.message}`)}}});}}});};var Rr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(Ge(i)){if(i.$fields||i[ft])return i;let a=tt(i,r).filter(d=>d.type==="transform"),s=clone(Ee(e)),u=clone(Ee(i)),$=n.mutation?.context||{},c=clone(Ee(i[ke]||i.$dbNode));return a.forEach(d=>{let l=d.fn(u,s,$,c||{});Object.keys(l).length!==0&&(i={...u,...l,...we(i),[ft]:!0});}),i}});e[t]=isArray(e[t])?o:o[0];};var Dr=(e,t,r)=>{let n=Pe(t,r),[o]=n;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Te]:r};};var xe=e=>{if(Array.isArray(e)){for(let t of e)if(xe(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"&&xe(e[t]))return !0}return !1};var Di=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Xe("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")},Ii=(e,t)=>{},Mt=(e,t,r)=>{let n={$rootWrap:{$root:e}},o=xe(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:s,parent:u,key:$,meta:c})=>{if(!(!u||!$)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let h=["$fields","$dbNode","$filter"],f=d[d.length-1],y=d[d.length-2];if($==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes(f)&&!h.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let l=s,p=d.includes("$filter");Object.keys(l).forEach(h=>{if(Di(l,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let f=h!=="$root"?gt(t,l,h):{fieldType:"rootField"};if(!f)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in f)return Ii();if(["rootField","linkField","roleField"].includes(f.fieldType)){if(["linkField","roleField"].includes(f.fieldType)&&(l[h]===null?Dr(l,h,f):Er(l,h,f)),f.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Fr(l,t);}let y=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");y.forEach(B=>{if(B){if(f?.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(f.fieldType)&&Tr(l,h,f,t),br(l,h,t),["rootField","linkField","roleField"].includes(f.fieldType)&&wr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(B=>{let g=q(t,B),{unidentifiedFields:L,usedLinkFields:Q,usedFields:I,fields:A}=le(g,B);if(I.forEach(j=>{if(!A.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(Q.length>1){let j=g.linkFields?.filter(K=>Q.includes(K.path));j?.some((K,me)=>j.some((v,C)=>{if(me!==C&&K.target!==v.target&&K.relation===v.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(Rr(l,h,t,r),Lr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Ir=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var kr=async(e,t)=>{let r=c=>{let d=[],l=[],p=m=>{if(m.$id)return m.$id;let E=q(t,m),{idFields:B}=E;if(!B)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=B;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=E.dataFields?.find(A=>A.path===g),Q=qe({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),I=m[g]||m.$id||Q;if(!I)throw new Error(`no idValue: ${JSON.stringify(m)}`);return I},h=m=>{if(m.$op==="create"){let E=p(m);if(d.find(B=>B.$id===E&&B.$op==="create"))throw new Error(`Duplicate id ${E} for node ${JSON.stringify(m)}`);if(l.find(B=>B.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:E});return}m.$tempId&&m.$op==="match"||d.push(m);},f=m=>{if(m.$op==="create"){let E=p(m);if(d.find(B=>B.$id===E),l.find(B=>B.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);l.push({...m,$id:E});return}l.push(m);};return traverse(c,({value:m,parent:E,meta:B})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=q(t,g),{dataFields:Q,roleFields:I,linkFields:A,usedFields:j}=le(L,g),K=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let C=j.filter(F=>Q?.includes(F)),w=j.filter(F=>I?.includes(F)),b=j.filter(F=>A?.includes(F));if(C.length>0)return "update";if(w.length>0||b.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},me={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,Q||[""])),$op:K(),$bzId:g.$bzId};h(me);let v=g[Te];if(v?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let C=v.relation===g.$thing,w=C?g.$bzId:`LT_${v4()}`,F=yr(c,E,B).$bzId;if(!F)throw new Error("No parent id found");let S=()=>g.$op==="delete"?C?"match":"delete":g.$op==="unlink"?C?"unlink":"delete":g.$op==="link"||g.$op==="create"?C?"link":"create":g.$op==="replace"?"replace":"match",T=q(t,{$thing:v.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(v.plays))throw new Error(`[Wrong format] Field ${v.plays} is not a role of relation ${v.relation}`);let k={$bzId:w,$thing:v.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:S(),...C?{}:{[v.path]:g.$bzId},[v.plays]:F,[Te]:v,[Re]:"linkField"};f(k),(g.$op==="unlink"||S()==="unlink")&&C&&f({$thing:v.relation,$thingType:"relation",$bzId:w,$op:"match",[v.plays]:F,[Te]:v,[Re]:"linkField"});}if(g.$thingType==="relation"){let C=ae(g,(F,S)=>I.includes(F)),w=mapEntries(C,(F,S)=>isArray(S)?[F,S]:isObject(S)?[F,S.$bzId]:[F,S]),b=ae(m,(F,S)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(C).filter(F=>!F.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let F=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=q(t,g).roles,T=mapEntries(w,(k,R)=>{let z=S[k]?.cardinality;if(!z)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(R)){if(z==="ONE"){if(R.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,R[0].$bzId||R[0]]}return [k,R.map(J=>J.$bzId||J)]}return [k,R.$bzId||R]}),D={...b,$thing:g.$thing,$thingType:"relation",$op:F(),...T,$bzId:g.$bzId,[Re]:"roleField"};f(D);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(C).length>0){let F=0;Object.entries(C).forEach(([S,T])=>{let D=isArray(T)?T:[T],k=R=>R==="create"||R==="replace"?"link":R;D.forEach(R=>{if(!R)return;let z=k(R.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&F>0)throw F+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...b,$thing:g.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[S]:R.$bzId,$bzId:g.$bzId,[Re]:"roleField"};f(J);});});}}}}}),[d,l]},[n,o]=r(e),i=n.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let l=c.findIndex(p=>p.$bzId===d.$bzId);if(l===-1)return [...c,d];if(c[l].$op==="create"&&d.$op==="match")return c;if(c[l].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,l),d,...c.slice(l+1)];if(c[l].$op==="update"&&d.$op==="update")return [...c.slice(0,l),{...c[l],...d},...c.slice(l+1)];if(c[l].$op==="update"&&d.$op==="match"||c[l].$op==="match"&&d.$op==="update")return [...c.slice(0,l),{...c[l],...d,$op:"update"},...c.slice(l+1)];if(c[l].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(c[l].$filter)===JSON.stringify(d.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[l].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[l].$op}. Current: ${d.$op}`)},[]),a=o.reduce((c,d)=>{let l=c.find(p=>(p.$id&&p.$id===d.$id||p.$bzId&&p.$bzId===d.$bzId)&&p.$thing===d.$thing&&p.$op===d.$op);if(l){let p={...l};return Object.keys(d).forEach(f=>{if(typeof f=="symbol"||f.startsWith("$"))return;let y=l[f],m=d[f];Array.isArray(y)&&Array.isArray(m)?p[f]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?p[f]=Array.from(new Set([y,...m])):p[f]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(p[f]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?p[f]=Array.from(new Set([y,m])):y==null&&(p[f]=m);}),[...c.filter(f=>!((f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op)),p]}return [...c,d]},[]);i.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&a.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Ir(c))}`)}});let s=[...i,...a],u=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),$=Array.from(u).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if($.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${$.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var Ne={};function ee(e){return {enumerable:!0,value:e}}function Pr(e){return {enumerable:!0,writable:!0,value:e}}var xi=()=>!0,qr=()=>({}),Nr=e=>e,Ni=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),ji=(e,t,r,[n,o])=>t.call(r,e.call(r,n,o),o),Se=(e,t)=>Object.freeze(Object.create(e,t));function xr(e,t,r){return e.reduce((n,o)=>function(...i){return r(n,o,this,i)},t)}function jr(e){return Se(this,{fn:ee(e)})}var _r={},x=jr.bind(_r);var zr={},wt=jr.bind(zr);function rt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Ur(e,t,...r){let n=xr(rt(zr,r).map(i=>i.fn),xi,Ni),o=xr(rt(_r,r).map(i=>i.fn),Nr,ji);return Se(this,{from:ee(e),to:ee(t),guards:ee(n),reducers:ee(o)})}var Wr={},Vr={},N=Ur.bind(Wr);Ur.bind(Vr,null);function _i(e,t,r){return Lt(t,e,r,this.immediates)||e}function Hr(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 zi={enter:Nr};function ie(...e){let t=rt(Wr,e),r=rt(Vr,e),n={final:ee(e.length===0),transitions:ee(Hr(t))};return r.length&&(n.immediates=ee(r),n.enter=ee(_i)),Se(zi,n)}var Ui={enter(e,t,r){let n=this.fn.call(t,t.context,r);return St.isPrototypeOf(n)?Se(Kr,{machine:ee(n),transitions:ee(this.transitions)}).enter(e,t,r):(n.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Kr={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,Lt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function W(e,...t){let r=ee(Hr(t));return St.isPrototypeOf(e)?Se(Kr,{machine:ee(e),transitions:r}):Se(Ui,{fn:ee(e),transitions:r})}var St={get state(){return {name:this.current,value:this.states[this.current]}}};function ye(e,t,r=qr){return typeof e!="string"&&(r=t||qr,t=e,e=Object.keys(t)[0]),Ne._create&&Ne._create(e,t),Se(St,{context:ee(r),current:ee(e),states:ee(t)})}function Lt(e,t,r,n){let{context:o}=e;for(let{to:i,guards:a,reducers:s}of n)if(a(o,r)){e.context=s.call(e,o,r);let u=t.original||t,$=Se(u,{current:ee(i),original:{value:u}});Ne._onEnter&&Ne._onEnter(t,i,e.context,o,r);let c=$.state.value;return e.machine=$,e.onChange(e),c.enter($,e,r)}}function Wi(e,t){let r=t.type||t,{machine:n}=e,{value:o,name:i}=n.state;return o.transitions.has(r)?Lt(e,n,t,o.transitions.get(r))||n:(Ne._send&&Ne._send(r,i),n)}var Vi={send(e){Wi(this,e);}};function fe(e,t,r,n){let o=Object.create(Vi,{machine:Pr(e),context:Pr(e.context(r,n)),onChange:ee(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,n),o}var Gr=(e,t)=>{if(!t)return;let r=Ki(t);return Ji(r,e.query)},Ki=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Ji=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let o=n;Object.keys(o).forEach(i=>{(o[i]===void 0||o[i]===null||isArray(o[i])&&o[i].length===0)&&(t?.returnNulls?o[i]=null:delete o[i]),o[i]===void 0&&delete o[i];}),Object.getOwnPropertySymbols(o).forEach(i=>{delete o[i];}),t?.noMetadata===!0&&Object.keys(o).forEach(i=>{i.startsWith("$")&&delete o[i];});}}));var Xr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,i=>{let{value:a,meta:s}=i,u=a;if(isObject(u)){if(u.$id){if(s.nodePath?.includes(".$filter"))return;let $=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing},c=q(t,$);if(!c?.name)throw new Error(`Schema not found for ${u.$thing}`);if(u.$path=c.name,Array.isArray(u.$id)||(u.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in u||"$relation"in u||"$thing"in u){let $=q(t,u);if(!$?.name)throw new Error(`Schema not found for ${u.$thing}`);u.$path=$.name;}if(u.$entity?(u.$thing=u.$entity,u.$thingType="entity",delete u.$entity):u.$relation&&(u.$thing=u.$relation,u.$thingType="relation",delete u.$relation),isObject(u)&&"$thing"in u&&u.$thing){let $=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing};u[re]=s.nodePath;let c=q(t,$);if(u.$filter&&(u.$filterByUnique=It(u.$filter,c),u.$filter=je(u.$filter,u.$thing,t)),u.$fields){u.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(u.$fields=[...u.$fields,...Array.isArray(c.idFields)?c.idFields:[]],u.$idNotIncluded=!0);let l=u.$fields?.flatMap(p=>{let h=Zr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}else {let l=Dt(c)?.flatMap(p=>{let h=Zr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>nt(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},Dt=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]},It=(e,t)=>Object.keys(e||{}).some(n=>{if(!Array.isArray(e[n])){let o=t.idFields?.includes(n),i=t.dataFields?.some(s=>(s.dbPath===n||s.path===n)&&s?.validations?.unique),a=n==="$id"&&!Array.isArray(e[n]);return o||i||a}return !1}),nt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Gi=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:o,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[ne]:a}},Zi=e=>{let{field:t,fieldStr:r,linkField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e,{target:u,oppositeLinkFieldsPlayedBy:$}=n;return $.map(c=>{let d=u==="role"?c.thingType:"relation",l=u==="role"?c.thing:n.relation,p={[`$${d}`]:l},h=q(a,p),f=t?.$fields?.filter(E=>nt(h,E)).length===0,y=[];if(typeof t!="string")if(t.$fields)if(f){let E=h.idFields||[];y=[...t.$fields,...E];}else y=t.$fields;else y=Dt(h);else y=["id"];t.$excludedFields&&(y=y.filter(E=>nt(h,E)?!0:!t.$excludedFields.includes(E.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...je(t.$filter,l,a)}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:c,$path:c.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:u,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:f,$filterByUnique:It(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},Xi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e;return n.playedBy.map(u=>{let{thing:$,thingType:c,relation:d}=u,l={[`$${c}`]:$},p=q(a,l),h=t?.$fields?.filter(m=>p?.idFields?.includes(m)||p?.idFields?.includes(m.$path)).length===0,f=[];if(typeof t!="string")if(t.$fields)if(h){let m=p.idFields||[];f=[...t.$fields,...m];}else f=t.$fields;else f=Dt(p);else f=["id"];t.$excludedFields&&(f=f.filter(m=>nt(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...je(t.$filter,$,a)}:void 0;return {$thingType:c,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:$,$fields:f,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:h,$filterByUnique:It(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},Zr=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,o=typeof e=="string",i=t.dataFields?.find(u=>u.path===n),a=t.linkFields?.find(u=>u.path===n),s=t.roles?.[n];if(i){let u=!!i.isVirtual&&!!i.default;return Gi({field:e,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:u,fieldSchema:i})}else {if(a)return Zi({field:e,fieldStr:n,linkField:a,$justId:o,dbPath:a.path,schema:r,fieldSchema:a});if(s)return Xi({field:e,fieldStr:n,roleField:s,$justId:o,dbPath:n,schema:r,fieldSchema:s})}return null},je=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce(($,c)=>{let d=a[c],l=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?$[c]=d:$[c]=je(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,f]=ve(p,c);if(h==="dataField")$[c]=d;else if(h==="linkField"||h==="roleField"){let y=f,[m]=y.$things;return l.every(E=>typeof E=="string")?$[c]={$id:l,$thing:m}:l.every(E=>isObject(E))&&($[c]=isArray(d)?{$or:je(d,m,r)}:je(d,m,r)),$}else throw new Error(`Field ${c} not found in schema of ${t}`)}return $},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var en=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:s})=>{if(isObject(s)){let u=s;if(!u.$thing)return;if(u.$thing){let $=q(e,u),{virtualFields:c}=$,d=u[re];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),p=l.$fields.map(f=>f.$path),h=l.$excludedFields;c.forEach(f=>{if(h?.includes(f)||p.length>0&&!p.includes(f))return;let y=$.dataFields?.find(m=>m.path===f);if(y?.default){let m=qe({currentThing:u,fieldSchema:y,mandatoryDependencies:!0});u[f]=m;}else if(u[f]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${f}`)}),h&&h.forEach(f=>{if(typeof f!="string")throw new Error("[Internal] ExcludedField is not a string");delete u[f];});}}})))(r):void 0;var he=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let u=Object.keys(a).reduce(($,c)=>{let d=a[c];if(c.startsWith("$"))return c==="$not"?{...$,$not:void 0,"$!":he(d,t,r)}:c==="$or"?{...$,$or:void 0,$OR:he(d,t,r)}:c==="$and"?{...$,$and:void 0,$AND:he(d,t,r)}:c==="$eq"?{...$,$nor:void 0,"$=":he(d,t,r)}:c==="$id"?{...$,$id:void 0,"record::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?$:{...$,[c]:he(d,t,r)};let l=t in r.entities?r.entities[t]:r.relations[t],[p,h]=ve(l,c);if(p==="dataField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return c===l.idFields[0]?{...$,"record::id(id)":{$IN:isArray(d)?d:[d]}}:{...$,[c]:d}}if(p==="linkField"||p==="roleField"){let f=h;if(f.$things.length!==1)throw new Error(`Not supported yet: Role ${c} in ${d.name} is played by multiple things: ${f.$things.join(", ")}`);let[y]=f.$things,m=f[Me].queryPath;return {...$,[m]:he(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(u)});return n?i:i[0]},$e=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,o])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(o)?o.map(s=>$e(s)):[$e(o)];i==="!"?r.push(`!(${a.join(` ${i} `)})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(o))if(n.includes("<-")||n.includes("->")){let i=$e(o);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent")){let i=$e(o),a=n.replace("$parent.","");r.push(`${a}[WHERE ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[i]=Object.keys(o),a=o[i];if(isArray(a))r.push(`${n} ${i.replace("$","")} [${a.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(a)){let s=$e(a);r.push(`${n} ${i.replace("$","")} ${s}`);}else r.push(`${n} ${i.replace("$","")} '${a}'`);}else throw new Error(`Invalid key ${n}`)}else if(Array.isArray(o)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${o.map(a=>`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} '${o}'`);}}),r.join(" AND ")},_e=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:o}=r;return `${n}${o?" DESC":" ASC"}`}).join(", ")}`;var rn=e=>{let{queries:t,schema:r}=e;return t.map(n=>so({query:n,schema:r}))},so=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:u}=t;if(o.length===0)return null;let $=[];$.push("SELECT");let c=At({parentQuery:t,queries:o,level:1,schema:r});c&&$.push(c);let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let p=(d.subTypes?[n,...d.subTypes]:[n]).map(h=>X(h));if(t.$id)if(typeof t.$id=="string")$.push(`FROM ${p.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,f=p.flatMap(y=>h?.map(m=>`${y}:\u27E8${m}\u27E9`));$.push(`FROM ${f.join(",")}`);}else throw new Error("Invalid $id");else $.push(`FROM ${p.join(",")}`);if(i){let h=he(i,n,r),f=$e(h);$.push(`WHERE ${f}`);}return u&&$.push(_e(u)),typeof s=="number"&&$.push(`LIMIT ${s}`),typeof a=="number"&&$.push(`START ${a}`),$.join(`
|
|
104
|
+
`)},At=e=>{let{queries:t,schema:r,level:n,parentQuery:o}=e,i=[],a=o[re];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(s=>{let u=ao({query:s,level:n,schema:r});u&&i.push(u);}),i.length===0?null:i.join(`,
|
|
105
|
+
`)},ao=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?lo({query:t,level:n}):t.$fieldType==="link"?co({query:t,level:n,schema:r}):t.$fieldType==="role"?uo({query:t,level:n,schema:r}):null},lo=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)},co=e=>{let{query:t,schema:r,level:n}=e,{$fields:o,$filter:i,$offset:a,$limit:s,$sort:u}=t;if(o.length===0)return null;let $=[];$.push(M("(",n));let c=n+1;$.push(M("SELECT",c));let d=At({parentQuery:t,queries:o,level:c+1,schema:r});d&&$.push(d);let l=t[ne][Me].queryPath;if($.push(M(`FROM ${l}`,c)),i){let p=he(i,t.$thing,r),h=$e(p);$.push(`WHERE ${h}`);}return u&&$.push(M(_e(u),c)),typeof s=="number"&&$.push(M(`LIMIT ${s}`,c)),typeof a=="number"&&$.push(M(`START ${a}`,c)),$.push(M(`) AS \`${t.$as}\``,n)),$.join(`
|
|
106
|
+
`)},uo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let o=[];o.push(M("(",n));let i=n+1;o.push(M("SELECT",i));let a=i+1,s=At({parentQuery:t,queries:t.$fields,level:a,schema:r});s&&o.push(s);let u=t[ne][Me].queryPath;if(o.push(M(`FROM ${u}`,i)),t.$filter){let $=he(t.$filter,t.$playedBy.thing,r),c=$e($);o.push(`WHERE ${c}`);}return o.push(M(`) AS \`${t.$as}\``,n)),o.join(`
|
|
107
|
+
`)};var nn=async e=>{let{client:t,queries:r}=e,n=`
|
|
42
108
|
BEGIN TRANSACTION;
|
|
43
109
|
${r.join(";")};
|
|
44
110
|
COMMIT TRANSACTION;
|
|
45
|
-
`;return await t.query(
|
|
46
|
-
`)
|
|
47
|
-
`),
|
|
48
|
-
${m}`);}let
|
|
49
|
-
offset ${
|
|
50
|
-
limit ${
|
|
51
|
-
`)},
|
|
52
|
-
?queryPath${
|
|
53
|
-
`)},it=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},oe=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,Yi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},xt=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,c=G(i,r),a=[],h=[];if(o?.forEach(p=>{let l=Yi(p),d=c.dataFields?.find(u=>u.path===l.field);if(!d)throw new Error(`"${r}" does not have data field "${l.field}"`);let s=`${l.field}_${v4()}`;a.push(T("{",n)),a.push(T(`$${t} has ${d.dbPath} $${s}_1;`,n+1)),a.push(T("not {",n+1)),a.push(T(`$${t} has ${d.dbPath} $${s}_2;`,n+2)),a.push(T(`$${s}_2 < $${s}_1;`,n+2)),a.push(T("};",n+1)),a.push(T(`?${s}_ = $${s}_1;`,n+1)),a.push(T("} or {",n)),a.push(T(`not { $${t} has ${d.dbPath} $${s}_1; };`,n+1)),a.push(T(`?${s}_ = "~";`,n+1)),a.push(T("};",n)),a.push(T(`?${s} = ?${s}_;`,n));let f=l.desc?"desc":"asc";h.push(`?${s} ${f}`);}),a.length!==0)return {match:a.join(""),sort:T(`sort ${h.join(", ")};`,n)}};var fn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((c,a)=>{let h=r[a],p=t[a];return Xi(c,h,p,i,o)})},Xi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?pn(e[0],t,i,o):e.map(n=>pn(n,t,i,o)),pn=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:c,roleFields:a,schemaValue:h}=jt(e,r),p=Nt(o,n,i),l=_t(c,r,i),d=Wt(a,r,i),s=t?.$fields?.every(u=>!n?.idFields?.includes(typeof u=="string"?u:u.$path));return {...l,...d,...h,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...s?Object.fromEntries(Object.entries(p).filter(([u])=>!n?.idFields?.includes(u))):p}},jt=(e,t)=>{let r=Object.keys(e),i=r.find(f=>f.endsWith(".$dataFields")),o=r.filter(f=>f.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(f=>{let u=f.replace(/\.\$multiVal$/,""),$=e[f][0][u].attribute;e[i][u]=$;});let n=e[i],c=i.split(".")[i.split(".").length-2];if(n.$metaData=c,n.length===0)throw new Error("No dataFields");let a=n.type,h={$thing:a.label,$thingType:a.root,[te]:e.queryPath.value},p={[`$${h.$thingType}`]:h.$thing},l=q(t,p),d=r.filter(f=>{let u=ae(f.split(".").pop());return !f.endsWith(".$dataFields")&&l.linkFields?.some($=>$.path===u)}).map(f=>{let u=ae(f.split(".").pop()),$=ae(l.linkFields?.find(y=>y.path===u));return {$linkFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),s=r.filter(f=>{let u=f.split(".").pop();return u&&!f.endsWith(".$dataFields")&&l.thingType==="relation"&&l.roles?.[u]}).map(f=>{let u=ae(f.split(".").pop());return {$roleFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:l.roles[u].cardinality}});return {dataFields:n,schemaValue:h,currentSchema:l,linkFields:d,roleFields:s}},Nt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=eo(i),n=Object.entries(e).filter(([c])=>c!=="type"&&!c.startsWith("$")).map(([c,a])=>{let h=t.dataFields?.find(s=>s.path===c||s.dbPath===c),p=c==="id",l=Array.isArray(o)?o.find(s=>s[c])?.[c]:c,d;if(h?.cardinality==="ONE"){if(d=a[0]?a[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"||h.contentType==="FLEX"&&a[0].type.value_type==="datetime"?d=d&&`${d}Z`:h.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[l,d],["$id",d]].filter(([s,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[l,null]]:[];h.contentType==="DATE"?d=a.map(s=>`${s.value}Z`):h.contentType==="FLEX"?d=a.map(s=>s.type.value_type==="datetime"?`${s.value}Z`:s.value):h.contentType==="JSON"?d=a.map(s=>s.value&&JSON.parse(s.value)):d=a.map(s=>s.value);}return [[l,d]].filter(([s,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},Wt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:c,$cardinality:a}=o,{as:h,justId:p,idNotIncluded:l,filterByUnique:d}=$n(c);if(h===null)return;let s=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return l==="true"&&$?.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});s.length>0?i[h]=a==="MANY"&&d==="false"?s:s[0]:r.query?.returnNulls&&(i[h]=null);}),i},_t=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:c,$cardinality:a}=o,{as:h,justId:p,idNotIncluded:l,filterByUnique:d}=$n(c);if(h===null)return;let s=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return l==="true"&&$.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});i[h]=s.length>0?a==="MANY"&&d==="false"?s:s[0]:r.query?.returnNulls?null:void 0;}),i},$n=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),c=e.match(r),a=e.match(i),h=e.match(o);return {as:n?n[1]:null,justId:c?c[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:h?h[1]:null}},eo=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(c,a,h)=>/^{.*}$/.test(h)?`:${h}`:`:${a}"${h}"`),n=n.replace(/\[([^\]]+)\]/g,(c,a)=>`[${a.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var mn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ge(r,i),c=await n.transaction(TransactionType.READ,o),[a,h]=await tryit(parallel)(t.length,t,async p=>await c.query.fetch(p).collect());if(a){await c.rollback();let p=a;throw new Error(`Error running TQL query: ${p.errors}`)}return await c.close(),h};var oo=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,so=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,ao=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,zt=H("error","error",V((e,t)=>({...e,error:t.error}))),lo=we("build",{build:Z(async e=>un({queries:e.bql.queries,schema:e.schema}),H("done","run",V(so)),zt),run:Z(async e=>mn({dbHandles:e.handles,tqlRequest:ae(e.tql.queries),config:e.config}),H("done","parse",V(ao)),zt),parse:Z(async e=>fn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ae(e.tql.res)}),H("done","success",V(oo)),zt),success:he(),error:he()},e=>e),co=async e=>new Promise((t,r)=>{ye(lo,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),yn=async(e,t,r,i,o)=>co({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var ho=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Vt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ot=H("error","error",V((e,t)=>({...e,error:t.error}))),uo=we("enrich",{enrich:Z(async e=>Jr(e.bql.raw,e.schema),H("done","adapter",V(ho)),ot),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((a,h)=>{let p=e.bql.raw[h],l=G(e.schema,a.$thing),{id:d}=l.defaultDBConnector;if(l.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${l.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(l.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${l.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${l.db}"`);let s=t[d];s.rawBql.push(p),s.bqlQueries.push(a),s.indices.push(h);});let r=Object.values(t),i=r.map(a=>{if(a.db==="typeDB")return yn(a.rawBql,a.bqlQueries,e.schema,e.config,e.handles);if(a.db==="surrealDB")return dn(a.bqlQueries,e.schema,e.config,a.client);throw new Error("Unsupported DB provider")}),o=await Promise.all(i),n=r.flatMap((a,h)=>{let p=o[h];return a.indices.map((l,d)=>({index:l,result:p[d]}))});return n.sort((a,h)=>a.index<h.index?-1:a.index>h.index?1:0),n.map(({result:a})=>a)},H("done","postHooks",V(Vt)),ot),postHooks:Z(async e=>vr(e.schema,ae(e.bql.queries),ae(e.bql.res)),H("done","clean",V(Vt)),ot),clean:Z(async e=>Kr(e.config,ae(e.bql.res)),H("done","success",V(Vt)),ot),success:he(),error:he()},e=>e),po=async e=>new Promise((t,r)=>{ye(uo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),je=async(e,t,r,i)=>po({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Ht="___",fo=Symbol.for("grandChildOfCreate"),gn=async(e,t,r,i)=>{let o=(F,Q)=>Object.keys(F).filter(E=>!E.startsWith("$")&&F[E]!==void 0?Q?!q(t,F).dataFields?.find(M=>M.path===E):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:F,key:Q,value:E})=>{F&&Q&&!Q.includes("$")&&isObject(F)?(Array.isArray(F[Q])?F[Q]:[F[Q]]).forEach(M=>{if(isObject(M)){if(F.$op!=="create")n.includes(M.$op)||n.push(M.$op);else if(M.$op==="delete"||M.$op==="unlink")throw new Error(`Cannot ${M.$op} under a create`)}}):!F&&isObject(E)&&(n.includes(E.$op)||n.push(E.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let a=(F=>{let Q=(E,b)=>{let M=[],R={},k=["$op","$bzId","$parentKey"],L=["$relation","$entity","$id",...k];for(let N in E)if(!k.includes(N)&&!(L.includes(N)&&!b))if(!N.includes("$")&&(isObject(E[N])||Array.isArray(E[N]))){let J=E[N];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Qe={$path:N,...Q(ce),...ce.$filter&&{$as:ce.$bzId}};M.find(U=>U.$path===Qe.$path&&!U.$filter)||(M=[...M,Qe]);});else {let ce={$path:N,...Q(J),...!J.$filter&&{$as:J.$bzId}};M=[...M,ce];}}else R[N]=E[N];return {...R,$fields:M}};return F.map(E=>Q(E,!0))})(Array.isArray(e)?e:[e]),p=(await je(a,t,{...r,query:{...r.query,returnNulls:!0}},i)).bql.res,l=(F,Q)=>{let E=F.$id||F.id||F.$bzId;if(F.$objectPath){let{$objectPath:b}=F,M=b?.beforePath||"root",R=Array.isArray(b.ids)?`[${b.ids}]`:b.ids;return {beforePath:`${M}.${R}___${b.key}`,ids:E,key:Q}}else return {beforePath:"root",ids:E,key:Q}},d=(F,Q)=>{let E=F?.beforePath||"root";if(typeof E!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let b=(Array.isArray(F?.ids)?`[${F?.ids}]`:F?.ids);return `${E}.${b}___${F?.key}`},s=F=>{if(F.includes("[")&&F.includes("]")){let[Q,E,b]=F.split(/[[\]]/);return E.split(",").map(R=>`${Q}${R}${b}`)}else return [F]},f={};(F=>produce(F,Q=>traverse(Q,({key:E,parent:b})=>{if(b&&E&&b.$id&&!E.includes("$")){let M=l(b,E),R=d(M);if(Array.isArray(b[E])){let k=[];b[E].forEach(L=>{isObject(L)?(L.$objectPath=M,k.push(L.$id.toString())):L&&k.push(L.toString());}),f[R]={$objectPath:M,$ids:k};}else {let k=b[E];isObject(k)?(f[R]={$objectPath:M,$ids:[k.$id.toString()]},k.$objectPath=M):k?f[R]={$objectPath:M,$ids:[k.toString()]}:k===null&&(f[R]=null);}}})))(p||{});let $=F=>produce(F,Q=>traverse(Q,({key:E,value:b,parent:M})=>{M&&E&&!E.includes("$")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(M)&&(Array.isArray(M[E])?M[E].forEach(R=>{typeof R!="string"&&(R.$objectPath=l(M,E),R.$parentIsCreate=M.$op==="create",R[fo]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[E])&&(M[E].$parentIsCreate=M.$op==="create",M[E][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[E].$objectPath=l(M,E)));})),y=$(e),m=F=>{let Q=[];return F.forEach(b=>{if(!b.$id&&!b.id&&!b.$tempId)if(b.$filter){let M=d({...b.$objectPath,key:b.$bzId}),R=f[M];R&&(Array.isArray(R.$ids)?R.$ids:[R.$ids]).forEach(L=>{let N={...b,$id:L,$bzId:`T4_${v4()}`,$filterBzId:b.$bzId};Q.push(N);});}else {let M=d(b.$objectPath),R=f[M];R?R?.$ids?.forEach(k=>{let L={...b,$id:k,$bzId:`T4_${v4()}`};Q.push(L);}):Q.push(b);}else Q.push(b);}),Q.map(b=>{let M={...b};return o(M,!0).forEach(R=>{let k=Array.isArray(M[R])?M[R]:[M[R]],L=m(k);M[R]=L;}),M})},B=m(Array.isArray(y)?y:[y]),w=$(B),S=(F=>{let Q=E=>{let b=U=>{let ee=[],z=[],P=[];return U.forEach(j=>{let se=o(j,!0);if(se.length>0){let I=!1;se.forEach(_=>{(Array.isArray(j[_])?j[_]:[j[_]]).filter(Y=>!Y.$id&&!Y.id&&typeof j=="object").length&&(I=!0);}),I?ee.push(j):z.push(j);}else j.$id?P.push({...j,$bzId:j.$tempId||j.$bzId}):P.push({...j,$bzId:j.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:P}},{operationWithMultiples:M,operationWithoutMultiples:R,otherOps:k}=b(E),L=U=>{let z=(()=>{let _={};for(let re in U){let v=q(t,U);!re.startsWith("$")&&v.dataFields?.find(Y=>Y.path===re)&&(_[re]=U[re]);}return _})(),P=Object.keys(U),j=o(U,!0),se=[],I=(_,re)=>{if(_===j.length){let Y={...re};P.forEach(ne=>{ne.startsWith("$")&&(Y[ne]=U[ne]);}),se.push({...Y,...z});return}let v={...re,[j[_]]:U[j[_]],...Fe(re),...z};I(_+1,v),I(_+1,re);};return I(0,{...Fe(U)}),se},N=[];return M.forEach(U=>{let ee=L(U),z=[];ee.forEach(P=>{let j=o(P,!0);if(P.$op==="create")z.push(P);else if(P.$id){let se=d(P.$objectPath),I=[];if(j.forEach(_=>{let re=`${se.includes("undefined")?"root":se}.${P.$id}${Ht}${_}`,v=f[re];P[_].filter(ne=>ne.$op==="unlink"||ne.$op==="delete"||ne.$op==="update").length>0?v?.$ids&&I.push({key:_,ids:v.$ids}):I.push({key:_,ids:[""]});}),I.length===j.length&&!z.find(_=>_.$id===P.$id))z.push(P);else {let _={...P,$bzId:P.$tempId||`T4_${v4()}`};j.forEach(v=>{let Y=P[v].filter(ne=>ne.$id);Y.length>0?_[v]=Y:_[v]=void 0;}),o(_,!0).length>0&&z.push(_);}}else if(P.$objectPath){let se=d(P.$objectPath),I=f[se]?.$ids||[];I.forEach(_=>{let re=[];j.forEach(v=>{let Y=`${se}.${_}${Ht}${v}`,ne=f[Y];ne&&re.push({key:v,ids:ne.$ids});}),j.length===0?I.filter(Y=>!z.find(ne=>ne.$id===Y)).forEach(Y=>{z.push({...P,$id:Y,$bzId:P.$tempId||`PQT2_${v4()}`});}):re.length===j.length&&!z.find(v=>v.$id===_)&&(j.forEach(v=>{let Y=`${d(P.$objectPath)}.${_}${Ht}${v}`,ne=f[Y]?.$ids||[],An=P[v].find(De=>!De.$id),Jt=[...ne.map(De=>({...An,$id:De,$objectPath:{beforePath:P.$objectPath.beforePath,ids:De,key:v}})),...P[v].filter(De=>De.$id)];Jt.length>0&&(P[v]=Jt);}),z.push({...P,$id:_,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else z.push(P);}),z.forEach(P=>{N.push(P);});}),[...N,...R,...k].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let P=Array.isArray(ee[z])?ee[z]:[ee[z]],j=Q(P);ee[z]=j;}),ee})};return Q(F)})(Array.isArray(w)?w:[w]),C=F=>F.map(Q=>{let E=o(Q,!0),b={...Q};return E.forEach(M=>{let R=Array.isArray(Q[M])?Q[M]:[Q[M]],k=[],L=[],N=[],J={},ce=ft(t,Q,M);R.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?L=[...L,...I.$id]:L.push(I.$id)):I.$op==="create"&&ce==="ONE"&&I.id?(J=I,Array.isArray(I.id)?N=[...L,...I.id]:N.push(I.id)):k.push(I);});let Qe=d(J.$objectPath),ee=s(Qe).map(I=>f[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I?.$ids||[]];});let P=z.filter(I=>!L.includes(I)),j=L.filter(I=>!z.includes(I)),se=Fe(J);P.length>0&&k.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...se}),j.length>0&&j.forEach(I=>{k.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${v4()}`,...se});}),N.length>0&&N.forEach(I=>{k.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${v4()}`,...se});}),b[M]=C(k);}),b}),A=$(C($(S)));(F=>produce(F,Q=>traverse(Q,E=>{let{key:b,value:M,parent:R}=E;b&&R&&!b?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(R)&&(Array.isArray(M)?M:[M]).forEach(L=>{let N=L.$filter?{...L.$objectPath,key:L.$filterBzId}:L.$objectPath,J=d(N),ce=f[J],Qe=(z,P)=>z.every(j=>P.includes(j)),U=L.$id?Array.isArray(L.$id)?Qe(L.$id,ce&&ce.$ids?ce.$ids:[]):ce?.$ids?.includes(L.$id):ce,ee=ft(t,R,L.$objectPath.key);if(L.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(L.$objectPath)}" because it is already occupied.`);if(L.$op)switch(L.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${L.$id}" because it is already linked to $id:"${R.$id}"`);break;}});})))(A);let W=(F=>produce(F,Q=>traverse(Q,E=>{let{value:b,meta:M}=E;isObject(b)&&(b[Symbol.for("path")]=M.nodePath,delete b.$objectPath,delete b.$parentIsCreate);})))(A);return [...Array.isArray(W)?W:[W]].sort((F,Q)=>F.$op==="create"&&Q.$op!=="create"?-1:F.$op!=="create"&&Q.$op==="create"?1:0)};var En=(e,t)=>produce(e,i=>at(t,i)),at=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>at(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||mo(e,t,o,i);});},mo=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(a=>a.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let c=i.linkFields?.find(a=>a.path===r);if(c){let a=c.oppositeLinkFieldsPlayedBy[0]?.thing;at(e,o,a);return}if(i.thingType==="relation"){let a=i.roles[r];if(!a)throw new Error(`[Schema] Role ${r} in ${i.name} is not defined`);let[h]=a.playedBy||[];if(!h)throw new Error(`Role ${a.path} in ${i} is not played by anything`);at(e,o,h.thing);}};var wn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(h=>Kt(h,!0)),a=(await je(n,t,r,i)).bql.res;return o.map((h,p)=>{let l=G(t,h.$thing);return Tn({mut:h,node:a[p],schema:t,thing:l})})},Mn=new Set(["$op","$bzId","$parentKey"]),go=new Set(["$relation","$entity","$id",...Mn]),Kt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(Mn.has(o)||go.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Kt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Kt(n,!1)});}return i.$fields=Object.values(r),i},Tn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Sn(o),c=Bo(r);if(Array.isArray(t))return t.map(h=>{let p=c[h.$id];return p?Bn({mut:h,node:p,schema:i,thing:o,...n}):h});let a=c[t.$id];return Bn({mut:t,node:a,schema:i,thing:o,...n})},Bn=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}=e,{$fields:h,...p}=t;if(!r)return p;let l=Qn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}),d={...p,[Ae]:l};for(let s in t){if(s.startsWith("$"))continue;let f=t[s];if(n[s]||!f||typeof f!="object"){d[s]=f;continue}let $=c[s]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[s]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${s}"`);let y=G(i,$);d[s]=Tn({mut:f,schema:i,node:r[s],thing:y});}return d},Qn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}=e,h=t||Eo(o),p={$id:r.$id};return h.forEach(l=>{let d=typeof l!="string",s=d?l.$path:l,f=r[s];if(n[s]){p[s]=f;return}let $=c[s]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[s]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${s}"`);if(!d){f&&(p[s]=Array.isArray(f)?f.map(Fn):Fn(f));return}let y=G(i,$),m=Sn(y);p[s]=Array.isArray(f)?f.map(B=>bn({...m,$fields:l.$fields,value:B,schema:i,thing:y})):bn({...m,$fields:l.$fields,value:f,schema:i,thing:y});}),p},Eo=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},Fn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},bn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return Qn({...e,node:t})},Sn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},Bo=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var Ln=he,Ne=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Fo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),bo=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),wo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Mo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),To=async e=>Object.keys(e.bql.current).length?Et(e.bql.current,e.schema,e.config):Et(e.bql.raw,e.schema,e.config),Qo=async e=>gn(e.bql.current,e.schema,e.config,e.handles),So=async e=>wn(e.bql.current,e.schema,e.config,e.handles),Lo=async e=>Lr(e.bql.current,e.schema),Ro=async e=>Cr(e.bql.things,e.bql.edges,e.schema),Co=async e=>br(e.typeDB.tqlMutation,e.handles,e.config),Do=async e=>wr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Ao=()=>!0,Io=e=>Pe(e.bql.current),Te=H("error","error",V((e,t)=>({...e,error:t.error}))),ko=we("stringify",{stringify:Z(async e=>En(e.bql.raw,e.schema),H("done","enrich",V(Ne)),Te),enrich:Z(To,H("done","preQuery",bt(Ao),V(Ne)),H("done","parseBQL",V(Ne)),Te),preQuery:Z(Qo,H("done","preHookDependencies",bt(Io),V(Ne)),H("done","parseBQL",V(Ne)),Te),preHookDependencies:Z(So,H("done","enrich",V(Ne)),Te),parseBQL:Z(Lo,H("done","buildMutation",V(bo)),Te),buildMutation:Z(Ro,H("done","runMutation",V(wo)),Te),runMutation:Z(Co,H("done","parseMutation",V(Mo)),Te),parseMutation:Z(Do,H("done","success",V(Fo)),Te),success:Ln(),error:Ln()},e=>e),Oo=async e=>new Promise((t,r)=>{ye(ko,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),Rn=async(e,t,r,i)=>Oo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Ut=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 i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o,providerConfig:i.providerConfig});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let c=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(c)}try{let c=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:c});}catch(c){let a=`[BORM:${i.provider}:${i.dbName}:session] ${(c.messageTemplate?._messageBody()||c.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,c]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let a=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await c.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:c,session:a});}catch(a){let h=`[BORM:${i.provider}:${i.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let r=ir(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()=>(await this.#e(),Zt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...ct.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[c,a]=await tryit(je)(n,this.schema,i,this.dbHandles);if(c){let p=new Error(c.error);throw p.stack=c.error.stack,p}let h=a.bql.res;return o?h:h[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...ct.mutation,...this.config.mutation,...r}},[o,n]=await tryit(Rn)(t,this.schema,i,this.dbHandles);if(o){let a=new Error(o.error.message);throw a.stack=o.error.stack,a}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Kc=Ut;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
111
|
+
`;return await t.query(n)};var sn=e=>{let{res:t,queries:r}=e;return t.map((o,i)=>an(r[i],o))},an=(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 Ct(e,t[0])}if(t.length>=1)return t.map(r=>Ct(e,r))}else throw new Error("res is unexpectedly not an array")},Ct=(e,t)=>{let r={[re]:t.$$queryPath,$id:t.$id,$thing:nr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(n=>{let o=n.$as,i=t[o];n.$path==="id"&&e.$idNotIncluded||(r[o]=ho(n,i));}),r},ho=(e,t)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:r}=e[ne];return e[ne].cardinality==="ONE"&&on(t,r),on(t,r)??null}return e.$justId?e.$filterByUnique||e[ne].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[ne].cardinality==="ONE"?Ct(e,t[0]):an(e,t)},on=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(o=>new Date(o).toISOString());return isArray(e)?n:n[0]}return e};var ln=e=>{let{queries:t,schema:r}=e;return t.map(n=>po({query:n,schema:r}))},po=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:u}=t;if(o.length===0)return null;let $=r.entities[n]||r.relations[n];if(!$)throw new Error(`Schema for ${n} not found`);let c=t[re],d=cn(c),l=dn(o.filter(g=>g.$fieldType==="data")),p=un(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),h=[...d,...l,...p].join(`,
|
|
112
|
+
`),f=$o(t,$),y=i?`WHERE ${$e(he(i,n,r))}`:"WHERE id",m=u?_e(u):"",E=typeof s=="number"?`LIMIT ${s}`:"",B=typeof a=="number"?`START ${a}`:"";return `SELECT ${h} ${f} ${y} ${m} ${E} ${B}`},$o=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>X(a)),o=(a,s)=>`${a}:\`${s}\``,i=a=>n.flatMap(s=>a.map(u=>o(s,u))).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")},cn=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],dn=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}\``),un=(e,t)=>e.map(r=>{let n=cn(r[re]),o=dn(r.$fields.filter(l=>l.$fieldType==="data")),i=un(r.$fields.filter(l=>l.$fieldType==="link"||l.$fieldType==="role"),t),a=[...n,...o,...i].join(`,
|
|
113
|
+
`),s=`FROM $parent.\`${r[ne].path}\`[*]`,u=r.$filter?`WHERE ${$e(he(r.$filter,r.$thing,t))}`:"WHERE id",$=r.$sort?_e(r.$sort):"",c=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${s} ${u} ${$} ${c} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var Ot=N("error","error",x((e,t)=>({...e,error:t.error}))),fo=ye("build",{build:W(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return rn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return ln({queries:e.bql.queries,schema:e.schema})},N("done","run",x((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Ot),run:W(async e=>nn({client:e.client,queries:ue(e.surql.queries)}),N("done","parse",x((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Ot),parse:W(async e=>sn({res:ue(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),N("done","success",x((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Ot),success:ie(),error:ie()},e=>e),mo=async e=>new Promise((t,r)=>{fe(fo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),hn=async(e,t,r,n)=>mo({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var kt="___",$n=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Eo({query:n,schema:r}))},Eo=e=>{let{query:t,schema:r}=e,{$path:n,$thing:o,$filter:i,$fields:a,$sort:s,$offset:u,$limit:$,$id:c}=t;if(!n)throw new Error("Path is not defined");let d=[],l=t[re];if(d.push("match"),d.push(`$${n} isa ${o};`),i||c){let f=Ye(r,t),y={...i,...c?{[f]:c}:{}},m=Nt({$filter:y,$var:n,$thing:o,schema:r,depth:0});d.push(`
|
|
114
|
+
${m}`);}let p=jt({schema:r,$thing:o,$var:n,$sort:s,depth:0});p&&d.push(p.match);let h=`M_${v4()}`;if(d.push(`?queryPath${h} = "${l}";`),d.push("fetch"),d.push(`?queryPath${h} as "queryPath";`),a){let f=a.filter(E=>E.$fieldType==="data");f&&f.length>0&&d.push(...Pt(f,n,0));let y=a.filter(E=>E.$fieldType==="link");y&&y.length>0&&d.push(...xt(y,n,n,0,r));let m=a.filter(E=>E.$fieldType==="role");m&&m.length>0&&d.push(...qt(m,n,n,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
|
|
115
|
+
offset ${u};`),typeof $=="number"&&d.push(`
|
|
116
|
+
limit ${$};`),d.join(`
|
|
117
|
+
`)},Pt=(e,t,r)=>{let n=[],o=[],i=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ne].contentType==="FLEX"&&i.push({path:e[c][ne].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let a=n.join(", "),u=`$metadata:{as:[${o.join(",")}]}`,$=[M(`$${t} as "${t}.${u}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(c=>{$.push(M(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),$},qt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:u,$as:$,$justId:c,$idNotIncluded:d,$filterByUnique:l,$thing:p,$sort:h,$offset:f,$limit:y}=s,m=s[re],E=`$metadata:{as:${$},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${E}.${s.$var}": {`,n)),a.push(M("match",i));let B=`${t}${kt}${s.$var}`;if(a.push(M(`$${B} isa ${s.$thing};`,i)),a.push(M(`$${t} (${s.$var}: $${t}${kt}${s.$var}) isa ${s.$intermediary};`,i)),s.$filter||s.$id){let L=Ye(o,s),Q=s.$id?{[L]:s.$id}:{},I={...s.$filter,...Q};a.push(Nt({$filter:I,$var:B,$thing:s.$thing,schema:o,depth:i}));}let g=jt({schema:o,$thing:p,$var:B,$sort:h,depth:i});if(g&&a.push(g.match),u){let L=`M_${v4()}`;a.push(M(`
|
|
118
|
+
?queryPath${L} = "${m}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${L} as "queryPath";`,i));let Q=u?.filter(j=>j.$fieldType==="data");Q&&Q.length>0&&a.push(...Pt(Q,B,i));let I=u?.filter(j=>j.$fieldType==="link");I&&I.length>0&&a.push(...xt(I,B,`${t}.${s.$var}`,i,o));let A=u?.filter(j=>j.$fieldType==="role");A&&A.length>0&&a.push(...qt(A,B,`${t}.${s.$var}`,i,o));}g&&a.push(g.sort),typeof f=="number"&&a.push(M(`offset ${f};`,i)),typeof y=="number"&&a.push(M(`limit ${y};`,i)),a.push(M("};",n));}return a},xt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:u,$as:$,$justId:c,$idNotIncluded:d,$filterByUnique:l,$playedBy:p,$thing:h,$sort:f,$offset:y,$limit:m}=s,E=s[re],B=`$metadata:{as:${$},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${B}.${s.$var}": {`,n)),a.push(M("match",i));let g=`${t}${kt}${s.$var}`;if(a.push(M(`$${g} isa ${s.$thing};`,i)),s.$filter||s.$id){let Q=Ye(o,s),I=s.$id?{[Q]:s.$id}:{},A={...s.$filter,...I};a.push(Nt({$filter:A,$var:g,$thing:s.$thing,schema:o,depth:i}));}let L=jt({schema:o,$thing:h,$var:g,$sort:f,depth:i});if(L&&a.push(L.match),s.$target==="role"?a.push(M(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${g}) isa ${s.$intermediary};`,i)):a.push(M(`$${g} (${s.$plays}: $${t});`,i)),u){let Q=`M_${v4()}`;a.push(M(`?queryPath${Q} = "${E}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${Q} as "queryPath";`,i));let I=u?.filter(K=>K.$fieldType==="data");I&&I.length>0&&a.push(...Pt(I,g,i));let A=u?.filter(K=>K.$fieldType==="link");A&&A.length>0&&a.push(...xt(A,g,`${t}.${s.$var}`,i,o));let j=u?.filter(K=>K.$fieldType==="role");j&&j.length>0&&a.push(...qt(j,g,`${t}.${s.$var}`,i,o));}L&&a.push(L.sort),typeof y=="number"&&a.push(M(`offset ${y};`,i)),typeof m=="number"&&a.push(M(`limit ${m};`,i)),a.push(M("};",n));}return a},Bo=(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,...o}=e,i=pn(o,r);return n&&(i.$not=pn(n,r)),i},pn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,o])=>{let i=t[n]||n;r[i]=o;}),r},Nt=e=>{let{$filter:t,$var:r,$thing:n,schema:o,depth:i}=e,a=Bo(t,Y(o,n)),{$not:s,...u}=a,$=Y(o,n),c=[];return Object.entries(s||{}).forEach(([d,l])=>{if(d.startsWith("$"))return;if($.dataFields?.find(f=>f.dbPath===d)){l===null?c.push(M(`$${r} has ${d} $${d}_${v4()};`,i)):Array.isArray(l)?l.forEach(f=>{c.push(M(`not { $${r} has ${d} ${ce(f)}; };`,i));}):c.push(M(`not { $${r} has ${d} ${ce(l)}; };`,i));return}let h=$.linkFields?.find(f=>f.path===d);if(h){let[f]=h.oppositeLinkFieldsPlayedBy,m=Y(o,f.thing).idFields?.[0];if(!m)throw new Error(`"${f.thing}" does not have an id field`);if(h.target==="relation")l===null?c.push(M(`(${h.plays}: $${r}) isa ${h.relation};`,i)):Array.isArray(l)?l.forEach(E=>{c.push(M(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(E)}; };`,i));}):c.push(M(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(l)}; };`,i));else {let E=`${f.thing}_${v4()}`;l===null?c.push(M(`$${E} isa ${f.thing}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`,i)):Array.isArray(l)?l.forEach(B=>{c.push(M(`not { $${E} isa ${f.thing}, has ${m} ${ce(B)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));}):c.push(M(`not { $${E} isa ${f.thing}, has ${m} ${ce(l)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));}return}if($.thingType==="relation"){let f=$.roles[d];if(f){let[y]=f.playedBy||[],E=Y(o,y.thing).idFields?.[0];if(!E)throw new Error(`"${y.thing}" does not have an id field`);let B=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;l===null?(c.push(M(`$${L} isa ${n};`,i)),c.push(M(`$${L} (${y.plays}: ${B});`,i)),c.push(M(`$${r} is $${L};`,i))):Array.isArray(l)?l.forEach(Q=>{c.push(M(`$${L} isa ${n};`,i)),c.push(M(`not { $${B} isa ${y.thing}, has ${E} ${ce(Q)}; $${L} (${y.plays}: $${B}); };`,i)),c.push(M(`$${r} is $${L};`,i));}):(c.push(M(`$${L} isa ${n};`,i)),c.push(M(`not { $${B} isa ${y.thing}, has ${E} ${ce(l)}; $${L} (${y.plays}: $${B}); };`,i)),c.push(M(`$${r} is $${L};`,i)));return}}}),Object.entries(u).forEach(([d,l])=>{if(d.startsWith("$"))return;if($.dataFields?.find(f=>f.dbPath===d)){if(l===null)c.push(M(`not { $${r} has ${d} $${d}_${v4()}; };`,i));else if(Array.isArray(l)){let f=l.map(m=>`$${r} has ${d} ${ce(m)};`),y=st(f);y&&c.push(M(y,i));}else c.push(M(`$${r} has ${d} ${ce(l)};`,i));return}let h=$.linkFields?.find(f=>f.path===d);if(h){let[f]=h.oppositeLinkFieldsPlayedBy,m=Y(o,f.thing).idFields?.[0];if(!m)throw new Error(`"${f.thing}" does not have an id field`);if(h.target==="relation")if(l===null)c.push(M(`not { (${h.plays}: $${r}) isa ${h.relation}; };`,i));else if(Array.isArray(l)){let E=l.map(g=>`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(g)};`),B=st(E);B&&c.push(M(B,i));}else c.push(M(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(l)};`,i));else {let E=`${f.thing}_${v4()}`;if(l===null)c.push(M(`not { $${E} isa ${f.thing}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));else if(Array.isArray(l)){let B=l.map(L=>`$${E} isa ${f.thing}, has ${m} ${ce(L)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`),g=st(B);g&&c.push(M(g,i));}else c.push(M(`$${E} isa ${f.thing}, has ${m} ${ce(l)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`,i));}return}if($.thingType==="relation"){let f=$.roles[d];if(f){let[y]=f.playedBy||[],E=Y(o,y.thing).idFields?.[0];if(!E)throw new Error(`"${y.thing}" does not have an id field`);let B=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;if(l===null)c.push(M(`$${L} isa ${n};`,i)),c.push(M(`not { $${L} (${y.plays}: ${B}); };`,i)),c.push(M(`$${r} is $${L};`,i));else if(Array.isArray(l)){let Q=l.map(A=>`$${B} isa ${y.thing}, has ${E} ${ce(A)}; $${L} (${y.plays}: $${B});`),I=st(Q);I&&(c.push(M(`$${L} isa ${n};`,i)),c.push(M(I,i)),c.push(M(`$${r} is $${L};`,i)));}else c.push(M(`$${L} isa ${n};`,i)),c.push(M(`$${B} isa ${y.thing}, has ${E} ${ce(l)}; $${L} (${y.plays}: $${B});`,i)),c.push(M(`$${r} is $${L};`,i));return}}throw new Error(`"${n}" does not have property "${d}"`)}),c.join(`
|
|
119
|
+
`)},st=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ce=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,Fo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},jt=e=>{let{$var:t,$thing:r,schema:n,$sort:o,depth:i}=e,a=Y(n,r),s=[],u=[];if(o?.forEach($=>{let c=Fo($),d=a.dataFields?.find(h=>h.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let l=`${c.field}_${v4()}`;s.push(M("{",i)),s.push(M(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),s.push(M("not {",i+1)),s.push(M(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),s.push(M(`$${l}_2 < $${l}_1;`,i+2)),s.push(M("};",i+1)),s.push(M(`?${l}_ = $${l}_1;`,i+1)),s.push(M("} or {",i)),s.push(M(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),s.push(M(`?${l}_ = "~";`,i+1)),s.push(M("};",i)),s.push(M(`?${l} = ?${l}_;`,i));let p=c.desc?"desc":"asc";u.push(`?${l} ${p}`);}),s.length!==0)return {match:s.join(""),sort:M(`sort ${u.join(", ")};`,i)}};var mn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:o,rawTqlRes:i}=e;if(t){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((a,s)=>{let u=r[s],$=t[s];return To(a,u,$,n,o)})},To=(e,t,r,n,o)=>e.length===0?null:r.$filterByUnique?fn(e[0],t,n,o):e.map(i=>fn(i,t,n,o)),fn=(e,t,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:a,roleFields:s,schemaValue:u}=_t(e,r),$=zt(o,i,n),c=Wt(a,r,n),d=Ut(s,r,n),l=t?.$fields?.every(h=>!i?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...d,...u,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?$.id:t.$id}:{},...l?Object.fromEntries(Object.entries($).filter(([h])=>!i?.idFields?.includes(h))):$}},_t=(e,t)=>{let r=Object.keys(e),n=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let h=p.replace(/\.\$multiVal$/,""),f=e[p][0][h].attribute;e[n][h]=f;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let s=i.type,u={$thing:s.label,$thingType:s.root,[re]:e.queryPath.value},$={[`$${u.$thingType}`]:u.$thing},c=q(t,$),d=r.filter(p=>{let h=ue(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some(f=>f.path===h)}).map(p=>{let h=ue(p.split(".").pop()),f=ue(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:f.cardinality}}),l=r.filter(p=>{let h=p.split(".").pop();return h&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(p=>{let h=ue(p.split(".").pop());return {$roleFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:i,schemaValue:u,currentSchema:c,linkFields:d,roleFields:l}},zt=(e,t,r)=>{let{$metaData:n}=e,{as:o}=Mo(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,s])=>{let u=t.dataFields?.find(l=>l.path===a||l.dbPath===a),$=a==="id",c=Array.isArray(o)?o.find(l=>l[a])?.[a]:a,d;if(u?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),$)return [[c,d],["$id",d]].filter(([l,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=s.map(l=>`${l.value}Z`):u.contentType==="FLEX"?d=s.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):u.contentType==="JSON"?d=s.map(l=>l.value&&JSON.parse(l.value)):d=s.map(l=>l.value);}return [[c,d]].filter(([l,p])=>p!==void 0)}).flat();return Object.fromEntries([...i])},Ut=(e,t,r)=>{let n={};return e.forEach(o=>{let{$roleFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=yn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=_t(p,t),B=zt(h,f,r);if($==="T")return B.id;{let g=Wt(y,t,r),L=Ut(m,t,r),Q={...B};return c==="true"&&f?.idFields?.forEach(I=>delete Q[I]),{...Q,...g,...L,...E}}});l.length>0?n[u]=s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[u]=null);}),n},Wt=(e,t,r)=>{let n={};return e.forEach(o=>{let{$linkFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=yn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=_t(p,t),B=zt(h,f,r);if($==="T")return B.id;{let g=Wt(y,t,r),L=Ut(m,t,r),Q={...B};return c==="true"&&f.idFields?.forEach(I=>delete Q[I]),{...Q,...g,...L,...E}}});n[u]=l.length>0?s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},yn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),s=e.match(n),u=e.match(o);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:u?u[1]:null}},Mo=e=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,s,u)=>/^{.*}$/.test(u)?`:${u}`:`:${s}"${u}"`),i=i.replace(/\[([^\]]+)\]/g,(a,s)=>`[${s.split(",").map(u=>u.trim().startsWith("{")&&u.trim().endsWith("}")?u.trim():`"${u.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var at=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!o)throw new Error("Client not found");n=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:n});}return {client:o,session:n}};var gn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,o=new TypeDBOptions;o.infer=!0;let{session:i}=await at(r,n),a=await i.transaction(TransactionType.READ,o),[s,u]=await tryit(parallel)(t.length,t,async $=>await a.query.fetch($).collect());if(s){await a.rollback();let $=s;throw new Error(`Error running TQL query: ${$.errors}`)}return await a.close(),u};var Do=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Io=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ao=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Vt=N("error","error",x((e,t)=>({...e,error:t.error}))),Co=ye("build",{build:W(async e=>$n({queries:e.bql.queries,schema:e.schema}),N("done","run",x(Io)),Vt),run:W(async e=>gn({dbHandles:e.handles,tqlRequest:ue(e.tql.queries),config:e.config}),N("done","parse",x(Ao)),Vt),parse:W(async e=>mn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ue(e.tql.res)}),N("done","success",x(Do)),Vt),success:ie(),error:ie()},e=>e),Oo=async e=>new Promise((t,r)=>{fe(Co,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),En=async(e,t,r,n,o)=>Oo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:o,error:null});var ko=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Ht=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,lt=N("error","error",x((e,t)=>({...e,error:t.error}))),Po=ye("enrich",{enrich:W(async e=>Xr(e.bql.raw,e.schema),N("done","adapter",x(ko)),lt),adapter:W(async e=>{let t={};e.bql.queries?.forEach((s,u)=>{let $=e.bql.raw[u],c=Y(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let p=e.handles.typeDB?.get(d)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let p=e.handles.surrealDB?.get(d)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let l=t[d];l.rawBql.push($),l.bqlQueries.push(s),l.indices.push(u);});let r=Object.values(t),n=r.map(s=>{if(s.db==="typeDB")return En(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return hn(s.bqlQueries,e.schema,e.config,s.client);throw new Error(`Unsupported DB "${JSON.stringify(s,null,2)}"`)}),o=await Promise.all(n),i=r.flatMap((s,u)=>{let $=o[u];return s.indices.map((c,d)=>({index:c,result:$[d]}))});return i.sort((s,u)=>s.index<u.index?-1:s.index>u.index?1:0),i.map(({result:s})=>s)},N("done","postHooks",x(Ht)),lt),postHooks:W(async e=>en(e.schema,ue(e.bql.queries),ue(e.bql.res)),N("done","clean",x(Ht)),lt),clean:W(async e=>Gr(e.config,ue(e.bql.res)),N("done","success",x(Ht)),lt),success:ie(),error:ie()},e=>e),qo=async e=>new Promise((t,r)=>{fe(Po,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>qo({bql:{raw:e},schema:t,config:r,handles:n,error:null});var Kt="___",xo=Symbol.for("grandChildOfCreate"),Bn=async(e,t,r,n)=>{let o=(w,b)=>Object.keys(w).filter(F=>!F.startsWith("$")&&w[F]!==void 0?b?!q(t,w).dataFields?.find(T=>T.path===F):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let i=[];if(traverse(e,({parent:w,key:b,value:F})=>{w&&b&&!b.includes("$")&&isObject(w)?(Array.isArray(w[b])?w[b]:[w[b]]).forEach(T=>{if(isObject(T)){if(w.$op!=="create")i.includes(T.$op)||i.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!w&&isObject(F)&&(i.includes(F.$op)||i.push(F.$op));}),!i.includes("delete")&&!i.includes("unlink")&&!i.includes("replace")&&!i.includes("update")&&!i.includes("link"))return;let s=(w=>{let b=(F,S)=>{let T=[],D={},k=["$op","$bzId","$parentKey"],R=["$relation","$entity","$id",...k];for(let z in F)if(!k.includes(z)&&!(R.includes(z)&&!S))if(!z.includes("$")&&(isObject(F[z])||Array.isArray(F[z]))){let J=F[z];if(Array.isArray(J)&&J.length>0)J.forEach(pe=>{let Le={$path:z,...b(pe),...pe.$filter&&{$as:pe.$bzId}};T.find(H=>H.$path===Le.$path&&!H.$filter)||(T=[...T,Le]);});else {let pe={$path:z,...b(J),...!J.$filter&&{$as:J.$bzId}};T=[...T,pe];}}else D[z]=F[z];return {...D,$fields:T}};return w.map(F=>b(F,!0))})(Array.isArray(e)?e:[e]),$=(await ze(s,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,c=(w,b)=>{let F=w.$id||w.id||w.$bzId;if(w.$objectPath){let{$objectPath:S}=w,T=S?.beforePath||"root",D=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${T}.${D}___${S.key}`,ids:F,key:b}}else return {beforePath:"root",ids:F,key:b}},d=(w,b)=>{let F=w?.beforePath||"root";if(typeof F!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=b||(Array.isArray(w?.ids)?`[${w?.ids}]`:w?.ids);return `${F}.${S}___${w?.key}`},l=w=>{if(w.includes("[")&&w.includes("]")){let[b,F,S]=w.split(/[[\]]/);return F.split(",").map(D=>`${b}${D}${S}`)}else return [w]},p={};(w=>produce(w,b=>traverse(b,({key:F,parent:S})=>{if(S&&F&&S.$id&&!F.includes("$")){let T=c(S,F),D=d(T);if(Array.isArray(S[F])){let k=[];S[F].forEach(R=>{isObject(R)?(R.$objectPath=T,k.push(R.$id.toString())):R&&k.push(R.toString());}),p[D]={$objectPath:T,$ids:k};}else {let k=S[F];isObject(k)?(p[D]={$objectPath:T,$ids:[k.$id.toString()]},k.$objectPath=T):k?p[D]={$objectPath:T,$ids:[k.toString()]}:k===null&&(p[D]=null);}}})))($||{});let f=w=>produce(w,b=>traverse(b,({key:F,value:S,parent:T})=>{T&&F&&!F.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(T)&&(Array.isArray(T[F])?T[F].forEach(D=>{typeof D!="string"&&(D.$objectPath=c(T,F),D.$parentIsCreate=T.$op==="create",D[xo]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[F])&&(T[F].$parentIsCreate=T.$op==="create",T[F][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[F].$objectPath=c(T,F)));})),y=f(e),m=w=>{let b=[];return w.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let T=d({...S.$objectPath,key:S.$bzId}),D=p[T];D&&(Array.isArray(D.$ids)?D.$ids:[D.$ids]).forEach(R=>{let z={...S,$id:R,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};b.push(z);});}else {let T=d(S.$objectPath),D=p[T];D?D?.$ids?.forEach(k=>{let R={...S,$id:k,$bzId:`T4_${v4()}`};b.push(R);}):b.push(S);}else b.push(S);}),b.map(S=>{let T={...S};return o(T,!0).forEach(D=>{let k=Array.isArray(T[D])?T[D]:[T[D]],R=m(k);T[D]=R;}),T})},E=m(Array.isArray(y)?y:[y]),B=f(E),L=(w=>{let b=F=>{let S=H=>{let te=[],V=[],P=[];return H.forEach(_=>{let de=o(_,!0);if(de.length>0){let O=!1;de.forEach(U=>{(Array.isArray(_[U])?_[U]:[_[U]]).filter(Z=>!Z.$id&&!Z.id&&typeof _=="object").length&&(O=!0);}),O?te.push(_):V.push(_);}else _.$id?P.push({..._,$bzId:_.$tempId||_.$bzId}):P.push({..._,$bzId:_.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:te,operationWithoutMultiples:V,otherOps:P}},{operationWithMultiples:T,operationWithoutMultiples:D,otherOps:k}=S(F),R=H=>{let V=(()=>{let U={};for(let oe in H){let G=q(t,H);!oe.startsWith("$")&&G.dataFields?.find(Z=>Z.path===oe)&&(U[oe]=H[oe]);}return U})(),P=Object.keys(H),_=o(H,!0),de=[],O=(U,oe)=>{if(U===_.length){let Z={...oe};P.forEach(se=>{se.startsWith("$")&&(Z[se]=H[se]);}),de.push({...Z,...V});return}let G={...oe,[_[U]]:H[_[U]],...we(oe),...V};O(U+1,G),O(U+1,oe);};return O(0,{...we(H)}),de},z=[];return T.forEach(H=>{let te=R(H),V=[];te.forEach(P=>{let _=o(P,!0);if(P.$op==="create")V.push(P);else if(P.$id){let de=d(P.$objectPath),O=[];if(_.forEach(U=>{let oe=`${de.includes("undefined")?"root":de}.${P.$id}${Kt}${U}`,G=p[oe];P[U].filter(se=>se.$op==="unlink"||se.$op==="delete"||se.$op==="update").length>0?G?.$ids&&O.push({key:U,ids:G.$ids}):O.push({key:U,ids:[""]});}),O.length===_.length&&!V.find(U=>U.$id===P.$id))V.push(P);else {let U={...P,$bzId:P.$tempId||`T4_${v4()}`};_.forEach(G=>{let Z=P[G].filter(se=>se.$id);Z.length>0?U[G]=Z:U[G]=void 0;}),o(U,!0).length>0&&V.push(U);}}else if(P.$objectPath){let de=d(P.$objectPath),O=p[de]?.$ids||[];O.forEach(U=>{let oe=[];_.forEach(G=>{let Z=`${de}.${U}${Kt}${G}`,se=p[Z];se&&oe.push({key:G,ids:se.$ids});}),_.length===0?O.filter(Z=>!V.find(se=>se.$id===Z)).forEach(Z=>{V.push({...P,$id:Z,$bzId:P.$tempId||`PQT2_${v4()}`});}):oe.length===_.length&&!V.find(G=>G.$id===U)&&(_.forEach(G=>{let Z=`${d(P.$objectPath)}.${U}${Kt}${G}`,se=p[Z]?.$ids||[],vn=P[G].find(Oe=>!Oe.$id),tr=[...se.map(Oe=>({...vn,$id:Oe,$objectPath:{beforePath:P.$objectPath.beforePath,ids:Oe,key:G}})),...P[G].filter(Oe=>Oe.$id)];tr.length>0&&(P[G]=tr);}),V.push({...P,$id:U,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else V.push(P);}),V.forEach(P=>{z.push(P);});}),[...z,...D,...k].filter(H=>o(H).length>0?!0:H.$op!=="update").map(H=>{let te={...H};return o(te,!0).forEach(V=>{let P=Array.isArray(te[V])?te[V]:[te[V]],_=b(P);te[V]=_;}),te})};return b(w)})(Array.isArray(B)?B:[B]),Q=w=>w.map(b=>{let F=o(b,!0),S={...b};return F.forEach(T=>{let D=Array.isArray(b[T])?b[T]:[b[T]],k=[],R=[],z=[],J={},pe=Et(t,b,T);D.filter(O=>O).forEach(O=>{O.$op==="replace"&&O.$id?(J=O,Array.isArray(O.$id)?R=[...R,...O.$id]:R.push(O.$id)):O.$op==="create"&&pe==="ONE"&&O.id?(J=O,Array.isArray(O.id)?z=[...R,...O.id]:z.push(O.id)):k.push(O);});let Le=d(J.$objectPath),te=l(Le).map(O=>p[O]),V=[];te.filter(O=>O!=null).forEach(O=>{V=[...V,...O?.$ids||[]];});let P=V.filter(O=>!R.includes(O)),_=R.filter(O=>!V.includes(O)),de=we(J);P.length>0&&k.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...de}),_.length>0&&_.forEach(O=>{k.push({...J,$op:"link",$id:O,$bzId:J.$tempId||`T5_${v4()}`,...de});}),z.length>0&&z.forEach(O=>{k.push({...J,$op:"create",id:O,$bzId:J.$tempId||`T6_${v4()}`,...de});}),S[T]=Q(k);}),S}),I=f(Q(f(L)));(w=>produce(w,b=>traverse(b,F=>{let{key:S,value:T,parent:D}=F;S&&D&&!S?.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(D)&&(Array.isArray(T)?T:[T]).forEach(R=>{let z=R.$filter?{...R.$objectPath,key:R.$filterBzId}:R.$objectPath,J=d(z),pe=p[J],Le=(V,P)=>V.every(_=>P.includes(_)),H=R.$id?Array.isArray(R.$id)?Le(R.$id,pe&&pe.$ids?pe.$ids:[]):pe?.$ids?.includes(R.$id):pe,te=Et(t,D,R.$objectPath.key);if(R.$op==="link"&&H&&te==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(R.$objectPath)}" because it is already occupied.`);if(R.$op)switch(R.$op){case"delete":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${R.$id}" because it is not linked to $id:"${D.$id}"`);break;case"update":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${R.$id}" because it is not linked to $id:"${D.$id}"`);break;case"unlink":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${R.$id}" because it is not linked to $id:"${D.$id}"`);break;case"link":if(H)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${R.$id}" because it is already linked to $id:"${D.$id}"`);break;}});})))(I);let K=(w=>produce(w,b=>traverse(b,F=>{let{value:S,meta:T}=F;isObject(S)&&(S[Symbol.for("path")]=T.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(I);return [...Array.isArray(K)?K:[K]].sort((w,b)=>w.$op==="create"&&b.$op!=="create"?-1:w.$op!=="create"&&b.$op==="create"?1:0)};var Fn=(e,t)=>produce(e,n=>dt(t,n)),dt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>dt(e,o,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||jo(e,t,o,n);});},jo=(e,t,r,n)=>{let o=t[r];if(!o)return;let i=n.dataFields?.find(s=>s.path===r);if(i){i.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let a=n.linkFields?.find(s=>s.path===r);if(a){let s=a.oppositeLinkFieldsPlayedBy[0]?.thing;dt(e,o,s);return}if(n.thingType==="relation"){let s=n.roles[r];if(!s)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[u]=s.playedBy||[];if(!u)throw new Error(`Role ${s.path} in ${n} is not played by anything`);dt(e,o,u.thing);}};var wn=async(e,t,r,n)=>{let o=Array.isArray(e)?e:[e],i=o.map(u=>Jt(u,!0)),s=(await ze(i,t,r,n)).bql.res;return o.map((u,$)=>{let c=Y(t,u.$thing);return Ln({mut:u,node:s[$],schema:t,thing:c})})},Sn=new Set(["$op","$bzId","$parentKey"]),zo=new Set(["$relation","$entity","$id",...Sn]),Jt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let n={};for(let o in e){if(Sn.has(o)||zo.has(o)&&!t)continue;let i=e[o];o.startsWith("$")?n[o]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[o]={$path:o,...Jt(i[0],!1)}):isObject(i)&&(r[o]={$path:o,...Jt(i,!1)});}return n.$fields=Object.values(r),n},Ln=e=>{let{mut:t,node:r,schema:n,thing:o}=e,i=Rn(o),a=Wo(r);if(Array.isArray(t))return t.map(u=>{let $=a[u.$id];return $?bn({mut:u,node:$,schema:n,thing:o,...i}):u});let s=a[t.$id];return bn({mut:t,node:s,schema:n,thing:o,...i})},bn=e=>{let{mut:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,{$fields:u,...$}=t;if(!r)return $;let c=Qn({$fields:t.$fields,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}),d={...$,[ke]:c};for(let l in t){if(l.startsWith("$"))continue;let p=t[l];if(i[l]||!p||typeof p!="object"){d[l]=p;continue}let f=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[l]?.playedBy?.[0]?.thing;if(!f)throw new Error(`"${o.name}" does not have field "${l}"`);let y=Y(n,f);d[l]=Ln({mut:p,schema:n,node:r[l],thing:y});}return d},Qn=e=>{let{$fields:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,u=t||Uo(o),$={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",l=d?c.$path:c,p=r[l];if(i[l]){$[l]=p;return}let f=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[l]?.playedBy?.[0]?.thing;if(!f)throw new Error(`"${o.name}" does not have field "${l}"`);if(!d){p&&($[l]=Array.isArray(p)?p.map(Tn):Tn(p));return}let y=Y(n,f),m=Rn(y);$[l]=Array.isArray(p)?p.map(E=>Mn({...m,$fields:c.$fields,value:E,schema:n,thing:y})):Mn({...m,$fields:c.$fields,value:p,schema:n,thing:y});}),$},Uo=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},Tn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},Mn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return Qn({...e,node:t})},Rn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},Wo=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var vt=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var In=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let n=l=>{let p=l.$op,h=`$${l.$bzId}`,f=q(r,l),{idFields:y,defaultDBConnector:m}=f,E=m?.path||l.$thing,B=l.$id,g=y?.[0],L=listify(l,(C,w)=>{if(C.startsWith("$")||C.startsWith("%")||C===g||w===void 0||w===null)return "";let b=f.dataFields?.find(T=>T.path===C);if(!b?.path)return "";let S=b.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(b.contentType))return `has ${S} '${w}'`;if(["NUMBER","BOOLEAN"].includes(b.contentType))return `has ${S} ${w}`;if(b.contentType==="DATE"){if(Number.isNaN(w.valueOf()))throw new Error("Invalid format, Nan Date");return w instanceof Date?`has ${S} ${w.toISOString().replace("Z","")}`:`has ${S} ${new Date(w).toISOString().replace("Z","")}`}if(b.contentType==="FLEX"){let T=`bza${De()}`,D=isArray(w)?w.map(k=>vt(k)):vt(w);if(Array.isArray(D))throw new Error("Array in FLEX fields not supported yet");return `has ${S} $${T}; $${T} '${T}' isa ${S}, has ${D.type}Attribute ${D.value}`}throw new Error(`Unsupported contentType ${b.contentType}`)}).filter(C=>C),Q=`${h}-atts`,I=listify(l,C=>{if(C.startsWith("$")||C.startsWith("%")||C===g)return "";let w=f.dataFields?.find(S=>S.path===C);if(!w?.path)return "";let F=w.dbPath;return `{${Q} isa ${F};}`}).filter(C=>C),A=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,j=B?[`has ${g} ${A}`]:[],K=[...j,...L].filter(C=>C).join(","),me=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[E,...j].filter(C=>C).join(",")};`;if(p==="update"){if(!I.length)throw new Error("update without attributes");return `${h} isa ${[E,...j].filter(C=>C).join(",")}, has ${Q};
|
|
120
|
+
${I.join(" or ")};`}return ""},v=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[E,...j].filter(C=>C).join(",")};`:"";if(Ge(l))return {op:p,deletionMatch:me(),insertionMatch:v(),insertion:p==="create"?`${h} isa ${[E,K].filter(C=>C).join(",")};`:p==="update"&&L.length?`${h} ${L.join(",")};`:"",deletion:p==="delete"?`${h} isa ${E};`:p==="update"&&I.length?`${h} has ${Q};`:""};throw new Error("in attributes")},o=l=>{let p=l.$op,h=q(r,l),f=`$${l.$bzId}`,y=l.$id,m=h.defaultDBConnector?.path||l.$thing,E="roles"in h?listify(h.roles,w=>w):[],B="roles"in h?mapEntries(h.roles,(w,b)=>[w,b.dbConnector?.path||w]):{},g=listify(l,(w,b)=>{if(!E.includes(w))return null;if(!("roles"in h))throw new Error("This should have roles! ");let F=B[w];return Array.isArray(b)?b.map(S=>({path:F,id:S})):{path:F,id:b}}).filter(w=>w).flat(),L=g.map(w=>{if(!w?.path)throw new Error("Object without path");return `${w.path}: $${w.id}`}),Q=g.length>0?`( ${L.join(" , ")} )`:"",I=l[Re];if(!I)throw new Error("[internal error] Symbol edgeType not defined");let A=Q?`${f} ${Q} ${I==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${f} ${I==="linkField"||p==="delete"?`isa ${m}`:""}`,K=()=>A?p==="link"?`${A};`:p==="create"?`${A}, has id '${y}';`:"":"",me=()=>A&&p==="match"?`${A};`:"",v=()=>A?p==="delete"?`${A};`:p==="match"?`${A};`:"":"",C=()=>A?p==="delete"?`${j};`:p==="unlink"?`${f} ${Q};`:"":"";return {deletionMatch:v(),insertionMatch:me(),deletion:C(),insertion:K(),op:""}},i=(l,p)=>{let h=p==="edges"?o:n;if(Array.isArray(l))return l.map(g=>{let{preDeletionBatch:L,insertionMatch:Q,deletionMatch:I,insertion:A,deletion:j}=h(g);return shake({preDeletionBatch:L,insertionMatch:Q,deletionMatch:I,insertion:A,deletion:j},K=>!K)}).filter(g=>g);let{preDeletionBatch:f,insertionMatch:y,deletionMatch:m,insertion:E,deletion:B}=h(l);return shake({preDeletionBatch:f,insertionMatch:y,deletionMatch:m,insertion:E,deletion:B},g=>!g)},a=i(e),s=Array.isArray(a)?a:[a],u=i(t,"edges"),$=Array.isArray(u)?u:[u],c=[...s,...$];return shake({insertionMatches:c.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:c.map(l=>l.deletionMatch).join(" ").trim(),insertions:c.map(l=>l.insertion).join(" ").trim(),deletions:c.map(l=>l.deletion).join(" ").trim()},l=>!l)};var An=async(e,t,r,n,o)=>{let i=[...t,...r],a=i.map(s=>{let u=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),$=s.$thing||s.$relation||s.$entity,c=$?Y(n,$):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!u&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,l=Object.entries(s).filter(([h,f])=>!h.startsWith("$")).reduce((h,[f,y])=>{if(c?.dataFields?.find(E=>E.path===f)?.contentType==="JSON")return h[f]=JSON.parse(y),h;if(s.$thingType==="relation"){let E=i.filter(B=>B.$id&&B.$bzId===y);return E.length===1?(h[f]=E[0].$id,h):(h[f]=y,h)}return h[f]=y,h},{});if(o.mutation?.noMetadata)return l;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...l,[s.path]:s.$id,...p}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(a)};var Cn=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:n}=await at(t,r),o=await n.transaction(TransactionType.WRITE),i=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{i&&await o.query.delete(i);let s=a&&o.query.insert(a),u=s?await s.collect():void 0;return await o.commit(),{insertions:u}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var vo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Yo=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),Go=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Gt=N("error","error",x((e,t)=>({...e,error:t.error}))),Zo=ye("buildMutation",{buildMutation:W(async e=>In(e.bql.things,e.bql.edges,e.schema),N("done","runMutation",x(Yo)),Gt),runMutation:W(async e=>Cn(e.tql.mutation,e.handles,e.config),N("done","parseMutation",x(Go)),Gt),parseMutation:W(async e=>An(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),N("done","success",x(vo)),Gt),success:ie(),error:ie()},e=>e),Xo=async e=>new Promise((t,r)=>{fe(Zo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),On=async(e,t,r,n,o,i,a)=>Xo({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:o,config:i,handles:a,error:null});var Zt=e=>{if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return `'${e}'`;if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var kn=async(e,t)=>{let r=a=>{let{$filter:s,$thing:u,$bzId:$,$op:c,$id:d,$tempId:l}=a,p=Y(t,u),{usedDataFields:h}=le(p,a),{idFields:f}=p,y=d||a[f[0]],m=X(u),E=ae(a,b=>b.startsWith("$")),B=ae(a,b=>!b.startsWith("$")),g=JSON.stringify(B),L=Object.entries(E).map(([b,F])=>b=="$tempId"?`'$tempId': '_:${F}'`:`'${b}': '${F}'`).join(","),Q=a[Ke],I=h.map(b=>{let F=p.dataFields?.find(T=>T.path===b||T.dbPath===b);if(!F)throw new Error(`Data field schema not found for ${b}`);if(f.includes(b))return;if(a[b]===null)return `${b} = NONE`;let S=a[b];if(["JSON","NUMBER","BOOLEAN"].includes(F.contentType))return `${b} = ${S}`;if(["TEXT","EMAIL"].includes(F.contentType))return `${b} = '${S}'`;if(F.contentType==="DATE")return `${b} = d"${S.toISOString()}"`;if(F.contentType==="FLEX"){let T=isArray(S)?S.map(D=>Zt(D)):Zt(S);return `${b} = ${isArray(T)?T.map(D=>D):T}`}throw new Error(`Unsupported data field type ${F.contentType} for key ${b} in mutation`)}).filter(Boolean),A=`$\u27E8${l||$}\u27E9`,j=Q?.bzId?`$\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9`:y?`${m}:\u27E8${y}\u27E9`:`${m}`,K=(()=>{if(Q?.bzId){let b=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(F=>`'${F}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${y}'] ]`:b}else {if(y){if(isArray(y))throw new Error("Multiple ids not supported");return `${m}:\u27E8${y}\u27E9`}return `${m}`}})(),me=s?`WHERE ${$e(he(s,u,t))}`:"",v=I.length>0?`SET ${I.join(", ")}`:"",C=`VALUE (CREATE ONLY Delta SET input = ${g}, meta = {${L}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,w="BEFORE";if(["link","unlink","replace"].includes(c))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return `LET ${A} = (SELECT VALUE id FROM ${K} ${me});`;if(a.$op==="create")return `LET ${A} = (CREATE ONLY ${m}:\u27E8${y}\u27E9 ${v} RETURN ${C});`;if(a.$op==="update")return `LET ${A} = IF (${j}) THEN (UPDATE ${K} ${v} ${me} RETURN ${C}) END;`;if(a.$op==="delete")return `LET ${A} = IF (${j}) THEN (DELETE ${K} ${me} RETURN ${w}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:s,$bzId:u,$op:$,$tempId:c}=a,d=Y(t,s),{usedRoleFields:l}=le(d,a),p=`$\u27E8${c||u}\u27E9`,h="roles"in d?l.flatMap(m=>{let E=d.roles[m];if(!E)throw new Error(`Role field schema not found for ${m}`);let{cardinality:B}=E,g=isArray(a[m])?a[m].map(L=>`$\u27E8${L}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(B==="ONE"){if(g.length>1)throw new Error(`${$==="link"?"Linking":"Replacing"} multiple values to a ONE field ${m}`);switch($){case"link":case"replace":return `${m} = ((type::is::array(${g[0]}) && array::len(${g[0]})==1) && ${g[0]}[0]) || ${g[0]}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${$} for ONE cardinality`)}}else if(B==="MANY"){let L=`array::flatten([${g}])`;switch($){case"link":return `${m} += ${L}`;case"unlink":return `${m} -= ${L}`;case"replace":return `${m} = ${L}`;default:throw new Error(`Unsupported operation ${$} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${B}`)}):[],f=h.length>0?`${h.join(", ")}`:"",y=f?`SET ${f}`:"";return `IF ${p} THEN (UPDATE ${p} ${y} RETURN VALUE id) END; ${p};`},o=a=>{let{$thing:s,$op:u}=a,$=Y(t,s),c=X(s),{usedRoleFields:d}=le($,a);if(!["create","delete"].includes(u))throw new Error("Arcs can only be created or deleted");let[l,p]=d,h=isArray(a[l])?a[l]:[a[l]],f=isArray(a[p])?a[p]:[a[p]];if(u==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let y=ae(a,A=>!A.startsWith("$")),E=`(CREATE ONLY Delta SET input = ${JSON.stringify(y)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,g=$.roles[l].cardinality==="MANY",Q=$.roles[p].cardinality==="MANY";return h.flatMap(A=>f.flatMap(j=>`FOR $node1 IN fn::as_array($\u27E8${A}\u27E9) { FOR $node2 IN fn::as_array($\u27E8${j}\u27E9) { CREATE ONLY ${c} SET ${l} = ${g?"fn::as_array($node1)":"$node1"}, ${p} = ${Q?"fn::as_array($node2)":"$node2"} RETURN ${E}; } }`))}if(u==="delete")return `DELETE FROM ${c} WHERE fn::as_array(${l}) CONTAINSANY $\u27E8${h}\u27E9 AND fn::as_array(${p}) CONTAINSANY $\u27E8${f}\u27E9 RETURN BEFORE`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(o)]};var Pn=async(e,t)=>{let r=`
|
|
121
|
+
BEGIN TRANSACTION;
|
|
122
|
+
${t.join(";")};
|
|
123
|
+
LET $DELTAS = SELECT * FROM Delta;
|
|
124
|
+
DELETE Delta;
|
|
125
|
+
RETURN $DELTAS;
|
|
126
|
+
|
|
127
|
+
LET $LOGS = SELECT * FROM LOG;
|
|
128
|
+
RETURN $LOGS;
|
|
129
|
+
COMMIT TRANSACTION;
|
|
130
|
+
`;try{return (await e.query(r)).filter(Boolean)}catch(n){let i=(await e.query_raw(r)).filter(a=>a.result!=="The query was not executed due to a failed transaction"&&a.result!=="There was an error when starting a new datastore transaction"&&a.status==="ERR");throw i.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(i)}`):n}};var jn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(o=>{if(isArray(o))return o.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error("Internal error: Invalid response from DB");return xn(i,r)});if(!isObject(o)||!("meta"in o))throw new Error("Internal error: Invalid response from DB");return xn(o,r)})},xn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,isArray(a)&&a.length===0?void 0:a]),n=ae(e.input||{},(i,a)=>a===null),o={...r,...e.meta,...n};return t.mutation?.noMetadata?ae(o,i=>!i.startsWith("$")):o};var rs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ns=(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}}},is=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Xt=N("error","error",x((e,t)=>({...e,error:t.error}))),os=ye("buildMutation",{buildMutation:W(async e=>kn(e.bql.flat,e.schema),N("done","runMutation",x(ns)),Xt),runMutation:W(async e=>Pn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations),N("done","parseMutation",x(is)),Xt),parseMutation:W(async e=>jn({res:e.surql.res,config:e.config,schema:e.schema}),N("done","success",x(rs)),Xt),success:ie(),error:ie()},e=>e),ss=async e=>new Promise((t,r)=>{fe(os,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),zn=async(e,t,r,n,o,i)=>ss({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:o,handles:i,error:null});var Wn=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:s,$bzId:u,$tempId:$}=i,c=t.relations[i.$thing]||t.entities[i.$thing];if(!c)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:p,usedRoleFields:h}=le(c,i);if(["create","update","delete","link","unlink","match","replace"].includes(s)){let y={...ae(i,m=>![...h,...p].includes(m)),...s==="link"||s==="unlink"||s==="replace"||s==="update"&&l.length===0?{$op:"match"}:{},...s==="link"||s==="replace"?{}:{[Ke]:d}};r.things.push(y);}let f={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let y=ae(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(B=>n(B,{bzId:u,edgeField:m,tempId:$})):n(i[m],{bzId:u,edgeField:m,tempId:$});let E=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries(f).forEach(([B,g])=>{let L=E.filter(Q=>g.includes(Q.$op)).map(Q=>Q.$bzId);L.length>0&&r.edges.push({...y,[m]:L,$op:B});});});}p&&p.forEach(y=>{isArray(i[y])?i[y].forEach(B=>n(B,{bzId:u,edgeField:y,tempId:$})):n(i[y],{bzId:u,edgeField:y,tempId:$});let m=c.linkFields?.find(B=>B.path===y),E=isArray(i[y])?i[y]:[i[y]];m.target==="relation"&&Object.entries(f).forEach(([B,g])=>{E.filter(Q=>g.includes(Q.$op)).forEach(Q=>{let I=ae(Q,A=>isSymbol(A)||A.startsWith("$"));r.edges.push({...I,[m.plays]:u,$op:B});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([g,L])=>{E.filter(I=>L.includes(I.$op)).forEach(I=>{let A={$thing:m.relation,$thingType:"relation",$bzId:`arc_${I.$bzId}`,[m.plays]:u,[m.oppositeLinkFieldsPlayedBy[0].plays]:I.$bzId,$op:g};r.arcs.push(A);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var Vn=ie,Ue=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,as=(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"}}),cs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ds=async e=>Object.keys(e.bql.enriched).length?Mt(e.bql.enriched,e.schema,e.config):Mt(e.bql.raw,e.schema,e.config),us=async e=>Bn(e.bql.enriched,e.schema,e.config,e.handles),hs=async e=>wn(e.bql.enriched,e.schema,e.config,e.handles),ps=async e=>kr(e.bql.enriched,e.schema),$s=async e=>Wn(e.bql.enriched,e.schema),fs=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}.`)},ms=e=>xe(e.bql.enriched),Ce=N("error","error",x((e,t)=>({...e,error:t.error}))),ys=ye("stringify",{stringify:W(async e=>Fn(e.bql.raw,e.schema),N("done","enrich",x(Ue)),Ce),enrich:W(ds,N("done","preQuery",wt(fs),x(Ue)),N("done","parseBQL",x(Ue)),Ce),preQuery:W(us,N("done","preHookDependencies",wt(ms),x(Ue)),N("done","parseBQL",x(Ue)),Ce),preHookDependencies:W(hs,N("done","enrich",x(Ue)),Ce),parseBQL:W(ps,N("done","flattenBQL",x(as)),Ce),flattenBQL:W($s,N("done","adapter",x(ls)),Ce),adapter:W(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 On(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return zn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},N("done","success",x(cs)),Ce),success:Vn(),error:Vn()},e=>e),gs=async e=>new Promise((t,r)=>{fe(ys,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Hn=async(e,t,r,n)=>gs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var er=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 o=new Surreal;await o.connect(n.url,{namespace:n.namespace,database:n.dbName,auth:{username:n.username,password:n.password},versionCheck:!1}),t.surrealDB.set(n.id,{client:o,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[o,i]=await tryit(TypeDB.coreDriver)(n.url);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.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 s=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(n.provider==="typeDBCluster"&&n.dbName){let o=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,o);if(i){let s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:s});}catch(s){let u=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=$r(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 sr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...$t.query,...this.config.query,...r}},o=Array.isArray(t),i=o?t:[t],[a,s]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let $=new Error(a.error);throw $.stack=a.error.stack,$}let u=s.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...$t.mutation,...this.config.mutation,...r}},[o,i]=await tryit(Hn)(t,this.schema,n,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}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();});}},hu=er;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
54
131
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
55
132
|
//! Todo: Sandbox the function in computeFunction()
|
|
56
133
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
57
134
|
//!old
|
|
58
135
|
|
|
59
|
-
export {
|
|
136
|
+
export { hu as default };
|
|
60
137
|
//# sourceMappingURL=out.js.map
|
|
61
138
|
//# sourceMappingURL=index.mjs.map
|