@blitznocode/blitz-orm 0.9.12 → 0.9.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +43 -45
- package/dist/index.mjs +43 -45
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -7,63 +7,61 @@ var objectTraversal = require('object-traversal');
|
|
|
7
7
|
var uuid = require('uuid');
|
|
8
8
|
var types = require('util/types');
|
|
9
9
|
|
|
10
|
-
var Nt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var bn=e=>{let t=[],n=new Map;return e.forEach(
|
|
11
|
-
`,Object.keys(t.entities).forEach(
|
|
12
|
-
`;let
|
|
13
|
-
`,
|
|
14
|
-
`),
|
|
15
|
-
`,
|
|
16
|
-
`)
|
|
17
|
-
`;}),Object.keys(t.relations).forEach(
|
|
18
|
-
`;let
|
|
19
|
-
`,
|
|
20
|
-
`),
|
|
21
|
-
`);}),
|
|
22
|
-
`,
|
|
23
|
-
`)
|
|
24
|
-
`;});let
|
|
10
|
+
var Nt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var bn=e=>{let t=[],n=new Map;return e.forEach(s=>{let{dbPath:d,contentType:l}=s,a=`${d}-${l}`;n.has(a)||(n.set(a,!0),t.push(s));}),t},se=async(e,t,n)=>{let d=(()=>{let $="",p=[];$+=`
|
|
11
|
+
`,Object.keys(t.entities).forEach(f=>{let Q=t.entities[f],{idFields:S,dataFields:y,linkFields:w,name:b}=Q,g=[],P=[],T=[];if("extends"in Q){let B=t.entities[Q.extends];B.dataFields&&B.dataFields.forEach(I=>{g.push(I.dbPath);}),B.linkFields&&B.linkFields.forEach(I=>{P.push(I.path);}),B.idFields&&B.idFields.forEach(I=>{T.push(I);});}$+=`${b} sub ${"extends"in Q?Q.extends:"entity"},
|
|
12
|
+
`;let L=[];if(S&&S.length>0){let B=new Set(S),F=Array.from(B).map(A=>`${A}`).join(", ");T.includes(F)||($+=` owns ${F} @key,
|
|
13
|
+
`,L.push(F));}if(y&&y.length>0&&y.forEach(B=>{!g.includes(B.dbPath)&&!L.includes(B.dbPath)&&($+=` owns ${B.dbPath},
|
|
14
|
+
`),p.push({dbPath:B.dbPath,contentType:B.contentType});}),w&&w.length>0){let B=[];w.forEach(I=>{let{relation:F,plays:A}=I;!P.includes(I.path)&&!B.includes(`${F}:${A}`)&&($+=` plays ${F}:${A},
|
|
15
|
+
`,B.push(`${F}:${A}`));});}$=$.replace(/,\s*$/,`;
|
|
16
|
+
`),$+=`
|
|
17
|
+
`;}),Object.keys(t.relations).forEach(f=>{let Q=t.relations[f],{idFields:S,dataFields:y,roles:w,name:b,linkFields:g}=Q,P=[],T=[],L=[],B=[];if("extends"in Q){let F=t.relations[Q.extends];F.dataFields&&F.dataFields.forEach(A=>{P.push(A.dbPath);}),F.linkFields&&F.linkFields.forEach(A=>{T.push(A.dbPath);}),F.roles&&Object.values(F.roles).forEach(R=>{L.push(R.name);}),F.idFields&&F.idFields.forEach(A=>{B.push(A);});}$+=`${b} sub ${"extends"in Q?Q.extends:"relation"},
|
|
18
|
+
`;let I=[];if(S&&S.length>0){let F=new Set(S),R=Array.from(F).map(z=>`${z}`).join(", ");B.includes(R)||($+=` owns ${R} @key,
|
|
19
|
+
`,I.push(R));}if(y&&y.length>0&&y.forEach(F=>{!P.includes(F.dbPath)&&!I.includes(F.dbPath)&&($+=` owns ${F.dbPath},
|
|
20
|
+
`),p.push({dbPath:F.dbPath,contentType:F.contentType});}),w&&Object.keys(w).forEach(F=>{L.includes(F)||($+=` relates ${F},
|
|
21
|
+
`);}),g&&g.length>0){let F=[];g.forEach(A=>{let{plays:R}=A;!T.includes(A.path)&&!F.includes(`${Q}:${R}`)&&($+=` plays ${A.relation}:${R},
|
|
22
|
+
`,F.push(`${Q}:${R}`));});}$=$.replace(/,\s*$/,`;
|
|
23
|
+
`),$+=`
|
|
24
|
+
`;});let E=`define
|
|
25
25
|
|
|
26
|
-
`;return bn(
|
|
27
|
-
`,
|
|
28
|
-
`:
|
|
29
|
-
`,
|
|
30
|
-
`):
|
|
31
|
-
`:
|
|
32
|
-
`:
|
|
33
|
-
`);}),`${
|
|
26
|
+
`;return bn(p).forEach(f=>{E+=`${f.dbPath} sub attribute,
|
|
27
|
+
`,f.contentType==="TEXT"||f.contentType==="ID"?E+=` value string;
|
|
28
|
+
`:f.contentType==="EMAIL"?(E+=` value string,
|
|
29
|
+
`,E+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
30
|
+
`):f.contentType==="DATE"?E+=` value datetime;
|
|
31
|
+
`:f.contentType==="BOOLEAN"?E+=` value boolean;
|
|
32
|
+
`:f.contentType==="NUMBER"&&(E+=` value long;
|
|
33
|
+
`);}),`${E}
|
|
34
34
|
|
|
35
|
-
${
|
|
36
|
-
`,n+=
|
|
37
|
-
`;
|
|
35
|
+
${$}`})(),l=e.dbConnectors[0].id,a=n.typeDB.get(l)?.session,m=n.typeDB.get(l)?.client;if(!a){console.log("Session Status: ","NO SESSION");return}await a.close();let[{dbName:M}]=e.dbConnectors;await(await m.databases.get(M)).delete(),await m.databases.create(M);let r=await m.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),i=await r.transaction(typedbDriver.TransactionType.WRITE);await i.query.define(d),await i.commit(),await i.close();let o=await r.transaction(typedbDriver.TransactionType.READ);(await(await o.query.match("match $a sub thing;")).collect()).forEach(async $=>{$.get("a");}),await o.close();};var ae={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ce=(e,t,n)=>n?t:`${e}\xB7${t}`;var de=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,s])=>t(n,s))))[0],Ft=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,s])=>t(n,s))),pe=(e,t)=>{let n=[],s=immer.produce(e,l=>objectTraversal.traverse(l,({key:a,value:m,meta:M})=>{if(M.depth===2&&(a&&(m.dataFields=m.dataFields?.map(k=>({...k,cardinality:k.cardinality||"ONE",dbPath:ce(a,k.path,k.shared)}))),m.extends)){if(!m.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector`);let k=l.entities[m.extends]||l.relations[m.extends];if(m.allExtends=[m.extends,...k.allExtends||[]],m.idFields=k.idFields?(m.idFields||[]).concat(k.idFields):m.idFields,m.dataFields=k.dataFields?(m.dataFields||[]).concat(k.dataFields.map(r=>{let i=m.extends,o=e.entities[i]||e.relations[i];for(;!o.dataFields?.find(u=>u.path===r.path);)i="extends"in o?o.extends:void 0,o=e.entities[i]||e.relations[i];return {...r,dbPath:ce(i,r.path,r.shared)}})):m.dataFields,m.linkFields=k.linkFields?(m.linkFields||[]).concat(k.linkFields):m.linkFields,"roles"in k){let r=m,i=k;r.roles=r.roles||{},r.roles={...r.roles,...i.roles},Object.keys(r.roles).length===0&&(r.roles={});}k?.hooks?.pre&&(m.hooks=m.hooks||{},m.hooks.pre=m.hooks.pre||[],m.hooks.pre=[...k?.hooks?.pre||[],...m?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:l,value:a,meta:m})=>{if(l==="linkFields"){let k=(()=>{if(!m.nodePath)throw new Error("No path");let[i,o]=m.nodePath.split(".");return {thing:o,thingType:i==="entities"?"entity":i==="relations"?"relation":""}})(),r=Array.isArray(a)?a.map(i=>({...i,...k})):[{...a,...k}];n.push(...r);}}),immer.produce(s,l=>objectTraversal.traverse(l,({value:a,key:m,meta:M})=>{if(M.depth===2&&a.idFields&&!a.id){a.name=m;let k=()=>{if(M.nodePath?.split(".")[0]==="entities")return "entity";if(M.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=k();let r=Object.keys(t).find(i=>t[i]?.get(a.defaultDBConnector.id));a.db=r,a.dbContext=ae[r],a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"roles"in a&&Object.entries(a.roles).forEach(([o,u])=>{u.fieldType="roleField",u.playedBy=n.filter(h=>h.relation===m&&h.plays===o)||[],u.name=o;}),"linkFields"in a&&a.linkFields&&a.linkFields?.forEach(o=>{if(o.fieldType="linkField",o.target==="relation"){o.oppositeLinkFieldsPlayedBy=[{plays:o.path,thing:o.relation,thingType:"relation"}];return}let u=n.filter(c=>c.relation===o.relation&&c.plays!==o.plays)||[];o.oppositeLinkFieldsPlayedBy=u;let{filter:h}=o;o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>c.target==="role"),h&&Array.isArray(h)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>h.some($=>c.thing===$.$role)),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>h.some($=>c.thing===$.$thing))),h&&!Array.isArray(h)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>c.$role===h.$role),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>c.thing===h.$thing));});}if(typeof a=="object"&&"playedBy"in a){let k=[...new Set(a.playedBy.map(r=>r.thing))];if(k.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${m}, path:${M.nodePath}, played by: ${k.join(", ")}`);if(a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${m}, path:${M.nodePath}`)}if(M.depth===4){let[k,r]=M.nodePath?.split(".")||[],i=l[k][r];a.validations&&(a.validations.required&&i.requiredFields.push(a.path),a.validations.enum&&i.enumFields.push(a.path),a.validations.fn&&i.fnValidatedFields.push(a.path)),a.default?a.isVirtual?i.virtualFields.push(a.path):i.computedFields.push(a.path):a.isVirtual&&i.virtualFields.push(a.path);}}))},O=(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)}`)},ue=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},Wt=(e,t,n)=>{let s=O(e,t),d=s.linkFields?.find(m=>m.path===n);if(d)return d;let l=s.dataFields?.find(m=>m.path===n);if(l)return l;let a="roles"in s?s.roles?.[n]:void 0;if(a)return a},_t=(e,t,n)=>Wt(e,t,n)?.cardinality,Z=(e,t)=>{let n=e.dataFields?.map(h=>h.path)||[],s=e.linkFields?.map(h=>h.path)||[],d="roles"in e?radash.listify(e.roles,h=>h):[],l=[...n||[],...s||[],...d||[]],m=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...l];if(!t)return {fields:l,dataFields:n,roleFields:d,linkFields:s};let M=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$"))return;if(!l.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")}):radash.listify(t,h=>{if(!h.startsWith("$")){if(!l.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),k=t.$filter?radash.listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&n?.includes(h)):[],r=t.$filter?radash.listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...d||[],...s||[]].includes(h)):[],i=[...M,...k].filter(h=>!m.includes(h)).filter(h=>h),o=t.$filter?Ft(t.$filter,(h,c)=>k.includes(h)):{},u=t.$filter?Ft(t.$filter,(h,c)=>r.includes(h)):{};return {fields:l,dataFields:n,roleFields:d,linkFields:s,usedFields:M,usedLinkFields:s.filter(h=>M.includes(h)),usedRoleFields:d.filter(h=>M.includes(h)),usedDataFields:n.filter(h=>M.includes(h)),unidentifiedFields:i,...k.length?{localFilters:o}:{},...r.length?{nestedFilters:u}:{}}};var he=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},fe=(e,t,n)=>{let d=(n.nodePath||"").split("."),l=radash.isArray(t)?d.slice(0,-2).join("."):d.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,l):{}},v=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var kt=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),J=e=>{if(Array.isArray(e))return e.map(t=>J(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,n={};return Object.entries(t).forEach(([s,d])=>{n[s]=J(d);}),n}else return e};var U=Symbol.for("queryPath"),Lt=Symbol.for("stepPrint"),lt=Symbol.for("edgeType"),it=Symbol.for("edgeSchema");var K="___",$e=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",s=(r,i)=>{let o="",u="";for(let h in r){let c=r[h];if(Array.isArray(c))for(let $=0;$<c.length;$++)u+=`{$${i} has ${h} "${c[$]}";}`,$<c.length-1?u+="or":u+=";";else o+=`, has ${h} "${c}"`;}o+=`;
|
|
36
|
+
`,n+=o,n+=u;},d=(r,i)=>{let o=[],u=[],h="";for(let p=0;p<r.length;p++)r[p].$isVirtual||o.push(` ${r[p].$dbPath}`),u.push(`{${r[p].$dbPath}:${r[p].$as}}`);let c=`${o.join(",")};
|
|
37
|
+
`;h=u.join(",");let $=`$metadata:{as:[${h}]}`;n+=`$${i} as "${i}.${$}.$dataFields": `,n+=c;},l=(r,i,o)=>{for(let u of r){let{$fields:h,$as:c,$justId:$,$idNotIncluded:p,$filterByUnique:E}=u,C=u[U],f=`$metadata:{as:${c},justId:${$?"T":"F"},idNotIncluded:${p},filterByUnique:${E}}`;if(n+=`"${o}.${f}.${u.$var}":{
|
|
38
38
|
`,n+=` match
|
|
39
|
-
`,
|
|
40
|
-
`,
|
|
39
|
+
`,u.$filter&&(n+=` $${i}${K}${u.$var} isa ${u.$thing}`,s(u.$filter,`${i}${K}${u.$var}`)),n+=` $${i} (${u.$var}: $${i}${K}${u.$var}) isa ${u.$intermediary};
|
|
40
|
+
`,h){let Q=`M_${uuid.v4()}`;n+=`?queryPath${Q} = "${C}";
|
|
41
41
|
`,n+=` fetch
|
|
42
|
-
`,n+=`?queryPath${
|
|
43
|
-
;`;let S=
|
|
44
|
-
`;}},a=(r,
|
|
42
|
+
`,n+=`?queryPath${Q} as "queryPath"
|
|
43
|
+
;`;let S=h?.filter(b=>b.$fieldType==="data");S&&S.length>0&&d(S,`${i}${K}${u.$var}`,`${i}.${u.$var}`);let y=h?.filter(b=>b.$fieldType==="link");y&&y.length>0&&a(y,`${i}${K}${u.$var}`,`${i}.${u.$var}`);let w=h?.filter(b=>b.$fieldType==="role");w&&w.length>0&&l(w,`${i}${K}${u.$var}`,`${i}.${u.$var}`);}n+=`};
|
|
44
|
+
`;}},a=(r,i,o)=>{for(let u of r){let{$fields:h,$as:c,$justId:$,$idNotIncluded:p,$filterByUnique:E,$playedBy:C}=u,f=u[U],Q=`$metadata:{as:${c},justId:${$?"T":"F"},idNotIncluded:${p},filterByUnique:${E}}`;if(n+=`"${o}.${Q}.${u.$var}":{
|
|
45
45
|
`,n+=` match
|
|
46
|
-
`,
|
|
47
|
-
`:n+=` $${
|
|
48
|
-
`,
|
|
46
|
+
`,u.$filter&&(n+=` $${i}${K}${u.$var} isa ${u.$thing}`,s(u.$filter,`${i}${K}${u.$var}`)),u.$target==="role"?n+=` $${i}_intermediary (${u.$plays}: $${i}, ${C.plays}: $${i}${K}${u.$var}) isa ${u.$intermediary};
|
|
47
|
+
`:n+=` $${i}${K}${u.$var} (${u.$plays}: $${i}) isa ${u.$thing};
|
|
48
|
+
`,h){let S=`M_${uuid.v4()}`;n+=`?queryPath${S} = "${f}";
|
|
49
49
|
`,n+=` fetch
|
|
50
50
|
`,n+=`?queryPath${S} as "queryPath"
|
|
51
|
-
;`;let
|
|
52
|
-
`;}},
|
|
53
|
-
$${
|
|
51
|
+
;`;let y=h?.filter(g=>g.$fieldType==="data");y&&y.length>0&&d(y,`${i}${K}${u.$var}`);let w=h?.filter(g=>g.$fieldType==="link");w&&w.length>0&&a(w,`${i}${K}${u.$var}`,`${i}.${u.$var}`);let b=h?.filter(g=>g.$fieldType==="role");b&&b.length>0&&l(b,`${i}${K}${u.$var}`,`${i}.${u.$var}`);}n+=`};
|
|
52
|
+
`;}},m=t.length>1,M=[];(r=>{if(m)for(let i of r){let{$path:o,$thing:u,$filter:h,$fields:c}=i;if(!o)throw new Error("Path is not defined");let $=i[U];n+=`match
|
|
53
|
+
$${o} isa ${u} `,h?s(h,o):n+="; ";let p=`M_${uuid.v4()}`;if(n+=`?queryPath${p} = "${$}";
|
|
54
54
|
`,n+=`fetch
|
|
55
|
-
`,n+=`?queryPath${
|
|
56
|
-
;`,
|
|
57
|
-
$${
|
|
55
|
+
`,n+=`?queryPath${p} as "queryPath"
|
|
56
|
+
;`,c){let E=c.filter(Q=>Q.$fieldType==="data");E&&E.length>0&&d(E,o);let C=c.filter(Q=>Q.$fieldType==="link");C&&C.length>0&&a(C,o,o);let f=c.filter(Q=>Q.$fieldType==="role");f&&f.length>0&&l(f,o,o);}M.push(n),n="";}else for(let i of r){let{$path:o,$thing:u,$filter:h,$fields:c}=i;if(!o||o==="undefined")throw new Error("Path is not defined");let $=i[U];if(n+=`match
|
|
57
|
+
$${o} isa ${u} `,h?s(h,o):n+="; ",n+=`?queryPath = "${$}";
|
|
58
58
|
`,n+=`fetch
|
|
59
59
|
`,n+=`?queryPath as "queryPath"
|
|
60
|
-
;`,d){let f=d.filter(Q=>Q.$fieldType==="data");f&&f.length>0&&c(f,i);let F=d.filter(Q=>Q.$fieldType==="link");F&&F.length>0&&a(F,i,i);let $=d.filter(Q=>Q.$fieldType==="role");$&&$.length>0&&s($,i,i);}}})(t),e.tqlRequest=B?k:n;};var vt=e=>{let t=e.dataFields?.map(s=>s.path)||[],n=e.linkFields?.map(s=>s.path)||[],o=Object.keys(e.roles||{})||[];return [...t,...n,...o]},Ht=(e,t)=>Object.keys(e||{}).some(o=>{if(!Array.isArray(e[o])){let c=t.idFields?.includes(o),s=t.dataFields?.some(a=>(a.dbPath===o||a.path===o)&&a?.validations?.unique);return c||s}return !1}),Kt=(e,t)=>{let n=t.dataFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],o=t.linkFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],c=Object.keys(t.roles||{}).map(a=>({path:a,dbPath:a}))||[],s=[...n,...o,...c];return Object.entries(e||{}).reduce((a,[B,k])=>{let m=s.find(r=>r.path===B);return a[m?.dbPath||B]=k,a},{})},ye=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let o=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),c=(r,l,i,h,p)=>({$path:l,$dbPath:h,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:i,$id:r.$id,$filter:r.$filter,$isVirtual:p,$filterProcessed:!0}),s=(r,l,i,h,p)=>{let{target:d,oppositeLinkFieldsPlayedBy:u}=i;return u.map(f=>{let F=d==="role"?f.thingType:"relation",$=d==="role"?f.thing:i.relation,Q={[`$${F}`]:$},P=O(n,Q),S=r?.$fields?.filter(b=>o(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?S?g=[...r.$fields,...P.idFields]:g=r.$fields:g=vt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>o(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:F,$plays:i.plays,$playedBy:f,$path:f.path,$dbPath:p,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:d,$intermediary:f.relation,$justId:h,$id:r.$id,$filter:Kt(r.$filter,P),$idNotIncluded:S,$filterByUnique:Ht(r.$filter,P),$filterProcessed:!0}})},a=(r,l,i,h,p)=>i.playedBy.map(d=>{let{thing:u,thingType:f,relation:F}=d,$={[`$${f}`]:u},Q=O(n,$),P=r?.$fields?.filter(g=>Q?.idFields?.includes(g)||Q?.idFields?.includes(g.$path)).length===0,S=[];return typeof r!="string"?r.$fields?P?S=[...r.$fields,...Q.idFields]:S=r.$fields:S=vt(Q):S=["id"],r.$excludedFields&&(S=S.filter(g=>o(Q,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:f,$path:l,$dbPath:p,$as:r.$as||l,$var:l,$thing:u,$fields:S,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:F,$justId:h,$id:r.$id,$filter:Kt(r.$filter,Q),$idNotIncluded:P,$filterByUnique:Ht(r.$filter,Q),$playedBy:d,$filterProcessed:!0}}),B=(r,l)=>{let i=typeof r=="string"?r:r.$path,h=typeof r=="string",p=l.dataFields?.find(f=>f.path===i),d=l.linkFields?.find(f=>f.path===i),u=l.roles?.[i];if(p){let f=p.isVirtual&&p.default;return c(r,i,h,p.dbPath,f)}else {if(d)return s(r,i,d,h,d.dbPath);if(u)return a(r,i,u,h,u.dbPath)}return null},m=(r=>immer.produce(r,l=>objectTraversal.traverse(l,i=>{let{value:h,meta:p}=i,d=h;if(radash.isObject(d)){if(d.$id){let u=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing},f=O(n,u);if(!f?.name)throw new Error(`Schema not found for ${d.$thing}`);if(d.$path=f.name,Array.isArray(d.$id)||(d.$filterByUnique=!0),f?.idFields?.length===1){let[F]=f.idFields;d.$filter={...d.$filter,[F]:d.$id},delete d.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in d||"$relation"in d||"$thing"in d){let u=O(n,d);if(!u?.name)throw new Error(`Schema not found for ${d.$thing}`);d.$path=u.name;}if(d.$entity?(d.$thing=d.$entity,d.$thingType="entity",delete d.$entity):d.$relation&&(d.$thing=d.$relation,d.$thingType="relation",delete d.$relation),radash.isObject(d)&&"$thing"in d){let u=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing};d[U]=p.nodePath;let f=O(n,u);if(d.$filter&&(d.$filterByUnique=Ht(d.$filter,f),d.$filterProcessed||(d.$filter=Kt(d.$filter,f))),d.$fields){d.$fields.filter(Q=>f?.idFields?.includes(Q)||f?.idFields?.includes(Q.$path)).length>0||(d.$fields=[...d.$fields,...Array.isArray(f.idFields)?f.idFields:[]],d.$idNotIncluded=!0);let $=d.$fields?.flatMap(Q=>{let P=B(Q,f);return Array.isArray(P)?P:[P]}).filter(Boolean);d.$fields=$;}else {let $=vt(f)?.flatMap(Q=>{let P=B(Q,f);return Array.isArray(P)?P:[P]}).filter(Boolean);d.$fields=$;}d.$excludedFields&&(d.$fields=d.$fields.filter(F=>o(f,F)?!0:!d.$excludedFields.includes(F.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=m;};var Et=async(e,t)=>{let n=t.dbConnectors[0].id,o=e.typeDB?.get(n)?.session,c=e.typeDB?.get(n)?.client;if(!o||!o.isOpen()){if(!c)throw new Error("Client not found");o=await c.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:c,session:o});}return {client:c,session:o}};var Be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:o,tqlRequest:c,config:s}=e;if(!o)throw new Error("BQL request not parsed");if(!c)throw new Error("TQL request not built");let a=new typedbDriver.TypeDBOptions;if(a.infer=!0,Array.isArray(c)){let k=await radash.parallel(c.length,c,async m=>{let{session:r}=await Et(n,s),l=await r.transaction(typedbDriver.TransactionType.READ,a);if(!l)throw new Error("Can't create transaction");let h=await l.query.fetch(m).collect();return await l.close(),h});t.rawTqlRes=k,t.isBatched=!0;}else {let{session:k}=await Et(n,s),m=await k.transaction(typedbDriver.TransactionType.READ,a);if(!m)throw new Error("Can't create transaction");let l=await m.query.fetch(c).collect();await m.close(),t.rawTqlRes=l;}};var Ee=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,o=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,c=/filterByUnique:([a-zA-Z0-9_\-·]+)/,s=e.match(t),a=e.match(n),B=e.match(o),k=e.match(c);return {as:s?s[1]:null,justId:a?a[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:k?k[1]:null}},On=e=>{try{let n=(c=>{let s=c.replace("$metadata:","");return s=s.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),s=s.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,B,k)=>/^{.*}$/.test(k)?`:${k}`:`:${B}"${k}"`),s=s.replace(/\[([^\]]+)\]/g,(a,B)=>`[${B.split(",").map(k=>k.trim().startsWith("{")&&k.trim().endsWith("}")?k.trim():`"${k.trim()}"`).join(",")}]`),s})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:o,schema:c,config:s}=e,{rawTqlRes:a,isBatched:B}=t;if(n){if(!a)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let k=(d,u)=>{let{$metaData:f}=d,{as:F}=On(f),$=Object.entries(d).filter(([Q])=>Q!=="type"&&!Q.includes("$")).map(([Q,P])=>{let S=u.dataFields?.find(y=>y.path===Q||y.dbPath===Q),g=Q==="id",b=Array.isArray(F)?F.find(y=>y[Q])?.[Q]:Q,T;if(S?.cardinality==="ONE"){if(T=P[0]?P[0].value:s.query?.returnNulls?null:void 0,S.contentType==="DATE"&&(T=T&&`${T}Z`),g)return [[b,T],["$id",T]].filter(([y,L])=>L!==void 0)}else if(S?.cardinality==="MANY"){if(!radash.isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return s.query?.returnNulls?[[b,null]]:[];S.contentType==="DATE"?T=P.map(y=>`${y.value}Z`):T=P.map(y=>y.value);}return [[b,T]].filter(([y,L])=>L!==void 0)}).flat();return Object.fromEntries([...$])},m=d=>d.reduce((u,f)=>{let{$roleFields:F,$metaData:$,$cardinality:Q}=f,{as:P,justId:S,idNotIncluded:g,filterByUnique:b}=Ee($),T=F.map(y=>{let{dataFields:L,currentSchema:M,linkFields:C,roleFields:E,schemaValue:w}=l(y),I=k(L,M);if(S==="T")return I.id;{let R=r(C),A=m(E),N={...I};return g==="true"&&M?.idFields?.forEach(D=>delete N[D]),{...N,...R,...A,...w}}});return T.length>0?u[P]=Q==="MANY"&&b==="false"?T:T[0]:s.query?.returnNulls&&(u[P]=null),u},{}),r=d=>d.reduce((u,f)=>{let{$linkFields:F,$metaData:$,$cardinality:Q}=f,{as:P,justId:S,idNotIncluded:g,filterByUnique:b}=Ee($),T=F.map(y=>{let{dataFields:L,currentSchema:M,linkFields:C,roleFields:E,schemaValue:w}=l(y),I=k(L,M);if(S==="T")return I.id;{let R=r(C),A=m(E),N={...I};return g==="true"&&M.idFields?.forEach(D=>delete N[D]),{...N,...R,...A,...w}}});return u[P]=T.length>0?Q==="MANY"&&b==="false"?T:T[0]:s.query?.returnNulls?null:void 0,u},{}),l=d=>{let u=Object.keys(d),f=u.find(y=>y.endsWith(".$dataFields"));if(!f)throw new Error("No datafields");let F=d[f],$=f.split(".")[f.split(".").length-2];if(F.$metaData=$,F.length===0)throw new Error("No datafields");let Q=F.type,P={$thing:Q.label,$thingType:Q.root,[U]:d.queryPath.value},S={[`$${P.$thingType}`]:P.$thing},g=O(c,S),b=u.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(L=>L.path===y.split(".").pop())).map(y=>({$linkFields:d[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(L=>L.path===y.split(".").pop())?.cardinality})),T=u.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:d[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:F,schemaValue:P,currentSchema:g,linkFields:b,roleFields:T}},i=d=>d.map(u=>{let{dataFields:f,currentSchema:F,linkFields:$,roleFields:Q,schemaValue:P}=l(u),S=k(f,F),g=r($),b=m(Q),T=o?.$fields?.every(L=>!F?.idFields?.includes(L)&&!F?.idFields?.includes(L.$path));return {...g,...b,...P,...!s.query?.noMetadata&&o.$id?{$id:Array.isArray(o.$id)?S.id:o.$id}:{},...T?Object.fromEntries(Object.entries(S).filter(([L])=>!F?.idFields?.includes(L))):S}}),p=(d=>{let u=f=>{let F=i(f);return o.$id&&!Array.isArray(o.$id)||n[0].$filterByUnique?F[0]??null:F.length===0?null:F};return B?d.map(u):u(d)})(a);t.bqlRes=p;};var qn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Dn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,we=e=>{let n=e.toString().replace(qn,"").trim().split("=>")[0].split("{")[0].replace(Dn,"").trim(),o=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return o?(o.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(s=>s.includes("{")&&s.includes("}")?(s.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):s.trim()).filter(Boolean):[]};var pt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!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(n){let{fn:c}=t.default,a=we(c).filter(B=>!(B 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 be=async(e,t)=>{let{schema:n,enrichedBqlQuery:o}=e,{bqlRes:c}=t;if(!c)return;let a=(B=>immer.produce(B,k=>objectTraversal.traverse(k,({value:m})=>{if(radash.isObject(m)){let r=m;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:i}=l,h=r[U];if(!h)throw new Error("[Internal] QueryPath is missing");let p=objectTraversal.getNodeByPath(o,h),d=p.$fields.map(f=>f.$path),u=p.$excludedFields;i.forEach(f=>{if(u?.includes(f)||d.length>0&&!d.includes(f))return;let F=l.dataFields?.find($=>$.path===f);if(F?.default){let $=pt({currentThing:r,fieldSchema:F,mandatoryDependencies:!0});r[f]=$;}else if(r[f]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${f}`)}),u&&u.forEach(f=>{if(typeof f!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[f];});}}})))(c);t.bqlRes=a;};var Le=async(e,t)=>{let{config:n}=e,{bqlRes:o}=t;if(!o)return;let s=(k=>immer.produce(k,m=>objectTraversal.traverse(m,({value:r})=>{radash.isObject(r);})))(o),B=(k=>immer.produce(k,m=>objectTraversal.traverse(m,({value:r})=>{if(radash.isObject(r)){let l=r;Object.keys(l).forEach(i=>{l[i]===void 0&&delete l[i];}),Object.getOwnPropertySymbols(l).forEach(i=>{delete l[i];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(i=>{i.startsWith("$")&&delete l[i];});}})))(s);t.bqlRes=B;};var Wn={query:[ye,$e,Be,Fe,be,Le]},Qe=async(e,t,n={},o=!0)=>{for(let c of e){let s=await c(t,n);if(s&&Array.isArray(s))for(let a of s)await Qe(a.pipeline,a.req,a.res,!1);}return o&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Lt=(e,t,n,o)=>Qe(Wn.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:o},{});var ut=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.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 Ie=(e,t,n)=>{let o=radash.isArray(e[t])?e[t]:[e[t]];if(!o.every(c=>typeof c=="object"))if(o.every(c=>typeof c=="string")){let c=ut(t,n),[s]=c,a=e.$op==="create"?"link":"replace",B=s.thing,k=s.thingType;if(o.some(m=>m.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:a,$thing:B,$thingType:k,$bzId:`S_${uuid.v4()}`};}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(o)}`)};var Ft=(e,t,n)=>{let o=O(n,t),{usedDataFields:c}=Z(o,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"&&c.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&c.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Qt=(e,t,n)=>{let o=O(n,t),{usedFields:c}=Z(o,t);return t.$op?(Ft(e,t,n),t.$op):t.$id||t.$filter?c.length>0?(Ft(e,{...t,$op:"update"},n),"update"):(Ft(e,{...t,$op:"link"},n),"link"):(Ft(e,{...t,$op:"create"},n),"create")};var Ce=(e,t)=>{let o=(radash.isArray(e.$root)?e.$root:[e.$root]).map(c=>{let s=Qt(c,c,t);return {...{...c.$thing?{}:{$thing:c.$entity||c.$relation},...c.$thingType?{}:{$thingType:ue(c,t)},...c.$op?{}:{$op:s},...c.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...c}});e.$root=radash.isArray(e.$root)?o:o[0];};var It=(e,t)=>{let n=t[kt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,kt,n.add("clean")),!0):!1:(Reflect.set(t,kt,new Set(["clean"])),!0)};var Se=(e,t,n)=>{if(It("split_ids",e)){let o=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(c=>{if(radash.isObject(c)&&"$id"in c&&radash.isArray(c.$id)){let s=c;if(O(n,s),!s.$bzId)throw new Error("[Internal Error] No bzId found");return s.$id.map((a,B)=>({...J(s),$id:a,$bzId:`${s.$bzId}_${B}`,...H(s)}))}return c});(o.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=o);}};var Ae=(e,t,n,o)=>{let c=(radash.isArray(e[t])?e[t]:[e[t]]).map(s=>{let a=ut(t,n),[B]=a,k=Qt(e,{...s,$thing:B.thing,$thingType:B.thingType},o),m=s.$bzId?s.$bzId:s.$tempId?s.$tempId:`N_${uuid.v4()}`;if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);return {...s,[rt]:n,$thing:B.thing,$thingType:B.thingType,$op:k,$bzId:m}});e[t]=radash.isArray(e[t])?c:c[0];};var Oe=(e,t,n)=>{let o=e[t];o&&(radash.isArray(o)?o:[o]).forEach(c=>{let s=O(n,c),{unidentifiedFields:a}=Z(s,c),{computedFields:B,virtualFields:k}=s,m=radash.listify(c,(i,h)=>h!==void 0?i:void 0),r=m.filter(i=>k?.includes(i));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(i=>!m.includes(i)).forEach(i=>{let h=s.dataFields?.find(F=>F.path===i),d=s.linkFields?.find(F=>F.path===i)?.oppositeLinkFieldsPlayedBy[0],u="roles"in s?de(s.roles,(F,$)=>F===i):void 0,f=h||d||u;if(!f)throw new Error(`no field Def for ${i}`);if(c.$op==="create"&&!c[i]){let F=pt({currentThing:c,fieldSchema:f,mandatoryDependencies:!0});c[i]=F;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(c)}`)});};var qe=(e,t,n)=>{let o=ut(t,n),[c]=o;e[t]={$thing:c.thing,$thingType:c.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[rt]:n};};var Pt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let o=`on${he(e.$op)}`;return n.pre.filter(a=>a.triggers[o]?.()).flatMap(a=>a.actions)}return []};var je=(e,t,n,o)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(s=>{if("$thing"in s){let{requiredFields:a,enumFields:B,fnValidatedFields:k,dataFields:m}=O(n,s);if("$op"in s&&s.$op==="create"&&a.forEach(r=>{if(!(r in s))throw new Error(`[Validations] Required field "${r}" is missing.`)}),("$op"in s&&s.$op==="update"||s.$op==="create")&&B.forEach(r=>{if(r in s){let l=m?.find(i=>i.path===r)?.validations?.enum;if(!l)throw new Error(`[Validations] Enum field "${r}" is missing enum options.`);if(radash.isArray(s[r]))s[r].some(i=>{if(!l.includes(i))throw new Error(`[Validations] Option "${i}" is not a valid option for field "${r}".`)});else if(l&&!l.includes(s[r]))throw new Error(`[Validations] Option "${s[r]}" is not a valid option for field "${r}".`)}}),("$op"in s&&s.$op==="update"||s.$op==="create")&&k.forEach(r=>{if(r in s)try{let l=m?.find(i=>i.path===r)?.validations?.fn;if(!l)throw new Error("Missing validation function.");if(!l(s[r]))throw new Error("Failed validation function.")}catch(l){throw new Error(`[Validations:attribute:${r}] ${l.message}`)}}),radash.isObject(s)&&"$thing"in s){let r=s.$thing,l=s,i=radash.clone(J(e)),h=radash.clone(J(l)),p=o.mutation?.context||{};Pt(l,n).forEach(u=>{if(u.type==="validate"){if(u.severity!=="error")return;try{let f=u.fn(h,i,p);if(f===!1)throw new Error(`${u.message}.`);if(f!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(f){throw new Error(`[Validations:thing:${r}] ${f.message}`)}}});}}});};var We=(e,t,n,o)=>{let c=(radash.isArray(e[t])?e[t]:[e[t]]).map(s=>{if(Mt(s)){let a=Pt(s,n).filter(r=>r.type==="transform"),B=radash.clone(J(e)),k=radash.clone(J(s)),m=o.mutation?.context||{};return a.forEach(r=>{let l=r.fn(k,B,m);Object.keys(l).length!==0&&(s={...k,...l,...H(s)});}),s}});e[t]=radash.isArray(e[t])?c:c[0];};var ir=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(It("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},or=(e,t)=>{},Zt=(e,t,n)=>{let c=immer.produce({$rootWrap:{$root:e}},s=>objectTraversal.traverse(s,({value:a,parent:B,key:k,meta:m})=>{if(!(!B||!k)&&radash.isObject(a)){if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a))throw k==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(a)?immer.current(a):a)}`)}let r=a;Object.keys(r).forEach(l=>{if(ir(r,l),l!=="$root"&&l.startsWith("$"))return;let i=l!=="$root"?Wt(t,r,l):{fieldType:"rootField"};if(!i)throw new Error(`[Internal] Field ${l} not found in schema`);if("contentType"in i)return or();if(["rootField","linkField","roleField"].includes(i.fieldType)){if(["linkField","roleField"].includes(i.fieldType)&&Ie(r,l,i),i.fieldType==="rootField"){if(!("$root"in r))throw new Error(`[Internal] Field ${l} is a rootField but the object is not a root`);Ce(r,t);}let h=radash.isArray(r[l])?r[l]:[r[l]],p=m.nodePath?.split(".").slice(1).join(".");h.forEach(u=>{if(u){if(i?.cardinality==="ONE"&&!u.$op&&!u.$id&&!u.$filter&&!u.$tempId&&r.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${p}.${l}`);if(u.$tempId&&!(u.$op===void 0||u.$op==="link"||u.$op==="create"||u.$op==="update"))throw new Error(`Invalid op ${u.$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(i.fieldType)&&(r[l]===null?qe(r,l,i):Ae(r,l,i,t)),Se(r,l,t),["rootField","linkField","roleField"].includes(i.fieldType)&&Oe(r,l,t),(radash.isArray(r[l])?r[l]:[r[l]]).forEach(u=>{let f=O(t,u),{unidentifiedFields:F,usedLinkFields:$,usedFields:Q,fields:P}=Z(f,u);if(Q.forEach(S=>{if(!P.includes(S))throw new Error(`[Schema] Field ${S} not found in the schema`)}),F.length>0)throw new Error(`Unknown fields: [${F.join(",")}] in ${JSON.stringify(a)}`);if($.length>1){let S=f.linkFields?.filter(g=>$.includes(g.path));S?.some((g,b)=>S.some((T,y)=>{if(b!==y&&g.target!==T.target&&g.relation===T.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),We(r,l,t,n),je(r,l,t,n);}});}}));return radash.isArray(c.$rootWrap.$root),c.$rootWrap.$root};var _e=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:o}=await Et(t,n),c=await o.transaction(typedbDriver.TransactionType.WRITE);if(!c)throw new Error("Can't create transaction");let s=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;s&&await c.query.delete(s);let B=a&&c.query.insert(a);try{let k=B?await B.collect():void 0;return await c.commit(),await c.close(),{insertions:k}}catch(k){throw await c.close(),new Error(`Transaction failed: ${k.message}`)}};var Ve=async(e,t,n,o)=>{let c=[...t,...n],s=c.map(a=>{let B=e.insertions?.find(k=>k.get(`${a.$bzId}`))?.get(`${a.$bzId}`);if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!B&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let k=B?.asThing().iid;if(o.mutation?.noMetadata)return Object.entries(a).filter(([l,i])=>!l.startsWith("$")).reduce((l,[i,h])=>{if(a.$thingType==="relation"){let p=c.filter(d=>d.$id&&d.$bzId===h);if(p.length>1)throw new Error(`Multiple things with the same bzId ${h}`);return p.length===1?(l[i]=p[0].$id,l):(l[i]=h,l)}return l[i]=h,l},{});let m=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:k,...a,[a.path]:a.$id,...m}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return radash.clone(s)};var ve=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(s=>s.startsWith("$")).forEach(s=>delete n[s]),Object.keys(n).filter(s=>typeof s=="symbol").forEach(s=>delete n[s])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var Je=async(e,t)=>{let n=m=>{let r=[],l=[],i=u=>{if(u.$id)return u.$id;let f=O(t,u),{idFields:F}=f;if(!F)throw new Error(`no idFields: ${JSON.stringify(u)}`);let[$]=F;if(!$)throw new Error(`no idField: ${JSON.stringify(u)}`);let Q=f.dataFields?.find(g=>g.path===$),P=pt({currentThing:u,fieldSchema:Q,mandatoryDependencies:!0}),S=u[$]||u.$id||P;if(!S)throw new Error(`no idValue: ${JSON.stringify(u)}`);return S},h=u=>{if(u.$op==="create"){let f=i(u);if(r.find(F=>F.$id===f))throw new Error(`Duplicate id ${f} for node ${JSON.stringify(u)}`);if(l.find(F=>F.$bzId===u.$bzId))throw new Error(`Duplicate $bzid ${u.$bzId} for node ${JSON.stringify(u)}`);r.push({...u,$id:f});return}u.$tempId&&u.$op==="match"||r.push(u);},p=u=>{if(u.$op==="create"){let f=i(u);if(r.find(F=>F.$id===f),l.find(F=>F.$bzId===u.$bzId))throw new Error(`Duplicate %bzId ${u.$bzIdd} for edge ${JSON.stringify(u)}`);l.push({...u,$id:f});return}l.push(u);};return objectTraversal.traverse(m,({value:u,parent:f,meta:F})=>{if(!radash.isObject(u))return;let $=u;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let Q=O(t,$),{dataFields:P,roleFields:S,linkFields:g,usedFields:b}=Z(Q,$),T=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let M=b.filter(w=>P?.includes(w)),C=b.filter(w=>S?.includes(w)),E=b.filter(w=>g?.includes(w));if(M.length>0)return "update";if(C.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...radash.shake(radash.pick($,P||[""])),$op:T(),$bzId:$.$bzId};h(y);let L=$[rt];if(L?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let M=L.relation===$.$thing,C=M?$.$bzId:`LT_${uuid.v4()}`,w=fe(m,f,F).$bzId;if(!w)throw new Error("No parent id found");let I=()=>{if($.$op==="delete")return M?"match":"delete";if($.$op==="unlink")return M?"unlink":"delete";if($.$op==="link"||$.$op==="create")return M?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R=O(t,{$thing:L.relation,$thingType:"relation"});if(!Object.keys(R.roles).includes(L.plays))throw new Error(`[Wrong format] Field ${L.plays} is not a role of relation ${L.relation}`);let N={$bzId:C,$thing:L.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:I(),...M?{}:{[L.path]:$.$bzId},[L.plays]:w,[rt]:L,[at]:"linkField"};p(N),($.$op==="unlink"||I()==="unlink")&&M&&p({$thing:L.relation,$thingType:"relation",$bzId:C,$op:"match",[L.plays]:w,[rt]:L,[at]:"linkField"});}if($.$thingType==="relation"){let M=Bt($,(w,I)=>S.includes(w)),C=radash.mapEntries(M,(w,I)=>radash.isArray(I)?[w,I]:radash.isObject(I)?[w,I.$bzId]:[w,I]),E=Bt(u,(w,I)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(M).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},I=O(t,$).roles,R=radash.mapEntries(C,(N,D)=>{let z=I[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(K=>K.$bzId||K)]}return [N,D.$bzId||D]}),A={...E,$thing:$.$thing,$thingType:"relation",$op:w(),...R,$bzId:$.$bzId,[at]:"roleField"};p(A);return}if($.$op==="match"||$.$op==="update"&&Object.keys(M).length>0){let w=0;Object.entries(M).forEach(([I,R])=>{let A=radash.isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;A.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let K={...E,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[I]:D.$bzId,$bzId:$.$bzId,[at]:"roleField"};p(K);});});}}}}}),[r,l]},[o,c]=n(e),s=o.reduce((m,r)=>{if(!r.$bzId)return [...m,r];let l=m.findIndex(i=>i.$bzId===r.$bzId);if(l===-1)return [...m,r];if(m[l].$op==="create"&&r.$op==="match")return m;if(m[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...m.slice(0,l),r,...m.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${m[l].$op}. Current: ${r.$op}`)},[]),a=c.reduce((m,r)=>{let l=m.find(i=>(i.$id&&i.$id===r.$id||i.$bzId&&i.$bzId===r.$bzId)&&i.$thing===r.$thing&&i.$op===r.$op);if(l){let i={...l};return Object.keys(r).forEach(p=>{if(typeof p=="symbol"||p.startsWith("$"))return;let d=l[p],u=r[p];Array.isArray(d)&&Array.isArray(u)?i[p]=Array.from(new Set([...d,...u])):!Array.isArray(d)&&Array.isArray(u)?d!==void 0?i[p]=Array.from(new Set([d,...u])):i[p]=u:Array.isArray(d)&&!Array.isArray(u)?u!==void 0&&(i[p]=Array.from(new Set([...d,u]))):d!==null&&u!==null&&d!==void 0&&u!==void 0?i[p]=Array.from(new Set([d,u])):d==null&&(i[p]=u);}),[...m.filter(p=>!((p.$id&&p.$id===r.$id||p.$bzId&&p.$bzId===r.$bzId)&&p.$thing===r.$thing&&p.$op===r.$op)),i]}return [...m,r]},[]);s.forEach(m=>{if((m.$thingType==="relation"||"relation"in m)&&a.filter(r=>r.$bzId===m.$bzId||r.$tempId&&r.$tempId===m.$tempId).length===0){if(m.$op==="delete"||m.$op==="match"||m.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(ve(m))}`)}});let B=[...s,...a];return new Set(B.filter(m=>m.$tempId).map(m=>m.$tempId)).forEach(m=>{if(B.filter(r=>r.$tempId===m&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:s,mergedEdges:a}};var Ze=async(e,t,n)=>{let o=i=>{let h=i.$op,p=`$${i.$bzId}`,d=O(n,i),{idFields:u,defaultDBConnector:f}=d,F=f?.path||i.$thing,$=i.$id,Q=u?.[0],P=radash.listify(i,(C,E)=>{if(C.startsWith("$")||C===Q||E===void 0||E===null)return "";let w=d.dataFields?.find(A=>A.path===C);if(!w?.path)return "";let R=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${R} '${E}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${R} ${E}`;if(w.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${R} ${E.toISOString().replace("Z","")}`:`has ${R} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(C=>C),S=`${p}-atts`,g=radash.listify(i,C=>{if(C.startsWith("$")||C===Q)return "";let E=d.dataFields?.find(R=>R.path===C);if(!E?.path)return "";let I=E.dbPath;return `{${S} isa ${I};}`}).filter(C=>C),b=radash.isArray($)?`like '${$.join("|")}'`:`'${$}'`,T=$?[`has ${Q} ${b}`]:[],y=[...T,...P].filter(C=>C).join(","),L=()=>{if(h==="delete"||h==="unlink"||h==="match")return `${p} isa ${[F,...T].filter(C=>C).join(",")};`;if(h==="update"){if(!g.length)throw new Error("update without attributes");return `${p} isa ${[F,...T].filter(C=>C).join(",")}, has ${S};
|
|
61
|
-
${g.join(" or ")};`}return ""},M=()=>h==="update"||h==="link"||h==="match"?`${p} isa ${[F,...T].filter(C=>C).join(",")};`:"";if(Mt(i))return {op:h,deletionMatch:L(),insertionMatch:M(),insertion:h==="create"?`${p} isa ${[F,y].filter(C=>C).join(",")};`:h==="update"&&P.length?`${p} ${P.join(",")};`:"",deletion:h==="delete"?`${p} isa ${F};`:h==="update"&&g.length?`${p} has ${S};`:""};throw new Error("in attributes")},c=i=>{let h=i.$op,p=O(n,i),d=`$${i.$bzId}`,u=i.$id,f=p.defaultDBConnector?.path||i.$thing,F="roles"in p?radash.listify(p.roles,E=>E):[],$="roles"in p?radash.mapEntries(p.roles,(E,w)=>[E,w.dbConnector?.path||E]):{},Q=radash.listify(i,(E,w)=>{if(!F.includes(E))return null;if(!("roles"in p))throw new Error("This should have roles! ");let I=$[E];return Array.isArray(w)?w.map(R=>({path:I,id:R})):{path:I,id:w}}).filter(E=>E).flat(),P=Q.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),S=Q.length>0?`( ${P.join(" , ")} )`:"",g=i[at];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=S?`${d} ${S} ${g==="linkField"||h==="delete"||h==="unlink"?`isa ${f}`:""}`:"",T=`${d} ${g==="linkField"||h==="delete"?`isa ${f}`:""}`,y=()=>b?h==="link"?`${b};`:h==="create"?`${b}, has id '${u}';`:"":"",L=()=>b&&h==="match"?`${b};`:"",M=()=>b?h==="delete"?`${b};`:h==="match"?`${b};`:"":"",C=()=>b?h==="delete"?`${T};`:h==="unlink"?`${d} ${S};`:"":"";return {deletionMatch:M(),insertionMatch:L(),deletion:C(),insertion:y(),op:""}},s=(i,h)=>{let p=h==="edges"?c:o;if(Array.isArray(i))return i.map(Q=>{let{preDeletionBatch:P,insertionMatch:S,deletionMatch:g,insertion:b,deletion:T}=p(Q);return radash.shake({preDeletionBatch:P,insertionMatch:S,deletionMatch:g,insertion:b,deletion:T},y=>!y)}).filter(Q=>Q);let{preDeletionBatch:d,insertionMatch:u,deletionMatch:f,insertion:F,deletion:$}=p(i);return radash.shake({preDeletionBatch:d,insertionMatch:u,deletionMatch:f,insertion:F,deletion:$},Q=>!Q)},a=s(e),B=Array.isArray(a)?a:[a],k=s(t,"edges"),m=Array.isArray(k)?k:[k],r=[...B,...m];return radash.shake({insertionMatches:r.map(i=>i.insertionMatch).join(" ").trim(),deletionMatches:r.map(i=>i.deletionMatch).join(" ").trim(),insertions:r.map(i=>i.insertion).join(" ").trim(),deletions:r.map(i=>i.deletion).join(" ").trim()},i=>!i)};var mr=Symbol.for("grandChildOfCreate"),Ye=async(e,t,n,o)=>{let c=(g,b)=>Object.keys(g).filter(T=>T.startsWith("$")?!1:b?!O(t,g).dataFields?.find(L=>L.path===T):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let s=[];if(objectTraversal.traverse(e,({parent:g,key:b,value:T})=>{g&&b&&!b.includes("$")&&radash.isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(L=>{if(radash.isObject(L)){if(g.$op!=="create")s.includes(L.$op)||s.push(L.$op);else if(L.$op==="delete"||L.$op==="unlink")throw new Error(`Cannot ${L.$op} under a create`)}}):!g&&radash.isObject(T)&&(s.includes(T.$op)||s.push(T.$op));}),!s.includes("delete")&&!s.includes("unlink")&&!s.includes("replace")&&!s.includes("update")&&!s.includes("link"))return;let B=(g=>{let b=(T,y)=>{let L=[],M={},C=["$op","$bzId","$parentKey"],E=["$relation","$entity","$id",...C];for(let w in T)if(!C.includes(w)&&!(E.includes(w)&&!y))if(!w.includes("$")&&(radash.isObject(T[w])||Array.isArray(T[w]))){let I=T[w];Array.isArray(I)&&I.length>0?I.forEach(R=>{L.push({$path:w,...b(R)});}):L.push({$path:w,...b(I)});}else M[w]=T[w];return {...M,$fields:L}};return g.map(T=>b(T,!0))})(Array.isArray(e)?e:[e]),k=await Lt(B,n,t,o),m=(g,b)=>{let T=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,L=y?.beforePath||"root",M=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${L}.${M}___${y.key}`,ids:T,key:b}}else return {beforePath:"root",ids:T,key:b}},r=(g,b)=>{let T=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${T}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,T,y]=g.split(/[[\]]/);return T.split(",").map(M=>`${b}${M}${y}`)}else return [g]},i={};(g=>immer.produce(g,b=>objectTraversal.traverse(b,T=>{let{key:y,parent:L}=T;if(L&&y&&L.$id&&!y.includes("$")){let M=m(L,y),C=r(M);if(Array.isArray(L[y])){let E=[];L[y].forEach(w=>{radash.isObject(w)?(w.$objectPath=M,E.push(w.$id.toString())):w&&E.push(w.toString());}),i[C]={$objectPath:M,$ids:E};}else {let E=L[y];radash.isObject(E)?(i[C]={$objectPath:M,$ids:[E.$id.toString()]},E.$objectPath=M):E&&(i[C]={$objectPath:M,$ids:[E.toString()]});}}})))(k||{});let p=g=>immer.produce(g,b=>objectTraversal.traverse(b,T=>{let{key:y,value:L,parent:M}=T;M&&y&&!y.includes("$")&&(Array.isArray(L)||radash.isObject(L))&&!Array.isArray(M)&&(Array.isArray(M[y])?M[y].forEach(C=>{typeof C!="string"&&(C.$objectPath=m(M,y),C.$parentIsCreate=M.$op==="create",C[mr]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):radash.isObject(M[y])&&(M[y].$parentIsCreate=M.$op==="create",M[y][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[y].$objectPath=m(M,y)));})),d=p(e),f=(g=>{let b=(M,C)=>{let E=[];M.filter(A=>A).forEach(A=>{let N=Object.keys(A).filter(D=>!D.startsWith("$")).length;if(Array.isArray(A.$id)&&N>0){let D=A.$id.map(z=>({...A,$id:z}));E=[...E,...D];}else E.push({...A});});let w=[],I=[],R=E.filter(A=>{let D=["delete","update","unlink"].includes(A.$op||""),z=c(A,!0).length;if((!A.$id||Array.isArray(A.$id)&&z>0||A.$filter)&&D)return !0;I.push({...A});});return R.length>0?R.forEach(A=>{let D=(j=>{let $t=(()=>{let _={};for(let x in j){let nt=O(t,j);!x.startsWith("$")&&nt.dataFields?.find(dt=>dt.path===x)&&(_[x]=j[x]);}return _})(),mt=Object.keys(j),et=mt.filter(_=>!_.startsWith("$")),Ot=[],bt=(_,x)=>{if(_===et.length){let dt={...x};mt.forEach(V=>{V.startsWith("$")&&(dt[V]=j[V]);}),Ot.push(dt);return}let nt={...x,[et[_]]:j[et[_]],...H(x),...$t};bt(_+1,nt),bt(_+1,x);};return bt(0,{...H(j)}),Ot})(A).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(ot=>!ot.startsWith("$")).length===0)),z=[],K=r(A.$objectPath),tt=i[K]?i[K].$ids:[],q=D.map((j,ot)=>{let $t=O(t,j),et=Object.keys(j).filter(x=>!x.includes("$")&&!$t.dataFields?.some(nt=>nt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):j[x]:[j[x]]).map(V=>{let qt=r(V.$objectPath);return {idsToKey:(Dt=>{let ie=[],gt=Dt.split("."),Bn=gt.slice(0,gt.length-1).join("."),En=gt.slice(gt.length-1,gt.length)[0].split("___")[1];for(let xt in i)if(xt.startsWith(Bn)&&xt.endsWith(En)){let jt=xt.split("."),Fn=jt.slice(jt.length-1,jt.length)[0].split("___")[0];ie.push(Fn);}return ie})(qt),key:x,multiple:V}})).filter(x=>x!==void 0),_=(x=>{let nt=x.map(V=>V.map(st=>st.idsToKey));return (V=>V.length>0?V.reduce((st,yt)=>st.concat(yt),[]).reduce((st,yt)=>st?yt.filter(Dt=>st.includes(Dt)):yt):[])(nt)})(et).filter(x=>!z.includes(x));if(z=[...z,..._],tt=tt.filter(x=>!_.includes(x)),ot===D.length-1&&tt.length>0)return {...j,$id:tt,$bzId:`T1_${uuid.v4()}`,...H(j)};if(_.length>0)return {...j,$id:_,$bzId:`T2_${uuid.v4()}`,...H(j)}}).filter(j=>j!==void 0),gn=(()=>{if(q.length===0&&!C?.$id)return R;if(q.length===0&&C?.$id){let j=Array.isArray(C.$id)?C.$id:[C.$id],ot=[];return j.forEach($t=>{let mt=r({...A.$objectPath,ids:$t}),et=i[mt];et&&ot.push({...A,$id:et.$ids,...H(A),$bzId:`T_${uuid.v4()}`});}),ot}else return q.filter(j=>j!==void 0)})();w=[...I,...gn].map(T);}):w=E.map(T),w},T=M=>{let C={...M,$bzId:M.$tempId??`T3_${uuid.v4()}`,...H(M)},E=O(t,M);return Object.keys(M).filter(w=>!w.includes("$")&&!E.dataFields?.some(I=>I.path===w)).forEach(w=>{let I=Array.isArray(M[w])?M[w]:[M[w]],R=b(I,M);C[w]=R.length>0?R:void 0;}),C},y=[];return g.forEach(M=>{y=[...y,...b([M])];}),y.map(M=>T(M))})(Array.isArray(d)?d:[d]),F=g=>g.map(b=>{let T=c(b,!0),y={...b};return T.forEach(L=>{let M=Array.isArray(b[L])?b[L]:[b[L]],C=[],E=[],w=[],I={},R=_t(t,b,L);M.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(I=q,Array.isArray(q.$id)?E=[...E,...q.$id]:E.push(q.$id)):q.$op==="create"&&R==="ONE"&&q.id?(I=q,Array.isArray(q.id)?w=[...E,...q.id]:w.push(q.id)):C.push(q);});let A=r(I.$objectPath),D=l(A).map(q=>i[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let K=z.filter(q=>!E.includes(q)),At=E.filter(q=>!z.includes(q)),tt=H(I);K.length>0&&C.push({...I,$op:"unlink",$id:K,$bzId:`T4_${uuid.v4()}`,id:void 0,...tt}),At.length>0&&At.forEach(q=>{C.push({...I,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...tt});}),w.length>0&&w.forEach(q=>{C.push({...I,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...tt});}),y[L]=F(C);}),y}),$=p(F(p(f)));return (g=>immer.produce(g,b=>objectTraversal.traverse(b,T=>{let{key:y,value:L,parent:M}=T;y&&M&&!y?.includes("$")&&(Array.isArray(L)||radash.isObject(L))&&!Array.isArray(M)&&(Array.isArray(L)?L:[L]).forEach(E=>{let w=i[r(E.$objectPath)],I=(N,D)=>N.every(z=>D.includes(z)),R=E.$id?Array.isArray(E.$id)?I(E.$id,w?w.$ids:[]):w?.$ids.includes(E.$id):w,A=_t(t,M,E.$objectPath.key);if(E.$op==="link"&&R&&A==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(E.$objectPath)}" because it is already occupied.`);if(E.$op)switch(E.$op){case"delete":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"update":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"unlink":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"link":if(R)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${E.$id}" because it is already linked to $id:"${M.$id}"`);break;}});})))($),(g=>immer.produce(g,b=>objectTraversal.traverse(b,T=>{let{value:y,meta:L}=T;radash.isObject(y)&&(y[Symbol.for("path")]=L.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};function W(e){return {enumerable:!0,value:e}}function Ge(e){return {enumerable:!0,writable:!0,value:e}}var ht={},yr=()=>!0,Xe=()=>({}),en=e=>e,gr=(e,t,n,o)=>e.apply(n,o)&&t.apply(n,o),Br=(e,t,n,[o,c])=>t.call(n,e.call(n,o,c),c),it=(e,t)=>Object.freeze(Object.create(e,t));function tn(e,t,n){return e.reduce((o,c)=>function(...s){return n(o,c,this,s)},t)}function nn(e){return it(this,{fn:W(e)})}var rn={},G=nn.bind(rn);var on={},sn=nn.bind(on);function Rt(e,t){return t.filter(n=>e.isPrototypeOf(n))}function an(e,t,...n){let o=tn(Rt(on,n).map(s=>s.fn),yr,gr),c=tn(Rt(rn,n).map(s=>s.fn),en,Br);return it(this,{from:W(e),to:W(t),guards:W(o),reducers:W(c)})}var ln={},cn={},X=an.bind(ln);an.bind(cn,null);function Er(e,t,n){return Xt(t,e,n,this.immediates)||e}function dn(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Fr={enter:en};function pn(...e){let t=Rt(ln,e),n=Rt(cn,e),o={final:W(e.length===0),transitions:W(dn(t))};return n.length&&(o.immediates=W(n),o.enter=W(Er)),it(Fr,o)}var wr={enter(e,t,n){let o=this.fn.call(t,t.context,n);return Gt.isPrototypeOf(o)?it(un,{machine:W(o),transitions:W(this.transitions)}).enter(e,t,n):(o.then(c=>t.send({type:"done",data:c})).catch(c=>t.send({type:"error",error:c})),e)}},un={enter(e,t,n){if(t.child=te(this.machine,o=>{t.onChange(o),t.child==o&&o.machine.state.value.final&&(delete t.child,t.send({type:"done",data:o.context}));},t.context,n),t.child.machine.state.value.final){let o=t.child.context;return delete t.child,Xt(t,e,{type:"done",data:o},this.transitions.get("done"))}return e}};function ct(e,...t){let n=W(dn(t));return Gt.isPrototypeOf(e)?it(un,{machine:W(e),transitions:n}):it(wr,{fn:W(e),transitions:n})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function hn(e,t,n=Xe){return typeof e!="string"&&(n=t||Xe,t=e,e=Object.keys(t)[0]),ht._create&&ht._create(e,t),it(Gt,{context:W(n),current:W(e),states:W(t)})}function Xt(e,t,n,o){let{context:c}=e;for(let{to:s,guards:a,reducers:B}of o)if(a(c,n)){e.context=B.call(e,c,n);let k=t.original||t,m=it(k,{current:W(s),original:{value:k}});ht._onEnter&&ht._onEnter(t,s,e.context,c,n);let r=m.state.value;return e.machine=m,e.onChange(e),r.enter(m,e,n)}}function br(e,t){let n=t.type||t,{machine:o}=e,{value:c,name:s}=o.state;return c.transitions.has(n)?Xt(e,o,t,c.transitions.get(n))||o:(ht._send&&ht._send(n,s),o)}var Tr={send(e){br(this,e);}};function te(e,t,n,o){let c=Object.create(Tr,{machine:Ge(e),context:Ge(e.context(n,o)),onChange:W(t)});return c.send=c.send.bind(c),c.machine=c.machine.state.value.enter(c.machine,c,o),c}var fn=pn,ee=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Mr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),kr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Lr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Qr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Ir=async e=>Object.keys(e.bql.current).length?Zt(e.bql.current,e.schema,e.config):Zt(e.bql.raw,e.schema,e.config),Pr=async e=>Ye(e.bql.current,e.schema,e.config,e.handles),Cr=async e=>Je(e.bql.current,e.schema),Sr=async e=>Ze(e.bql.things,e.bql.edges,e.schema),Rr=async e=>_e(e.typeDB.tqlMutation,e.handles,e.config),Ar=async e=>Ve(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),Or=()=>!0,ft=X("error","error",G((e,t)=>({...e,error:t.error}))),qr=hn("enrich",{enrich:ct(Ir,X("done","preQuery",sn(Or),G(ee)),X("done","parseBQL",G(ee)),ft),preQuery:ct(Pr,X("done","parseBQL",G(ee)),ft),parseBQL:ct(Cr,X("done","buildMutation",G(kr)),ft),buildMutation:ct(Sr,X("done","runMutation",G(Lr)),ft),runMutation:ct(Rr,X("done","parseMutation",G(Qr)),ft),parseMutation:ct(Ar,X("done","success",G(Mr)),ft),success:fn(),error:fn()},e=>e),Dr=async e=>new Promise((t,n)=>{te(qr,o=>{o.machine.state.name==="success"&&t(o.context),o.machine.state.name==="error"&&n(o.context);},e);}),$n=async(e,t,n,o)=>Dr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:o,depthLevel:0,error:null});immer.enableMapSet();var re=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async o=>{if(o.provider==="typeDB"&&o.dbName){let[c,s]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(o.url);if(c){let a=`[BORM:${o.provider}:${o.dbName}:core] ${c.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await s.session(o.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(o.id,{client:s,session:a});}catch(a){let B=`[BORM:${o.provider}:${o.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(o.provider==="typeDBCluster"&&o.dbName){let[c,s]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(o.addresses,o.credentials);if(c){let a=`[BORM:${o.provider}:${o.dbName}:core] ${c.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(o.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(o.id,{client:s,session:a});}catch(a){let B=`[BORM:${o.provider}:${o.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=pe(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),se(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let o={...this.config,query:{...Nt.query,...this.config.query,...n}};return Lt(t,o,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let o={...this.config,mutation:{...Nt.mutation,...this.config.mutation,...n}},[c,s]=await radash.tryit($n)(t,this.schema,o,this.dbHandles);if(c)throw console.error(c.error.stack.split(`
|
|
62
|
-
`).slice(0,4).join(`
|
|
63
|
-
`)),new Error(c.error.message);return s.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Hs=re;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
60
|
+
;`,c){let p=c.filter(f=>f.$fieldType==="data");p&&p.length>0&&d(p,o);let E=c.filter(f=>f.$fieldType==="link");E&&E.length>0&&a(E,o,o);let C=c.filter(f=>f.$fieldType==="role");C&&C.length>0&&l(C,o,o);}}})(t),e.tqlRequest=m?M:n;};var Ht=e=>{let t=e.dataFields?.map(l=>l.path)||[],n=e.linkFields?.map(l=>l.path)||[],s=Object.keys(e.roles||{})||[];return [...t,...n,...s]},Kt=(e,t)=>Object.keys(e||{}).some(s=>{if(!Array.isArray(e[s])){let d=t.idFields?.includes(s),l=t.dataFields?.some(a=>(a.dbPath===s||a.path===s)&&a?.validations?.unique);return d||l}return !1}),vt=(e,t)=>{let n=t.dataFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],s=t.linkFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],d=Object.keys(t.roles||{}).map(a=>({path:a,dbPath:a}))||[],l=[...n,...s,...d];return Object.entries(e||{}).reduce((a,[m,M])=>{let k=l.find(r=>r.path===m);return a[k?.dbPath||m]=M,a},{})},ye=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let s=(r,i)=>typeof i=="string"?r.idFields?.includes(i):r.idFields?.includes(i.$path),d=(r,i,o,u,h)=>({$path:i,$dbPath:u,$thingType:"attribute",$as:r.$as||i,$var:i,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:h,$filterProcessed:!0}),l=(r,i,o,u,h)=>{let{target:c,oppositeLinkFieldsPlayedBy:$}=o;return $.map(p=>{let E=c==="role"?p.thingType:"relation",C=c==="role"?p.thing:o.relation,f={[`$${E}`]:C},Q=O(n,f),S=r?.$fields?.filter(w=>s(Q,w)).length===0,y=[];return typeof r!="string"?r.$fields?S?y=[...r.$fields,...Q.idFields]:y=r.$fields:y=Ht(Q):y=["id"],r.$excludedFields&&(y=y.filter(w=>s(Q,w)?!0:!r.$excludedFields.includes(w.$path))),{$thingType:E,$plays:o.plays,$playedBy:p,$path:p.path,$dbPath:h,$as:r.$as||i,$var:i,$thing:C,$fields:y,$excludedFields:r.$excludedFields,$fieldType:"link",$target:c,$intermediary:p.relation,$justId:u,$id:r.$id,$filter:vt(r.$filter,Q),$idNotIncluded:S,$filterByUnique:Kt(r.$filter,Q),$filterProcessed:!0}})},a=(r,i,o,u,h)=>o.playedBy.map(c=>{let{thing:$,thingType:p,relation:E}=c,C={[`$${p}`]:$},f=O(n,C),Q=r?.$fields?.filter(y=>f?.idFields?.includes(y)||f?.idFields?.includes(y.$path)).length===0,S=[];return typeof r!="string"?r.$fields?Q?S=[...r.$fields,...f.idFields]:S=r.$fields:S=Ht(f):S=["id"],r.$excludedFields&&(S=S.filter(y=>s(f,y)?!0:!r.$excludedFields.includes(y.$path))),{$thingType:p,$path:i,$dbPath:h,$as:r.$as||i,$var:i,$thing:$,$fields:S,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:u,$id:r.$id,$filter:vt(r.$filter,f),$idNotIncluded:Q,$filterByUnique:Kt(r.$filter,f),$playedBy:c,$filterProcessed:!0}}),m=(r,i)=>{let o=typeof r=="string"?r:r.$path,u=typeof r=="string",h=i.dataFields?.find(p=>p.path===o),c=i.linkFields?.find(p=>p.path===o),$=i.roles?.[o];if(h){let p=h.isVirtual&&h.default;return d(r,o,u,h.dbPath,p)}else {if(c)return l(r,o,c,u,c.dbPath);if($)return a(r,o,$,u,$.dbPath)}return null},k=(r=>immer.produce(r,i=>objectTraversal.traverse(i,o=>{let{value:u,meta:h}=o,c=u;if(radash.isObject(c)){if(c.$id){let $=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},p=O(n,$);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=p.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),p?.idFields?.length===1){let[E]=p.idFields;c.$filter={...c.$filter,[E]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let $=O(n,c);if(!$?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=$.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),radash.isObject(c)&&"$thing"in c){let $=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[U]=h.nodePath;let p=O(n,$);if(c.$filter&&(c.$filterByUnique=Kt(c.$filter,p),c.$filterProcessed||(c.$filter=vt(c.$filter,p))),c.$fields){c.$fields.filter(f=>p?.idFields?.includes(f)||p?.idFields?.includes(f.$path)).length>0||(c.$fields=[...c.$fields,...Array.isArray(p.idFields)?p.idFields:[]],c.$idNotIncluded=!0);let C=c.$fields?.flatMap(f=>{let Q=m(f,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=C;}else {let C=Ht(p)?.flatMap(f=>{let Q=m(f,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=C;}c.$excludedFields&&(c.$fields=c.$fields.filter(E=>s(p,E)?!0:!c.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=k;};var wt=async(e,t)=>{let n=t.dbConnectors[0].id,s=e.typeDB?.get(n)?.session,d=e.typeDB?.get(n)?.client;if(!s||!s.isOpen()){if(!d)throw new Error("Client not found");s=await d.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:d,session:s});}return {client:d,session:s}};var Be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:s,tqlRequest:d,config:l}=e;if(!s)throw new Error("BQL request not parsed");if(!d)throw new Error("TQL request not built");let a=new typedbDriver.TypeDBOptions;if(a.infer=!0,Array.isArray(d)){let M=await radash.parallel(d.length,d,async k=>{let{session:r}=await wt(n,l),i=await r.transaction(typedbDriver.TransactionType.READ,a);if(!i)throw new Error("Can't create transaction");let u=await i.query.fetch(k).collect();return await i.close(),u});t.rawTqlRes=M,t.isBatched=!0;}else {let{session:M}=await wt(n,l),k=await M.transaction(typedbDriver.TransactionType.READ,a);if(!k)throw new Error("Can't create transaction");let i=await k.query.fetch(d).collect();await k.close(),t.rawTqlRes=i;}};var Ee=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,s=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,d=/filterByUnique:([a-zA-Z0-9_\-·]+)/,l=e.match(t),a=e.match(n),m=e.match(s),M=e.match(d);return {as:l?l[1]:null,justId:a?a[1]:null,idNotIncluded:m?m[1]:null,filterByUnique:M?M[1]:null}},On=e=>{try{let n=(d=>{let l=d.replace("$metadata:","");return l=l.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),l=l.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,m,M)=>/^{.*}$/.test(M)?`:${M}`:`:${m}"${M}"`),l=l.replace(/\[([^\]]+)\]/g,(a,m)=>`[${m.split(",").map(M=>M.trim().startsWith("{")&&M.trim().endsWith("}")?M.trim():`"${M.trim()}"`).join(",")}]`),l})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:s,schema:d,config:l}=e,{rawTqlRes:a,isBatched:m}=t;if(n){if(!a)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let M=(c,$)=>{let{$metaData:p}=c,{as:E}=On(p),C=Object.entries(c).filter(([f])=>f!=="type"&&!f.includes("$")).map(([f,Q])=>{let S=$.dataFields?.find(g=>g.path===f||g.dbPath===f),y=f==="id",w=Array.isArray(E)?E.find(g=>g[f])?.[f]:f,b;if(S?.cardinality==="ONE"){if(b=Q[0]?Q[0].value:l.query?.returnNulls?null:void 0,S.contentType==="DATE"&&(b=b&&`${b}Z`),y)return [[w,b],["$id",b]].filter(([g,P])=>P!==void 0)}else if(S?.cardinality==="MANY"){if(!radash.isArray(Q))throw new Error("Typedb fetch has changed its format");if(Q.length===0)return l.query?.returnNulls?[[w,null]]:[];S.contentType==="DATE"?b=Q.map(g=>`${g.value}Z`):b=Q.map(g=>g.value);}return [[w,b]].filter(([g,P])=>P!==void 0)}).flat();return Object.fromEntries([...C])},k=c=>c.reduce(($,p)=>{let{$roleFields:E,$metaData:C,$cardinality:f}=p,{as:Q,justId:S,idNotIncluded:y,filterByUnique:w}=Ee(C),b=E.map(g=>{let{dataFields:P,currentSchema:T,linkFields:L,roleFields:B,schemaValue:I}=i(g),F=M(P,T);if(S==="T")return F.id;{let A=r(L),R=k(B),z={...F};return y==="true"&&T?.idFields?.forEach(N=>delete z[N]),{...z,...A,...R,...I}}});return b.length>0?$[Q]=f==="MANY"&&w==="false"?b:b[0]:l.query?.returnNulls&&($[Q]=null),$},{}),r=c=>c.reduce(($,p)=>{let{$linkFields:E,$metaData:C,$cardinality:f}=p,{as:Q,justId:S,idNotIncluded:y,filterByUnique:w}=Ee(C),b=E.map(g=>{let{dataFields:P,currentSchema:T,linkFields:L,roleFields:B,schemaValue:I}=i(g),F=M(P,T);if(S==="T")return F.id;{let A=r(L),R=k(B),z={...F};return y==="true"&&T.idFields?.forEach(N=>delete z[N]),{...z,...A,...R,...I}}});return $[Q]=b.length>0?f==="MANY"&&w==="false"?b:b[0]:l.query?.returnNulls?null:void 0,$},{}),i=c=>{let $=Object.keys(c),p=$.find(g=>g.endsWith(".$dataFields"));if(!p)throw new Error("No datafields");let E=c[p],C=p.split(".")[p.split(".").length-2];if(E.$metaData=C,E.length===0)throw new Error("No datafields");let f=E.type,Q={$thing:f.label,$thingType:f.root,[U]:c.queryPath.value},S={[`$${Q.$thingType}`]:Q.$thing},y=O(d,S),w=$.filter(g=>!g.endsWith(".$dataFields")&&y.linkFields?.some(P=>P.path===g.split(".").pop())).map(g=>({$linkFields:c[g],$key:g.split(".").pop(),$metaData:g.split(".")[g.split(".").length-2],$cardinality:y?.linkFields?.find(P=>P.path===g.split(".").pop())?.cardinality})),b=$.filter(g=>!g.endsWith(".$dataFields")&&y.roles?.[g.split(".").pop()]).map(g=>({$roleFields:c[g],$key:g.split(".").pop(),$metaData:g.split(".")[g.split(".").length-2],$cardinality:y.roles[g.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:Q,currentSchema:y,linkFields:w,roleFields:b}},o=c=>c.map($=>{let{dataFields:p,currentSchema:E,linkFields:C,roleFields:f,schemaValue:Q}=i($),S=M(p,E),y=r(C),w=k(f),b=s?.$fields?.every(P=>!E?.idFields?.includes(P)&&!E?.idFields?.includes(P.$path));return {...y,...w,...Q,...!l.query?.noMetadata&&s.$id?{$id:Array.isArray(s.$id)?S.id:s.$id}:{},...b?Object.fromEntries(Object.entries(S).filter(([P])=>!E?.idFields?.includes(P))):S}}),h=(c=>{let $=p=>{let E=o(p);return s.$id&&!Array.isArray(s.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return m?c.map($):$(c)})(a);t.bqlRes=h;};var qn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Dn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,we=e=>{let n=e.toString().replace(qn,"").trim().split("=>")[0].split("{")[0].replace(Dn,"").trim(),s=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return s?(s.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(l=>l.includes("{")&&l.includes("}")?(l.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(m=>m.split(":")[0].trim().replace(/['"[\]]/g,"")):l.trim()).filter(Boolean):[]};var ht=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!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(n){let{fn:d}=t.default,a=we(d).filter(m=>!(m 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 be=async(e,t)=>{let{schema:n,enrichedBqlQuery:s}=e,{bqlRes:d}=t;if(!d)return;let a=(m=>immer.produce(m,M=>objectTraversal.traverse(M,({value:k})=>{if(radash.isObject(k)){let r=k;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let i=O(n,r),{virtualFields:o}=i,u=r[U];if(!u)throw new Error("[Internal] QueryPath is missing");let h=objectTraversal.getNodeByPath(s,u),c=h.$fields.map(p=>p.$path),$=h.$excludedFields;o.forEach(p=>{if($?.includes(p)||c.length>0&&!c.includes(p))return;let E=i.dataFields?.find(C=>C.path===p);if(E?.default){let C=ht({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[p]=C;}else if(r[p]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${p}`)}),$&&$.forEach(p=>{if(typeof p!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[p];});}}})))(d);t.bqlRes=a;};var Le=async(e,t)=>{let{config:n}=e,{bqlRes:s}=t;if(!s)return;let l=(M=>immer.produce(M,k=>objectTraversal.traverse(k,({value:r})=>{radash.isObject(r);})))(s),m=(M=>immer.produce(M,k=>objectTraversal.traverse(k,({value:r})=>{if(radash.isObject(r)){let i=r;Object.keys(i).forEach(o=>{i[o]===void 0&&delete i[o];}),Object.getOwnPropertySymbols(i).forEach(o=>{delete i[o];}),n.query?.noMetadata===!0&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}})))(l);t.bqlRes=m;};var Wn={query:[ye,$e,Be,Fe,be,Le]},Qe=async(e,t,n={},s=!0)=>{for(let d of e){let l=await d(t,n);if(l&&Array.isArray(l))for(let a of l)await Qe(a.pipeline,a.req,a.res,!1);}return s&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Qt=(e,t,n,s)=>Qe(Wn.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:s},{});var ft=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.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 Ie=(e,t,n)=>{let s=radash.isArray(e[t])?e[t]:[e[t]];if(!s.every(d=>typeof d=="object"))if(s.every(d=>typeof d=="string")){let d=ft(t,n),[l]=d,a=e.$op==="create"?"link":"replace",m=l.thing,M=l.thingType;if(s.some(k=>k.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:a,$thing:m,$thingType:M,$bzId:`S_${uuid.v4()}`};}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(s)} Parent: ${JSON.stringify(e,null,2)})`)};var ct=(e,t,n)=>{let s=O(n,t),{usedDataFields:d}=Z(s,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"&&d.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&d.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var It=(e,t,n)=>{let s=O(n,t),{usedFields:d}=Z(s,t);return t.$op?(ct(e,t,n),t.$op):t.$id||t.$filter?d.length>0?(ct(e,{...t,$op:"update"},n),"update"):(ct(e,{...t,$op:"link"},n),"link"):t.$tempId?d.length>0?(ct(e,{...t,$op:"create"},n),"create"):(ct(e,{...t,$op:"create"},n),"link"):(ct(e,{...t,$op:"create"},n),"create")};var Ce=(e,t)=>{let s=(radash.isArray(e.$root)?e.$root:[e.$root]).map(d=>{let l=It(d,d,t);return {...{...d.$thing?{}:{$thing:d.$entity||d.$relation},...d.$thingType?{}:{$thingType:ue(d,t)},...d.$op?{}:{$op:l},...d.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...d}});e.$root=radash.isArray(e.$root)?s:s[0];};var Pt=(e,t)=>{let n=t[Lt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,Lt,n.add("clean")),!0):!1:(Reflect.set(t,Lt,new Set(["clean"])),!0)};var Se=(e,t,n)=>{if(Pt("split_ids",e)){let s=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(d=>{if(radash.isObject(d)&&"$id"in d&&radash.isArray(d.$id)){let l=d;if(O(n,l),!l.$bzId)throw new Error("[Internal Error] No bzId found");return l.$id.map((a,m)=>({...J(l),$id:a,$bzId:`${l.$bzId}_${m}`,...v(l)}))}return d});(s.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=s);}};var Re=(e,t,n,s)=>{let d=(radash.isArray(e[t])?e[t]:[e[t]]).map(l=>{let a=ft(t,n),[m]=a,M=It(e,{...l,$thing:m.thing,$thingType:m.thingType},s),k=l.$bzId?l.$bzId:l.$tempId?l.$tempId:`N_${uuid.v4()}`;if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);return {...l,[it]:n,$thing:m.thing,$thingType:m.thingType,$op:M,$bzId:k}});e[t]=radash.isArray(e[t])?d:d[0];};var Oe=(e,t,n)=>{let s=e[t];s&&(radash.isArray(s)?s:[s]).forEach(d=>{let l=O(n,d),{unidentifiedFields:a}=Z(l,d),{computedFields:m,virtualFields:M}=l,k=radash.listify(d,(o,u)=>u!==void 0?o:void 0),r=k.filter(o=>M?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(m.filter(o=>!k.includes(o)).forEach(o=>{let u=l.dataFields?.find(E=>E.path===o),c=l.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],$="roles"in l?de(l.roles,(E,C)=>E===o):void 0,p=u||c||$;if(!p)throw new Error(`no field Def for ${o}`);if(d.$op==="create"&&!d[o]){let E=ht({currentThing:d,fieldSchema:p,mandatoryDependencies:!0});d[o]=E;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(d)}`)});};var Ct=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let s=`on${he(e.$op)}`;return n.pre.filter(a=>!a.triggers||a.triggers[s]?.()).flatMap(a=>a.actions)}return []};var xe=(e,t,n,s)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(l=>{if("$thing"in l){let{requiredFields:a,enumFields:m,fnValidatedFields:M,dataFields:k}=O(n,l);if("$op"in l&&l.$op==="create"&&a.forEach(r=>{if(!(r in l))throw new Error(`[Validations] Required field "${r}" is missing.`)}),("$op"in l&&l.$op==="update"||l.$op==="create")&&m.forEach(r=>{if(r in l){let i=k?.find(o=>o.path===r)?.validations?.enum;if(!i)throw new Error(`[Validations] Enum field "${r}" is missing enum options.`);if(radash.isArray(l[r]))l[r].some(o=>{if(!i.includes(o))throw new Error(`[Validations] Option "${o}" is not a valid option for field "${r}".`)});else if(i&&!i.includes(l[r]))throw new Error(`[Validations] Option "${l[r]}" is not a valid option for field "${r}".`)}}),("$op"in l&&l.$op==="update"||l.$op==="create")&&M.forEach(r=>{if(r in l)try{let i=k?.find(o=>o.path===r)?.validations?.fn;if(!i)throw new Error("Missing validation function.");if(!i(l[r]))throw new Error("Failed validation function.")}catch(i){throw new Error(`[Validations:attribute:${r}] ${i.message}`)}}),radash.isObject(l)&&"$thing"in l){let r=l.$thing,i=l,o=radash.clone(J(e)),u=radash.clone(J(i)),h=s.mutation?.context||{};Ct(i,n).forEach($=>{if($.type==="validate"){if($.severity!=="error")return;try{let p=$.fn(u,o,h);if(p===!1)throw new Error(`${$.message}.`);if(p!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(p){throw new Error(`[Validations:thing:${r}] ${p.message}`)}}});}}});};var ze=(e,t,n,s)=>{let d=(radash.isArray(e[t])?e[t]:[e[t]]).map(l=>{if(kt(l)){let a=Ct(l,n).filter(r=>r.type==="transform"),m=radash.clone(J(e)),M=radash.clone(J(l)),k=s.mutation?.context||{};return a.forEach(r=>{let i=r.fn(M,m,k);Object.keys(i).length!==0&&(l={...M,...i,...v(l)});}),l}});e[t]=radash.isArray(e[t])?d:d[0];};var We=(e,t,n)=>{let s=ft(t,n),[d]=s;e[t]={$thing:d.thing,$thingType:d.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[it]:n};};var ir=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Pt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},or=(e,t)=>{},Zt=(e,t,n)=>{let d=immer.produce({$rootWrap:{$root:e}},l=>objectTraversal.traverse(l,({value:a,parent:m,key:M,meta:k})=>{if(!(!m||!M)&&radash.isObject(a)){if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a))throw M==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(a)?immer.current(a):a)}`)}let r=a;Object.keys(r).forEach(i=>{if(ir(r,i),i!=="$root"&&i.startsWith("$"))return;let o=i!=="$root"?Wt(t,r,i):{fieldType:"rootField"};if(!o)throw new Error(`[Internal] Field ${i} not found in schema`);if("contentType"in o)return or();if(["rootField","linkField","roleField"].includes(o.fieldType)){if(["linkField","roleField"].includes(o.fieldType)&&(r[i]===null?We(r,i,o):Ie(r,i,o)),o.fieldType==="rootField"){if(!("$root"in r))throw new Error(`[Internal] Field ${i} is a rootField but the object is not a root`);Ce(r,t);}let u=radash.isArray(r[i])?r[i]:[r[i]],h=k.nodePath?.split(".").slice(1).join(".");u.forEach($=>{if($){if(o?.cardinality==="ONE"&&!$.$op&&!$.$id&&!$.$filter&&!$.$tempId&&r.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${h}.${i}`);if($.$tempId&&!($.$op===void 0||$.$op==="link"||$.$op==="create"||$.$op==="update"))throw new Error(`Invalid op ${$.$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(o.fieldType)&&Re(r,i,o,t),Se(r,i,t),["rootField","linkField","roleField"].includes(o.fieldType)&&Oe(r,i,t),(radash.isArray(r[i])?r[i]:[r[i]]).forEach($=>{let p=O(t,$),{unidentifiedFields:E,usedLinkFields:C,usedFields:f,fields:Q}=Z(p,$);if(f.forEach(S=>{if(!Q.includes(S))throw new Error(`[Schema] Field ${S} not found in the schema`)}),E.length>0)throw new Error(`Unknown fields: [${E.join(",")}] in ${JSON.stringify(a)}`);if(C.length>1){let S=p.linkFields?.filter(y=>C.includes(y.path));S?.some((y,w)=>S.some((b,g)=>{if(w!==g&&y.target!==b.target&&y.relation===b.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),ze(r,i,t,n),xe(r,i,t,n);}});}}));return console.log("After enrich",d.$rootWrap.$root),radash.isArray(d.$rootWrap.$root),d.$rootWrap.$root};var _e=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:s}=await wt(t,n),d=await s.transaction(typedbDriver.TransactionType.WRITE);if(!d)throw new Error("Can't create transaction");let l=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;l&&await d.query.delete(l);let m=a&&d.query.insert(a);try{let M=m?await m.collect():void 0;return await d.commit(),await d.close(),{insertions:M}}catch(M){throw await d.close(),new Error(`Transaction failed: ${M.message}`)}};var Ve=async(e,t,n,s)=>{let d=[...t,...n],l=d.map(a=>{let m=e.insertions?.find(M=>M.get(`${a.$bzId}`))?.get(`${a.$bzId}`);if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!m&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let M=m?.asThing().iid;if(s.mutation?.noMetadata)return Object.entries(a).filter(([i,o])=>!i.startsWith("$")).reduce((i,[o,u])=>{if(a.$thingType==="relation"){let h=d.filter(c=>c.$id&&c.$bzId===u);if(h.length>1)throw new Error(`Multiple things with the same bzId ${u}`);return h.length===1?(i[o]=h[0].$id,i):(i[o]=u,i)}return i[o]=u,i},{});let k=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:M,...a,[a.path]:a.$id,...k}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return radash.clone(l)};var He=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(l=>l.startsWith("$")).forEach(l=>delete n[l]),Object.keys(n).filter(l=>typeof l=="symbol").forEach(l=>delete n[l])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var Je=async(e,t)=>{let n=r=>{let i=[],o=[],u=p=>{if(p.$id)return p.$id;let E=O(t,p),{idFields:C}=E;if(!C)throw new Error(`no idFields: ${JSON.stringify(p)}`);let[f]=C;if(!f)throw new Error(`no idField: ${JSON.stringify(p)}`);let Q=E.dataFields?.find(w=>w.path===f),S=ht({currentThing:p,fieldSchema:Q,mandatoryDependencies:!0}),y=p[f]||p.$id||S;if(!y)throw new Error(`no idValue: ${JSON.stringify(p)}`);return y},h=p=>{if(p.$op==="create"){let E=u(p);if(i.find(C=>C.$id===E))throw new Error(`Duplicate id ${E} for node ${JSON.stringify(p)}`);if(o.find(C=>C.$bzId===p.$bzId))throw new Error(`Duplicate $bzid ${p.$bzId} for node ${JSON.stringify(p)}`);i.push({...p,$id:E});return}p.$tempId&&p.$op==="match"||i.push(p);},c=p=>{if(p.$op==="create"){let E=u(p);if(i.find(C=>C.$id===E),o.find(C=>C.$bzId===p.$bzId))throw new Error(`Duplicate %bzId ${p.$bzIdd} for edge ${JSON.stringify(p)}`);o.push({...p,$id:E});return}o.push(p);};return objectTraversal.traverse(r,({value:p,parent:E,meta:C})=>{if(!radash.isObject(p))return;let f=p;if(f.$thing){if(!f.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(f)}`);if(!f.$bzId)throw new Error("[internal error] BzId not found");let Q=O(t,f),{dataFields:S,roleFields:y,linkFields:w,usedFields:b}=Z(Q,f),g=()=>{if(f.$op==="create"||f.$op==="delete")return f.$op;if(f.$op==="update"){let L=b.filter(F=>S?.includes(F)),B=b.filter(F=>y?.includes(F)),I=b.filter(F=>w?.includes(F));if(L.length>0)return "update";if(B.length>0||I.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(f)}`)}return "match"},P={...f.$id&&{$id:f.$id},...f.$tempId&&{$tempId:f.$tempId},...f.$filter&&{$filter:f.$filter},$thing:f.$thing,...f.$thingType&&{$thingType:f.$thingType},...radash.shake(radash.pick(f,S||[""])),$op:g(),$bzId:f.$bzId};h(P);let T=f[it];if(T?.fieldType==="linkField"){if((f.$op==="link"||f.$op==="unlink")&&(f.$id||f.$filter)){if(f.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");i.push({...f,$op:"match"});}let L=T.relation===f.$thing,B=L?f.$bzId:`LT_${uuid.v4()}`,F=fe(r,E,C).$bzId;if(!F)throw new Error("No parent id found");let A=()=>{if(f.$op==="delete")return L?"match":"delete";if(f.$op==="unlink")return L?"unlink":"delete";if(f.$op==="link"||f.$op==="create")return L?"link":"create";if(f.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R=O(t,{$thing:T.relation,$thingType:"relation"});if(!Object.keys(R.roles).includes(T.plays))throw new Error(`[Wrong format] Field ${T.plays} is not a role of relation ${T.relation}`);let N={$bzId:B,$thing:T.relation,$thingType:"relation",...f.$tempId?{$tempId:f.$tempId}:{},$op:A(),...L?{}:{[T.path]:f.$bzId},[T.plays]:F,[it]:T,[lt]:"linkField"};c(N),(f.$op==="unlink"||A()==="unlink")&&L&&c({$thing:T.relation,$thingType:"relation",$bzId:B,$op:"match",[T.plays]:F,[it]:T,[lt]:"linkField"});}if(f.$thingType==="relation"){let L=Ft(f,(F,A)=>y.includes(F)),B=radash.mapEntries(L,(F,A)=>radash.isArray(A)?[F,A]:radash.isObject(A)?[F,A.$bzId]:[F,A]),I=Ft(p,(F,A)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(L).filter(F=>!F.startsWith("$")).length>0){if(f.$op==="create"||f.$op==="delete"){let F=()=>{if(f.$op==="create")return "link";if(f.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},A=O(t,f).roles,R=radash.mapEntries(B,(N,D)=>{let _=A[N]?.cardinality;if(!_)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(_==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(tt=>tt.$bzId||tt)]}return [N,D.$bzId||D]}),z={...I,$thing:f.$thing,$thingType:"relation",$op:F(),...R,$bzId:f.$bzId,[lt]:"roleField"};c(z);return}if(f.$op==="match"||f.$op==="update"&&Object.keys(L).length>0){let F=0;Object.entries(L).forEach(([A,R])=>{let z=radash.isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;z.forEach(D=>{if(!D)return;let _=N(D.$op);if(_==="replace")throw new Error("Not supported yet: replace on roleFields");if(_==="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 tt={...I,$thing:f.$thing,$thingType:"relation",$op:_==="delete"?"unlink":_,[A]:D.$bzId,$bzId:f.$bzId,[lt]:"roleField"};c(tt);});});}}}}}),[i,o]},[s,d]=n(e),l=s.reduce((r,i)=>{if(!i.$bzId)return [...r,i];let o=r.findIndex(u=>u.$bzId===i.$bzId);if(o===-1)return [...r,i];if(r[o].$op==="create"&&i.$op==="match")return r;if(r[o].$op==="match"&&(i.$op==="create"||i.$op==="match"))return [...r.slice(0,o),i,...r.slice(o+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${i.$tempId}". Existing: ${r[o].$op}. Current: ${i.$op}`)},[]),a=d.reduce((r,i)=>{let o=r.find(u=>(u.$id&&u.$id===i.$id||u.$bzId&&u.$bzId===i.$bzId)&&u.$thing===i.$thing&&u.$op===i.$op);if(o){let u={...o};return Object.keys(i).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let $=o[c],p=i[c];Array.isArray($)&&Array.isArray(p)?u[c]=Array.from(new Set([...$,...p])):!Array.isArray($)&&Array.isArray(p)?$!==void 0?u[c]=Array.from(new Set([$,...p])):u[c]=p:Array.isArray($)&&!Array.isArray(p)?p!==void 0&&(u[c]=Array.from(new Set([...$,p]))):$!==null&&p!==null&&$!==void 0&&p!==void 0?u[c]=Array.from(new Set([$,p])):$==null&&(u[c]=p);}),[...r.filter(c=>!((c.$id&&c.$id===i.$id||c.$bzId&&c.$bzId===i.$bzId)&&c.$thing===i.$thing&&c.$op===i.$op)),u]}return [...r,i]},[]);l.forEach(r=>{if((r.$thingType==="relation"||"relation"in r)&&a.filter(i=>i.$bzId===r.$bzId||i.$tempId&&i.$tempId===r.$tempId).length===0){if(r.$op==="delete"||r.$op==="match"||r.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(He(r))}`)}});let m=[...l,...a],M=new Set(m.filter(r=>r.$tempId).map(r=>r.$tempId)),k=Array.from(M).filter(r=>!m.some(i=>i.$tempId===r&&i.$op==="create"));if(k.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${k.join(", ")}`);return {mergedThings:l,mergedEdges:a}};var Ze=async(e,t,n)=>{let s=o=>{let u=o.$op,h=`$${o.$bzId}`,c=O(n,o),{idFields:$,defaultDBConnector:p}=c,E=p?.path||o.$thing,C=o.$id,f=$?.[0],Q=radash.listify(o,(L,B)=>{if(L.startsWith("$")||L===f||B===void 0||B===null)return "";let I=c.dataFields?.find(R=>R.path===L);if(!I?.path)return "";let A=I.dbPath;if(["TEXT","ID","EMAIL"].includes(I.contentType))return `has ${A} '${B}'`;if(["NUMBER","BOOLEAN"].includes(I.contentType))return `has ${A} ${B}`;if(I.contentType==="DATE"){if(Number.isNaN(B.valueOf()))throw new Error("Invalid format, Nan Date");return B instanceof Date?`has ${A} ${B.toISOString().replace("Z","")}`:`has ${A} ${new Date(B).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${I.contentType}`)}).filter(L=>L),S=`${h}-atts`,y=radash.listify(o,L=>{if(L.startsWith("$")||L===f)return "";let B=c.dataFields?.find(A=>A.path===L);if(!B?.path)return "";let F=B.dbPath;return `{${S} isa ${F};}`}).filter(L=>L),w=radash.isArray(C)?`like '${C.join("|")}'`:`'${C}'`,b=C?[`has ${f} ${w}`]:[],g=[...b,...Q].filter(L=>L).join(","),P=()=>{if(u==="delete"||u==="unlink"||u==="match")return `${h} isa ${[E,...b].filter(L=>L).join(",")};`;if(u==="update"){if(!y.length)throw new Error("update without attributes");return `${h} isa ${[E,...b].filter(L=>L).join(",")}, has ${S};
|
|
61
|
+
${y.join(" or ")};`}return ""},T=()=>u==="update"||u==="link"||u==="match"?`${h} isa ${[E,...b].filter(L=>L).join(",")};`:"";if(kt(o))return {op:u,deletionMatch:P(),insertionMatch:T(),insertion:u==="create"?`${h} isa ${[E,g].filter(L=>L).join(",")};`:u==="update"&&Q.length?`${h} ${Q.join(",")};`:"",deletion:u==="delete"?`${h} isa ${E};`:u==="update"&&y.length?`${h} has ${S};`:""};throw new Error("in attributes")},d=o=>{let u=o.$op,h=O(n,o),c=`$${o.$bzId}`,$=o.$id,p=h.defaultDBConnector?.path||o.$thing,E="roles"in h?radash.listify(h.roles,B=>B):[],C="roles"in h?radash.mapEntries(h.roles,(B,I)=>[B,I.dbConnector?.path||B]):{},f=radash.listify(o,(B,I)=>{if(!E.includes(B))return null;if(!("roles"in h))throw new Error("This should have roles! ");let F=C[B];return Array.isArray(I)?I.map(A=>({path:F,id:A})):{path:F,id:I}}).filter(B=>B).flat(),Q=f.map(B=>{if(!B?.path)throw new Error("Object without path");return `${B.path}: $${B.id}`}),S=f.length>0?`( ${Q.join(" , ")} )`:"",y=o[lt];if(!y)throw new Error("[internal error] Symbol edgeType not defined");let w=S?`${c} ${S} ${y==="linkField"||u==="delete"||u==="unlink"?`isa ${p}`:""}`:"",b=`${c} ${y==="linkField"||u==="delete"?`isa ${p}`:""}`,g=()=>w?u==="link"?`${w};`:u==="create"?`${w}, has id '${$}';`:"":"",P=()=>w&&u==="match"?`${w};`:"",T=()=>w?u==="delete"?`${w};`:u==="match"?`${w};`:"":"",L=()=>w?u==="delete"?`${b};`:u==="unlink"?`${c} ${S};`:"":"";return {deletionMatch:T(),insertionMatch:P(),deletion:L(),insertion:g(),op:""}},l=(o,u)=>{let h=u==="edges"?d:s;if(Array.isArray(o))return o.map(f=>{let{preDeletionBatch:Q,insertionMatch:S,deletionMatch:y,insertion:w,deletion:b}=h(f);return radash.shake({preDeletionBatch:Q,insertionMatch:S,deletionMatch:y,insertion:w,deletion:b},g=>!g)}).filter(f=>f);let{preDeletionBatch:c,insertionMatch:$,deletionMatch:p,insertion:E,deletion:C}=h(o);return radash.shake({preDeletionBatch:c,insertionMatch:$,deletionMatch:p,insertion:E,deletion:C},f=>!f)},a=l(e),m=Array.isArray(a)?a:[a],M=l(t,"edges"),k=Array.isArray(M)?M:[M],r=[...m,...k];return radash.shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var mr=Symbol.for("grandChildOfCreate"),Ye=async(e,t,n,s)=>{let d=(y,w)=>Object.keys(y).filter(b=>b.startsWith("$")?!1:w?!O(t,y).dataFields?.find(P=>P.path===b):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let l=[];if(objectTraversal.traverse(e,({parent:y,key:w,value:b})=>{y&&w&&!w.includes("$")&&radash.isObject(y)?(Array.isArray(y[w])?y[w]:[y[w]]).forEach(P=>{if(radash.isObject(P)){if(y.$op!=="create")l.includes(P.$op)||l.push(P.$op);else if(P.$op==="delete"||P.$op==="unlink")throw new Error(`Cannot ${P.$op} under a create`)}}):!y&&radash.isObject(b)&&(l.includes(b.$op)||l.push(b.$op));}),!l.includes("delete")&&!l.includes("unlink")&&!l.includes("replace")&&!l.includes("update")&&!l.includes("link"))return;let m=(y=>{let w=(b,g)=>{let P=[],T={},L=["$op","$bzId","$parentKey"],B=["$relation","$entity","$id",...L];for(let I in b)if(!L.includes(I)&&!(B.includes(I)&&!g))if(!I.includes("$")&&(radash.isObject(b[I])||Array.isArray(b[I]))){let F=b[I];Array.isArray(F)&&F.length>0?F.forEach(A=>{P.push({$path:I,...w(A)});}):P.push({$path:I,...w(F)});}else T[I]=b[I];return {...T,$fields:P}};return y.map(b=>w(b,!0))})(Array.isArray(e)?e:[e]),M=await Qt(m,n,t,s),k=(y,w)=>{let b=y.$id||y.id||y.$bzId;if(y.$objectPath){let{$objectPath:g}=y,P=g?.beforePath||"root",T=Array.isArray(g.ids)?`[${g.ids}]`:g.ids;return {beforePath:`${P}.${T}___${g.key}`,ids:b,key:w}}else return {beforePath:"root",ids:b,key:w}},r=(y,w)=>{let b=y?.beforePath||"root",g=w||(Array.isArray(y?.ids)?`[${y?.ids}]`:y?.ids);return `${b}.${g}___${y?.key}`},i=y=>{if(y.includes("[")&&y.includes("]")){let[w,b,g]=y.split(/[[\]]/);return b.split(",").map(T=>`${w}${T}${g}`)}else return [y]},o={};(y=>immer.produce(y,w=>objectTraversal.traverse(w,b=>{let{key:g,parent:P}=b;if(P&&g&&P.$id&&!g.includes("$")){let T=k(P,g),L=r(T);if(Array.isArray(P[g])){let B=[];P[g].forEach(I=>{radash.isObject(I)?(I.$objectPath=T,B.push(I.$id.toString())):I&&B.push(I.toString());}),o[L]={$objectPath:T,$ids:B};}else {let B=P[g];radash.isObject(B)?(o[L]={$objectPath:T,$ids:[B.$id.toString()]},B.$objectPath=T):B&&(o[L]={$objectPath:T,$ids:[B.toString()]});}}})))(M||{});let h=y=>immer.produce(y,w=>objectTraversal.traverse(w,b=>{let{key:g,value:P,parent:T}=b;T&&g&&!g.includes("$")&&(Array.isArray(P)||radash.isObject(P))&&!Array.isArray(T)&&(Array.isArray(T[g])?T[g].forEach(L=>{typeof L!="string"&&(L.$objectPath=k(T,g),L.$parentIsCreate=T.$op==="create",L[mr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):radash.isObject(T[g])&&(T[g].$parentIsCreate=T.$op==="create",T[g][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[g].$objectPath=k(T,g)));})),c=h(e),p=(y=>{let w=(T,L)=>{let B=[];T.filter(R=>R).forEach(R=>{let z=Object.keys(R).filter(N=>!N.startsWith("$")).length;if(Array.isArray(R.$id)&&z>0){let N=R.$id.map(D=>({...R,$id:D}));B=[...B,...N];}else B.push({...R});});let I=[],F=[],A=B.filter(R=>{let N=["delete","update","unlink"].includes(R.$op||""),D=d(R,!0).length;if((!R.$id||Array.isArray(R.$id)&&D>0||R.$filter)&&N)return !0;F.push({...R});});return A.length>0?A.forEach(R=>{let N=(j=>{let yt=(()=>{let V={};for(let x in j){let rt=O(t,j);!x.startsWith("$")&&rt.dataFields?.find(ut=>ut.path===x)&&(V[x]=j[x]);}return V})(),gt=Object.keys(j),nt=gt.filter(V=>!V.startsWith("$")),Ot=[],Tt=(V,x)=>{if(V===nt.length){let ut={...x};gt.forEach(H=>{H.startsWith("$")&&(ut[H]=j[H]);}),Ot.push(ut);return}let rt={...x,[nt[V]]:j[nt[V]],...v(x),...yt};Tt(V+1,rt),Tt(V+1,x);};return Tt(0,{...v(j)}),Ot})(R).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(st=>!st.startsWith("$")).length===0)),D=[],_=r(R.$objectPath),et=o[_]?o[_].$ids:[],q=N.map((j,st)=>{let yt=O(t,j),nt=Object.keys(j).filter(x=>!x.includes("$")&&!yt.dataFields?.some(rt=>rt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(H=>!H.$id||Array.isArray(H.$id)||H.$filter):j[x]:[j[x]]).map(H=>{let qt=r(H.$objectPath);return {idsToKey:(Dt=>{let ie=[],Et=Dt.split("."),Bn=Et.slice(0,Et.length-1).join("."),En=Et.slice(Et.length-1,Et.length)[0].split("___")[1];for(let xt in o)if(xt.startsWith(Bn)&&xt.endsWith(En)){let jt=xt.split("."),Fn=jt.slice(jt.length-1,jt.length)[0].split("___")[0];ie.push(Fn);}return ie})(qt),key:x,multiple:H}})).filter(x=>x!==void 0),V=(x=>{let rt=x.map(H=>H.map(at=>at.idsToKey));return (H=>H.length>0?H.reduce((at,Bt)=>at.concat(Bt),[]).reduce((at,Bt)=>at?Bt.filter(Dt=>at.includes(Dt)):Bt):[])(rt)})(nt).filter(x=>!D.includes(x));if(D=[...D,...V],et=et.filter(x=>!V.includes(x)),st===N.length-1&&et.length>0)return {...j,$id:et,$bzId:`T1_${uuid.v4()}`,...v(j)};if(V.length>0)return {...j,$id:V,$bzId:`T2_${uuid.v4()}`,...v(j)}}).filter(j=>j!==void 0),gn=(()=>{if(q.length===0&&!L?.$id)return A;if(q.length===0&&L?.$id){let j=Array.isArray(L.$id)?L.$id:[L.$id],st=[];return j.forEach(yt=>{let gt=r({...R.$objectPath,ids:yt}),nt=o[gt];nt&&st.push({...R,$id:nt.$ids,...v(R),$bzId:`T_${uuid.v4()}`});}),st}else return q.filter(j=>j!==void 0)})();I=[...F,...gn].map(b);}):I=B.map(b),I},b=T=>{let L={...T,$bzId:T.$tempId??`T3_${uuid.v4()}`,...v(T)},B=O(t,T);return Object.keys(T).filter(I=>!I.includes("$")&&!B.dataFields?.some(F=>F.path===I)).forEach(I=>{let F=Array.isArray(T[I])?T[I]:[T[I]],A=w(F,T);L[I]=A.length>0?A:void 0;}),L},g=[];return y.forEach(T=>{g=[...g,...w([T])];}),g.map(T=>b(T))})(Array.isArray(c)?c:[c]),E=y=>y.map(w=>{let b=d(w,!0),g={...w};return b.forEach(P=>{let T=Array.isArray(w[P])?w[P]:[w[P]],L=[],B=[],I=[],F={},A=_t(t,w,P);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(F=q,Array.isArray(q.$id)?B=[...B,...q.$id]:B.push(q.$id)):q.$op==="create"&&A==="ONE"&&q.id?(F=q,Array.isArray(q.id)?I=[...B,...q.id]:I.push(q.id)):L.push(q);});let R=r(F.$objectPath),N=i(R).map(q=>o[q]),D=[];N.filter(q=>q!=null).forEach(q=>{D=[...D,...q.$ids];});let _=D.filter(q=>!B.includes(q)),tt=B.filter(q=>!D.includes(q)),et=v(F);_.length>0&&L.push({...F,$op:"unlink",$id:_,$bzId:`T4_${uuid.v4()}`,id:void 0,...et}),tt.length>0&&tt.forEach(q=>{L.push({...F,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...et});}),I.length>0&&I.forEach(q=>{L.push({...F,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...et});}),g[P]=E(L);}),g}),C=h(E(h(p)));return (y=>immer.produce(y,w=>objectTraversal.traverse(w,b=>{let{key:g,value:P,parent:T}=b;g&&T&&!g?.includes("$")&&(Array.isArray(P)||radash.isObject(P))&&!Array.isArray(T)&&(Array.isArray(P)?P:[P]).forEach(B=>{let I=o[r(B.$objectPath)],F=(z,N)=>z.every(D=>N.includes(D)),A=B.$id?Array.isArray(B.$id)?F(B.$id,I?I.$ids:[]):I?.$ids.includes(B.$id):I,R=_t(t,T,B.$objectPath.key);if(B.$op==="link"&&A&&R==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(B.$objectPath)}" because it is already occupied.`);if(B.$op)switch(B.$op){case"delete":if(!A&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${B.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!A&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${B.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!A&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${B.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(A)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${B.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))(C),(y=>immer.produce(y,w=>objectTraversal.traverse(w,b=>{let{value:g,meta:P}=b;radash.isObject(g)&&(g[Symbol.for("path")]=P.nodePath,delete g.$objectPath,delete g.$parentIsCreate);})))(C)};function W(e){return {enumerable:!0,value:e}}function Ge(e){return {enumerable:!0,writable:!0,value:e}}var $t={},yr=()=>!0,Xe=()=>({}),en=e=>e,gr=(e,t,n,s)=>e.apply(n,s)&&t.apply(n,s),Br=(e,t,n,[s,d])=>t.call(n,e.call(n,s,d),d),ot=(e,t)=>Object.freeze(Object.create(e,t));function tn(e,t,n){return e.reduce((s,d)=>function(...l){return n(s,d,this,l)},t)}function nn(e){return ot(this,{fn:W(e)})}var rn={},G=nn.bind(rn);var on={},sn=nn.bind(on);function Rt(e,t){return t.filter(n=>e.isPrototypeOf(n))}function an(e,t,...n){let s=tn(Rt(on,n).map(l=>l.fn),yr,gr),d=tn(Rt(rn,n).map(l=>l.fn),en,Br);return ot(this,{from:W(e),to:W(t),guards:W(s),reducers:W(d)})}var ln={},cn={},X=an.bind(ln);an.bind(cn,null);function Er(e,t,n){return Xt(t,e,n,this.immediates)||e}function dn(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Fr={enter:en};function pn(...e){let t=Rt(ln,e),n=Rt(cn,e),s={final:W(e.length===0),transitions:W(dn(t))};return n.length&&(s.immediates=W(n),s.enter=W(Er)),ot(Fr,s)}var wr={enter(e,t,n){let s=this.fn.call(t,t.context,n);return Gt.isPrototypeOf(s)?ot(un,{machine:W(s),transitions:W(this.transitions)}).enter(e,t,n):(s.then(d=>t.send({type:"done",data:d})).catch(d=>t.send({type:"error",error:d})),e)}},un={enter(e,t,n){if(t.child=te(this.machine,s=>{t.onChange(s),t.child==s&&s.machine.state.value.final&&(delete t.child,t.send({type:"done",data:s.context}));},t.context,n),t.child.machine.state.value.final){let s=t.child.context;return delete t.child,Xt(t,e,{type:"done",data:s},this.transitions.get("done"))}return e}};function pt(e,...t){let n=W(dn(t));return Gt.isPrototypeOf(e)?ot(un,{machine:W(e),transitions:n}):ot(wr,{fn:W(e),transitions:n})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function hn(e,t,n=Xe){return typeof e!="string"&&(n=t||Xe,t=e,e=Object.keys(t)[0]),$t._create&&$t._create(e,t),ot(Gt,{context:W(n),current:W(e),states:W(t)})}function Xt(e,t,n,s){let{context:d}=e;for(let{to:l,guards:a,reducers:m}of s)if(a(d,n)){e.context=m.call(e,d,n);let M=t.original||t,k=ot(M,{current:W(l),original:{value:M}});$t._onEnter&&$t._onEnter(t,l,e.context,d,n);let r=k.state.value;return e.machine=k,e.onChange(e),r.enter(k,e,n)}}function br(e,t){let n=t.type||t,{machine:s}=e,{value:d,name:l}=s.state;return d.transitions.has(n)?Xt(e,s,t,d.transitions.get(n))||s:($t._send&&$t._send(n,l),s)}var Tr={send(e){br(this,e);}};function te(e,t,n,s){let d=Object.create(Tr,{machine:Ge(e),context:Ge(e.context(n,s)),onChange:W(t)});return d.send=d.send.bind(d),d.machine=d.machine.state.value.enter(d.machine,d,s),d}var fn=pn,ee=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Mr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),kr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Lr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Qr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Ir=async e=>Object.keys(e.bql.current).length?Zt(e.bql.current,e.schema,e.config):Zt(e.bql.raw,e.schema,e.config),Pr=async e=>Ye(e.bql.current,e.schema,e.config,e.handles),Cr=async e=>Je(e.bql.current,e.schema),Sr=async e=>Ze(e.bql.things,e.bql.edges,e.schema),Ar=async e=>_e(e.typeDB.tqlMutation,e.handles,e.config),Rr=async e=>Ve(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),Or=()=>!0,mt=X("error","error",G((e,t)=>({...e,error:t.error}))),qr=hn("enrich",{enrich:pt(Ir,X("done","preQuery",sn(Or),G(ee)),X("done","parseBQL",G(ee)),mt),preQuery:pt(Pr,X("done","parseBQL",G(ee)),mt),parseBQL:pt(Cr,X("done","buildMutation",G(kr)),mt),buildMutation:pt(Sr,X("done","runMutation",G(Lr)),mt),runMutation:pt(Ar,X("done","parseMutation",G(Qr)),mt),parseMutation:pt(Rr,X("done","success",G(Mr)),mt),success:fn(),error:fn()},e=>e),Dr=async e=>new Promise((t,n)=>{te(qr,s=>{s.machine.state.name==="success"&&t(s.context),s.machine.state.name==="error"&&n(s.context);},e);}),$n=async(e,t,n,s)=>Dr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:s,depthLevel:0,error:null});immer.enableMapSet();var re=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async s=>{if(s.provider==="typeDB"&&s.dbName){let[d,l]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(s.url);if(d){let a=`[BORM:${s.provider}:${s.dbName}:core] ${d.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await l.session(s.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(s.id,{client:l,session:a});}catch(a){let m=`[BORM:${s.provider}:${s.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(m)}}if(s.provider==="typeDBCluster"&&s.dbName){let[d,l]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(s.addresses,s.credentials);if(d){let a=`[BORM:${s.provider}:${s.dbName}:core] ${d.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await l.session(s.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(s.id,{client:l,session:a});}catch(a){let m=`[BORM:${s.provider}:${s.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(m)}}}));let n=pe(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),se(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let s={...this.config,query:{...Nt.query,...this.config.query,...n}};return Qt(t,s,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let s={...this.config,mutation:{...Nt.mutation,...this.config.mutation,...n}},[d,l]=await radash.tryit($n)(t,this.schema,s,this.dbHandles);if(d){let m=new Error(d.error.message);throw m.stack=d.error.stack,m}return l.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Ks=re;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
64
62
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
65
63
|
//! Todo: Sandbox the function in computeFunction()
|
|
66
64
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
67
65
|
//!old
|
|
68
66
|
|
|
69
|
-
module.exports =
|
|
67
|
+
module.exports = Ks;
|
package/dist/index.mjs
CHANGED
|
@@ -5,63 +5,61 @@ import { traverse, getNodeByPath } from 'object-traversal';
|
|
|
5
5
|
import { v4 } from 'uuid';
|
|
6
6
|
import { isSet } from 'util/types';
|
|
7
7
|
|
|
8
|
-
var Nt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var bn=e=>{let t=[],n=new Map;return e.forEach(
|
|
9
|
-
`,Object.keys(t.entities).forEach(
|
|
10
|
-
`;let
|
|
11
|
-
`,
|
|
12
|
-
`),
|
|
13
|
-
`,
|
|
14
|
-
`)
|
|
15
|
-
`;}),Object.keys(t.relations).forEach(
|
|
16
|
-
`;let
|
|
17
|
-
`,
|
|
18
|
-
`),
|
|
19
|
-
`);}),
|
|
20
|
-
`,
|
|
21
|
-
`)
|
|
22
|
-
`;});let
|
|
8
|
+
var Nt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var bn=e=>{let t=[],n=new Map;return e.forEach(s=>{let{dbPath:d,contentType:l}=s,a=`${d}-${l}`;n.has(a)||(n.set(a,!0),t.push(s));}),t},se=async(e,t,n)=>{let d=(()=>{let $="",p=[];$+=`
|
|
9
|
+
`,Object.keys(t.entities).forEach(f=>{let Q=t.entities[f],{idFields:S,dataFields:y,linkFields:w,name:b}=Q,g=[],P=[],T=[];if("extends"in Q){let B=t.entities[Q.extends];B.dataFields&&B.dataFields.forEach(I=>{g.push(I.dbPath);}),B.linkFields&&B.linkFields.forEach(I=>{P.push(I.path);}),B.idFields&&B.idFields.forEach(I=>{T.push(I);});}$+=`${b} sub ${"extends"in Q?Q.extends:"entity"},
|
|
10
|
+
`;let L=[];if(S&&S.length>0){let B=new Set(S),F=Array.from(B).map(A=>`${A}`).join(", ");T.includes(F)||($+=` owns ${F} @key,
|
|
11
|
+
`,L.push(F));}if(y&&y.length>0&&y.forEach(B=>{!g.includes(B.dbPath)&&!L.includes(B.dbPath)&&($+=` owns ${B.dbPath},
|
|
12
|
+
`),p.push({dbPath:B.dbPath,contentType:B.contentType});}),w&&w.length>0){let B=[];w.forEach(I=>{let{relation:F,plays:A}=I;!P.includes(I.path)&&!B.includes(`${F}:${A}`)&&($+=` plays ${F}:${A},
|
|
13
|
+
`,B.push(`${F}:${A}`));});}$=$.replace(/,\s*$/,`;
|
|
14
|
+
`),$+=`
|
|
15
|
+
`;}),Object.keys(t.relations).forEach(f=>{let Q=t.relations[f],{idFields:S,dataFields:y,roles:w,name:b,linkFields:g}=Q,P=[],T=[],L=[],B=[];if("extends"in Q){let F=t.relations[Q.extends];F.dataFields&&F.dataFields.forEach(A=>{P.push(A.dbPath);}),F.linkFields&&F.linkFields.forEach(A=>{T.push(A.dbPath);}),F.roles&&Object.values(F.roles).forEach(R=>{L.push(R.name);}),F.idFields&&F.idFields.forEach(A=>{B.push(A);});}$+=`${b} sub ${"extends"in Q?Q.extends:"relation"},
|
|
16
|
+
`;let I=[];if(S&&S.length>0){let F=new Set(S),R=Array.from(F).map(z=>`${z}`).join(", ");B.includes(R)||($+=` owns ${R} @key,
|
|
17
|
+
`,I.push(R));}if(y&&y.length>0&&y.forEach(F=>{!P.includes(F.dbPath)&&!I.includes(F.dbPath)&&($+=` owns ${F.dbPath},
|
|
18
|
+
`),p.push({dbPath:F.dbPath,contentType:F.contentType});}),w&&Object.keys(w).forEach(F=>{L.includes(F)||($+=` relates ${F},
|
|
19
|
+
`);}),g&&g.length>0){let F=[];g.forEach(A=>{let{plays:R}=A;!T.includes(A.path)&&!F.includes(`${Q}:${R}`)&&($+=` plays ${A.relation}:${R},
|
|
20
|
+
`,F.push(`${Q}:${R}`));});}$=$.replace(/,\s*$/,`;
|
|
21
|
+
`),$+=`
|
|
22
|
+
`;});let E=`define
|
|
23
23
|
|
|
24
|
-
`;return bn(
|
|
25
|
-
`,
|
|
26
|
-
`:
|
|
27
|
-
`,
|
|
28
|
-
`):
|
|
29
|
-
`:
|
|
30
|
-
`:
|
|
31
|
-
`);}),`${
|
|
24
|
+
`;return bn(p).forEach(f=>{E+=`${f.dbPath} sub attribute,
|
|
25
|
+
`,f.contentType==="TEXT"||f.contentType==="ID"?E+=` value string;
|
|
26
|
+
`:f.contentType==="EMAIL"?(E+=` value string,
|
|
27
|
+
`,E+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
28
|
+
`):f.contentType==="DATE"?E+=` value datetime;
|
|
29
|
+
`:f.contentType==="BOOLEAN"?E+=` value boolean;
|
|
30
|
+
`:f.contentType==="NUMBER"&&(E+=` value long;
|
|
31
|
+
`);}),`${E}
|
|
32
32
|
|
|
33
|
-
${
|
|
34
|
-
`,n+=
|
|
35
|
-
`;
|
|
33
|
+
${$}`})(),l=e.dbConnectors[0].id,a=n.typeDB.get(l)?.session,m=n.typeDB.get(l)?.client;if(!a){console.log("Session Status: ","NO SESSION");return}await a.close();let[{dbName:M}]=e.dbConnectors;await(await m.databases.get(M)).delete(),await m.databases.create(M);let r=await m.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),i=await r.transaction(TransactionType.WRITE);await i.query.define(d),await i.commit(),await i.close();let o=await r.transaction(TransactionType.READ);(await(await o.query.match("match $a sub thing;")).collect()).forEach(async $=>{$.get("a");}),await o.close();};var ae={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ce=(e,t,n)=>n?t:`${e}\xB7${t}`;var de=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,s])=>t(n,s))))[0],Ft=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,s])=>t(n,s))),pe=(e,t)=>{let n=[],s=produce(e,l=>traverse(l,({key:a,value:m,meta:M})=>{if(M.depth===2&&(a&&(m.dataFields=m.dataFields?.map(k=>({...k,cardinality:k.cardinality||"ONE",dbPath:ce(a,k.path,k.shared)}))),m.extends)){if(!m.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector`);let k=l.entities[m.extends]||l.relations[m.extends];if(m.allExtends=[m.extends,...k.allExtends||[]],m.idFields=k.idFields?(m.idFields||[]).concat(k.idFields):m.idFields,m.dataFields=k.dataFields?(m.dataFields||[]).concat(k.dataFields.map(r=>{let i=m.extends,o=e.entities[i]||e.relations[i];for(;!o.dataFields?.find(u=>u.path===r.path);)i="extends"in o?o.extends:void 0,o=e.entities[i]||e.relations[i];return {...r,dbPath:ce(i,r.path,r.shared)}})):m.dataFields,m.linkFields=k.linkFields?(m.linkFields||[]).concat(k.linkFields):m.linkFields,"roles"in k){let r=m,i=k;r.roles=r.roles||{},r.roles={...r.roles,...i.roles},Object.keys(r.roles).length===0&&(r.roles={});}k?.hooks?.pre&&(m.hooks=m.hooks||{},m.hooks.pre=m.hooks.pre||[],m.hooks.pre=[...k?.hooks?.pre||[],...m?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:l,value:a,meta:m})=>{if(l==="linkFields"){let k=(()=>{if(!m.nodePath)throw new Error("No path");let[i,o]=m.nodePath.split(".");return {thing:o,thingType:i==="entities"?"entity":i==="relations"?"relation":""}})(),r=Array.isArray(a)?a.map(i=>({...i,...k})):[{...a,...k}];n.push(...r);}}),produce(s,l=>traverse(l,({value:a,key:m,meta:M})=>{if(M.depth===2&&a.idFields&&!a.id){a.name=m;let k=()=>{if(M.nodePath?.split(".")[0]==="entities")return "entity";if(M.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=k();let r=Object.keys(t).find(i=>t[i]?.get(a.defaultDBConnector.id));a.db=r,a.dbContext=ae[r],a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"roles"in a&&Object.entries(a.roles).forEach(([o,u])=>{u.fieldType="roleField",u.playedBy=n.filter(h=>h.relation===m&&h.plays===o)||[],u.name=o;}),"linkFields"in a&&a.linkFields&&a.linkFields?.forEach(o=>{if(o.fieldType="linkField",o.target==="relation"){o.oppositeLinkFieldsPlayedBy=[{plays:o.path,thing:o.relation,thingType:"relation"}];return}let u=n.filter(c=>c.relation===o.relation&&c.plays!==o.plays)||[];o.oppositeLinkFieldsPlayedBy=u;let{filter:h}=o;o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>c.target==="role"),h&&Array.isArray(h)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>h.some($=>c.thing===$.$role)),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>h.some($=>c.thing===$.$thing))),h&&!Array.isArray(h)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>c.$role===h.$role),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(c=>c.thing===h.$thing));});}if(typeof a=="object"&&"playedBy"in a){let k=[...new Set(a.playedBy.map(r=>r.thing))];if(k.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${m}, path:${M.nodePath}, played by: ${k.join(", ")}`);if(a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${m}, path:${M.nodePath}`)}if(M.depth===4){let[k,r]=M.nodePath?.split(".")||[],i=l[k][r];a.validations&&(a.validations.required&&i.requiredFields.push(a.path),a.validations.enum&&i.enumFields.push(a.path),a.validations.fn&&i.fnValidatedFields.push(a.path)),a.default?a.isVirtual?i.virtualFields.push(a.path):i.computedFields.push(a.path):a.isVirtual&&i.virtualFields.push(a.path);}}))},O=(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)}`)},ue=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},Wt=(e,t,n)=>{let s=O(e,t),d=s.linkFields?.find(m=>m.path===n);if(d)return d;let l=s.dataFields?.find(m=>m.path===n);if(l)return l;let a="roles"in s?s.roles?.[n]:void 0;if(a)return a},_t=(e,t,n)=>Wt(e,t,n)?.cardinality,Z=(e,t)=>{let n=e.dataFields?.map(h=>h.path)||[],s=e.linkFields?.map(h=>h.path)||[],d="roles"in e?listify(e.roles,h=>h):[],l=[...n||[],...s||[],...d||[]],m=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...l];if(!t)return {fields:l,dataFields:n,roleFields:d,linkFields:s};let M=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$"))return;if(!l.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("$")){if(!l.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),k=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&n?.includes(h)):[],r=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...d||[],...s||[]].includes(h)):[],i=[...M,...k].filter(h=>!m.includes(h)).filter(h=>h),o=t.$filter?Ft(t.$filter,(h,c)=>k.includes(h)):{},u=t.$filter?Ft(t.$filter,(h,c)=>r.includes(h)):{};return {fields:l,dataFields:n,roleFields:d,linkFields:s,usedFields:M,usedLinkFields:s.filter(h=>M.includes(h)),usedRoleFields:d.filter(h=>M.includes(h)),usedDataFields:n.filter(h=>M.includes(h)),unidentifiedFields:i,...k.length?{localFilters:o}:{},...r.length?{nestedFilters:u}:{}}};var he=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},fe=(e,t,n)=>{let d=(n.nodePath||"").split("."),l=isArray(t)?d.slice(0,-2).join("."):d.slice(0,-1).join(".");return t?getNodeByPath(e,l):{}},v=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var kt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),J=e=>{if(Array.isArray(e))return e.map(t=>J(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,n={};return Object.entries(t).forEach(([s,d])=>{n[s]=J(d);}),n}else return e};var U=Symbol.for("queryPath"),Lt=Symbol.for("stepPrint"),lt=Symbol.for("edgeType"),it=Symbol.for("edgeSchema");var K="___",$e=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",s=(r,i)=>{let o="",u="";for(let h in r){let c=r[h];if(Array.isArray(c))for(let $=0;$<c.length;$++)u+=`{$${i} has ${h} "${c[$]}";}`,$<c.length-1?u+="or":u+=";";else o+=`, has ${h} "${c}"`;}o+=`;
|
|
34
|
+
`,n+=o,n+=u;},d=(r,i)=>{let o=[],u=[],h="";for(let p=0;p<r.length;p++)r[p].$isVirtual||o.push(` ${r[p].$dbPath}`),u.push(`{${r[p].$dbPath}:${r[p].$as}}`);let c=`${o.join(",")};
|
|
35
|
+
`;h=u.join(",");let $=`$metadata:{as:[${h}]}`;n+=`$${i} as "${i}.${$}.$dataFields": `,n+=c;},l=(r,i,o)=>{for(let u of r){let{$fields:h,$as:c,$justId:$,$idNotIncluded:p,$filterByUnique:E}=u,C=u[U],f=`$metadata:{as:${c},justId:${$?"T":"F"},idNotIncluded:${p},filterByUnique:${E}}`;if(n+=`"${o}.${f}.${u.$var}":{
|
|
36
36
|
`,n+=` match
|
|
37
|
-
`,
|
|
38
|
-
`,
|
|
37
|
+
`,u.$filter&&(n+=` $${i}${K}${u.$var} isa ${u.$thing}`,s(u.$filter,`${i}${K}${u.$var}`)),n+=` $${i} (${u.$var}: $${i}${K}${u.$var}) isa ${u.$intermediary};
|
|
38
|
+
`,h){let Q=`M_${v4()}`;n+=`?queryPath${Q} = "${C}";
|
|
39
39
|
`,n+=` fetch
|
|
40
|
-
`,n+=`?queryPath${
|
|
41
|
-
;`;let S=
|
|
42
|
-
`;}},a=(r,
|
|
40
|
+
`,n+=`?queryPath${Q} as "queryPath"
|
|
41
|
+
;`;let S=h?.filter(b=>b.$fieldType==="data");S&&S.length>0&&d(S,`${i}${K}${u.$var}`,`${i}.${u.$var}`);let y=h?.filter(b=>b.$fieldType==="link");y&&y.length>0&&a(y,`${i}${K}${u.$var}`,`${i}.${u.$var}`);let w=h?.filter(b=>b.$fieldType==="role");w&&w.length>0&&l(w,`${i}${K}${u.$var}`,`${i}.${u.$var}`);}n+=`};
|
|
42
|
+
`;}},a=(r,i,o)=>{for(let u of r){let{$fields:h,$as:c,$justId:$,$idNotIncluded:p,$filterByUnique:E,$playedBy:C}=u,f=u[U],Q=`$metadata:{as:${c},justId:${$?"T":"F"},idNotIncluded:${p},filterByUnique:${E}}`;if(n+=`"${o}.${Q}.${u.$var}":{
|
|
43
43
|
`,n+=` match
|
|
44
|
-
`,
|
|
45
|
-
`:n+=` $${
|
|
46
|
-
`,
|
|
44
|
+
`,u.$filter&&(n+=` $${i}${K}${u.$var} isa ${u.$thing}`,s(u.$filter,`${i}${K}${u.$var}`)),u.$target==="role"?n+=` $${i}_intermediary (${u.$plays}: $${i}, ${C.plays}: $${i}${K}${u.$var}) isa ${u.$intermediary};
|
|
45
|
+
`:n+=` $${i}${K}${u.$var} (${u.$plays}: $${i}) isa ${u.$thing};
|
|
46
|
+
`,h){let S=`M_${v4()}`;n+=`?queryPath${S} = "${f}";
|
|
47
47
|
`,n+=` fetch
|
|
48
48
|
`,n+=`?queryPath${S} as "queryPath"
|
|
49
|
-
;`;let
|
|
50
|
-
`;}},
|
|
51
|
-
$${
|
|
49
|
+
;`;let y=h?.filter(g=>g.$fieldType==="data");y&&y.length>0&&d(y,`${i}${K}${u.$var}`);let w=h?.filter(g=>g.$fieldType==="link");w&&w.length>0&&a(w,`${i}${K}${u.$var}`,`${i}.${u.$var}`);let b=h?.filter(g=>g.$fieldType==="role");b&&b.length>0&&l(b,`${i}${K}${u.$var}`,`${i}.${u.$var}`);}n+=`};
|
|
50
|
+
`;}},m=t.length>1,M=[];(r=>{if(m)for(let i of r){let{$path:o,$thing:u,$filter:h,$fields:c}=i;if(!o)throw new Error("Path is not defined");let $=i[U];n+=`match
|
|
51
|
+
$${o} isa ${u} `,h?s(h,o):n+="; ";let p=`M_${v4()}`;if(n+=`?queryPath${p} = "${$}";
|
|
52
52
|
`,n+=`fetch
|
|
53
|
-
`,n+=`?queryPath${
|
|
54
|
-
;`,
|
|
55
|
-
$${
|
|
53
|
+
`,n+=`?queryPath${p} as "queryPath"
|
|
54
|
+
;`,c){let E=c.filter(Q=>Q.$fieldType==="data");E&&E.length>0&&d(E,o);let C=c.filter(Q=>Q.$fieldType==="link");C&&C.length>0&&a(C,o,o);let f=c.filter(Q=>Q.$fieldType==="role");f&&f.length>0&&l(f,o,o);}M.push(n),n="";}else for(let i of r){let{$path:o,$thing:u,$filter:h,$fields:c}=i;if(!o||o==="undefined")throw new Error("Path is not defined");let $=i[U];if(n+=`match
|
|
55
|
+
$${o} isa ${u} `,h?s(h,o):n+="; ",n+=`?queryPath = "${$}";
|
|
56
56
|
`,n+=`fetch
|
|
57
57
|
`,n+=`?queryPath as "queryPath"
|
|
58
|
-
;`,d){let f=d.filter(Q=>Q.$fieldType==="data");f&&f.length>0&&c(f,i);let F=d.filter(Q=>Q.$fieldType==="link");F&&F.length>0&&a(F,i,i);let $=d.filter(Q=>Q.$fieldType==="role");$&&$.length>0&&s($,i,i);}}})(t),e.tqlRequest=B?k:n;};var vt=e=>{let t=e.dataFields?.map(s=>s.path)||[],n=e.linkFields?.map(s=>s.path)||[],o=Object.keys(e.roles||{})||[];return [...t,...n,...o]},Ht=(e,t)=>Object.keys(e||{}).some(o=>{if(!Array.isArray(e[o])){let c=t.idFields?.includes(o),s=t.dataFields?.some(a=>(a.dbPath===o||a.path===o)&&a?.validations?.unique);return c||s}return !1}),Kt=(e,t)=>{let n=t.dataFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],o=t.linkFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],c=Object.keys(t.roles||{}).map(a=>({path:a,dbPath:a}))||[],s=[...n,...o,...c];return Object.entries(e||{}).reduce((a,[B,k])=>{let m=s.find(r=>r.path===B);return a[m?.dbPath||B]=k,a},{})},ye=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let o=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),c=(r,l,i,h,p)=>({$path:l,$dbPath:h,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:i,$id:r.$id,$filter:r.$filter,$isVirtual:p,$filterProcessed:!0}),s=(r,l,i,h,p)=>{let{target:d,oppositeLinkFieldsPlayedBy:u}=i;return u.map(f=>{let F=d==="role"?f.thingType:"relation",$=d==="role"?f.thing:i.relation,Q={[`$${F}`]:$},P=O(n,Q),S=r?.$fields?.filter(b=>o(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?S?g=[...r.$fields,...P.idFields]:g=r.$fields:g=vt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>o(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:F,$plays:i.plays,$playedBy:f,$path:f.path,$dbPath:p,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:d,$intermediary:f.relation,$justId:h,$id:r.$id,$filter:Kt(r.$filter,P),$idNotIncluded:S,$filterByUnique:Ht(r.$filter,P),$filterProcessed:!0}})},a=(r,l,i,h,p)=>i.playedBy.map(d=>{let{thing:u,thingType:f,relation:F}=d,$={[`$${f}`]:u},Q=O(n,$),P=r?.$fields?.filter(g=>Q?.idFields?.includes(g)||Q?.idFields?.includes(g.$path)).length===0,S=[];return typeof r!="string"?r.$fields?P?S=[...r.$fields,...Q.idFields]:S=r.$fields:S=vt(Q):S=["id"],r.$excludedFields&&(S=S.filter(g=>o(Q,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:f,$path:l,$dbPath:p,$as:r.$as||l,$var:l,$thing:u,$fields:S,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:F,$justId:h,$id:r.$id,$filter:Kt(r.$filter,Q),$idNotIncluded:P,$filterByUnique:Ht(r.$filter,Q),$playedBy:d,$filterProcessed:!0}}),B=(r,l)=>{let i=typeof r=="string"?r:r.$path,h=typeof r=="string",p=l.dataFields?.find(f=>f.path===i),d=l.linkFields?.find(f=>f.path===i),u=l.roles?.[i];if(p){let f=p.isVirtual&&p.default;return c(r,i,h,p.dbPath,f)}else {if(d)return s(r,i,d,h,d.dbPath);if(u)return a(r,i,u,h,u.dbPath)}return null},m=(r=>produce(r,l=>traverse(l,i=>{let{value:h,meta:p}=i,d=h;if(isObject(d)){if(d.$id){let u=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing},f=O(n,u);if(!f?.name)throw new Error(`Schema not found for ${d.$thing}`);if(d.$path=f.name,Array.isArray(d.$id)||(d.$filterByUnique=!0),f?.idFields?.length===1){let[F]=f.idFields;d.$filter={...d.$filter,[F]:d.$id},delete d.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in d||"$relation"in d||"$thing"in d){let u=O(n,d);if(!u?.name)throw new Error(`Schema not found for ${d.$thing}`);d.$path=u.name;}if(d.$entity?(d.$thing=d.$entity,d.$thingType="entity",delete d.$entity):d.$relation&&(d.$thing=d.$relation,d.$thingType="relation",delete d.$relation),isObject(d)&&"$thing"in d){let u=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing};d[U]=p.nodePath;let f=O(n,u);if(d.$filter&&(d.$filterByUnique=Ht(d.$filter,f),d.$filterProcessed||(d.$filter=Kt(d.$filter,f))),d.$fields){d.$fields.filter(Q=>f?.idFields?.includes(Q)||f?.idFields?.includes(Q.$path)).length>0||(d.$fields=[...d.$fields,...Array.isArray(f.idFields)?f.idFields:[]],d.$idNotIncluded=!0);let $=d.$fields?.flatMap(Q=>{let P=B(Q,f);return Array.isArray(P)?P:[P]}).filter(Boolean);d.$fields=$;}else {let $=vt(f)?.flatMap(Q=>{let P=B(Q,f);return Array.isArray(P)?P:[P]}).filter(Boolean);d.$fields=$;}d.$excludedFields&&(d.$fields=d.$fields.filter(F=>o(f,F)?!0:!d.$excludedFields.includes(F.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=m;};var Et=async(e,t)=>{let n=t.dbConnectors[0].id,o=e.typeDB?.get(n)?.session,c=e.typeDB?.get(n)?.client;if(!o||!o.isOpen()){if(!c)throw new Error("Client not found");o=await c.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:c,session:o});}return {client:c,session:o}};var Be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:o,tqlRequest:c,config:s}=e;if(!o)throw new Error("BQL request not parsed");if(!c)throw new Error("TQL request not built");let a=new TypeDBOptions;if(a.infer=!0,Array.isArray(c)){let k=await parallel(c.length,c,async m=>{let{session:r}=await Et(n,s),l=await r.transaction(TransactionType.READ,a);if(!l)throw new Error("Can't create transaction");let h=await l.query.fetch(m).collect();return await l.close(),h});t.rawTqlRes=k,t.isBatched=!0;}else {let{session:k}=await Et(n,s),m=await k.transaction(TransactionType.READ,a);if(!m)throw new Error("Can't create transaction");let l=await m.query.fetch(c).collect();await m.close(),t.rawTqlRes=l;}};var Ee=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,o=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,c=/filterByUnique:([a-zA-Z0-9_\-·]+)/,s=e.match(t),a=e.match(n),B=e.match(o),k=e.match(c);return {as:s?s[1]:null,justId:a?a[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:k?k[1]:null}},On=e=>{try{let n=(c=>{let s=c.replace("$metadata:","");return s=s.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),s=s.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,B,k)=>/^{.*}$/.test(k)?`:${k}`:`:${B}"${k}"`),s=s.replace(/\[([^\]]+)\]/g,(a,B)=>`[${B.split(",").map(k=>k.trim().startsWith("{")&&k.trim().endsWith("}")?k.trim():`"${k.trim()}"`).join(",")}]`),s})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:o,schema:c,config:s}=e,{rawTqlRes:a,isBatched:B}=t;if(n){if(!a)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let k=(d,u)=>{let{$metaData:f}=d,{as:F}=On(f),$=Object.entries(d).filter(([Q])=>Q!=="type"&&!Q.includes("$")).map(([Q,P])=>{let S=u.dataFields?.find(y=>y.path===Q||y.dbPath===Q),g=Q==="id",b=Array.isArray(F)?F.find(y=>y[Q])?.[Q]:Q,T;if(S?.cardinality==="ONE"){if(T=P[0]?P[0].value:s.query?.returnNulls?null:void 0,S.contentType==="DATE"&&(T=T&&`${T}Z`),g)return [[b,T],["$id",T]].filter(([y,L])=>L!==void 0)}else if(S?.cardinality==="MANY"){if(!isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return s.query?.returnNulls?[[b,null]]:[];S.contentType==="DATE"?T=P.map(y=>`${y.value}Z`):T=P.map(y=>y.value);}return [[b,T]].filter(([y,L])=>L!==void 0)}).flat();return Object.fromEntries([...$])},m=d=>d.reduce((u,f)=>{let{$roleFields:F,$metaData:$,$cardinality:Q}=f,{as:P,justId:S,idNotIncluded:g,filterByUnique:b}=Ee($),T=F.map(y=>{let{dataFields:L,currentSchema:M,linkFields:C,roleFields:E,schemaValue:w}=l(y),I=k(L,M);if(S==="T")return I.id;{let R=r(C),A=m(E),N={...I};return g==="true"&&M?.idFields?.forEach(D=>delete N[D]),{...N,...R,...A,...w}}});return T.length>0?u[P]=Q==="MANY"&&b==="false"?T:T[0]:s.query?.returnNulls&&(u[P]=null),u},{}),r=d=>d.reduce((u,f)=>{let{$linkFields:F,$metaData:$,$cardinality:Q}=f,{as:P,justId:S,idNotIncluded:g,filterByUnique:b}=Ee($),T=F.map(y=>{let{dataFields:L,currentSchema:M,linkFields:C,roleFields:E,schemaValue:w}=l(y),I=k(L,M);if(S==="T")return I.id;{let R=r(C),A=m(E),N={...I};return g==="true"&&M.idFields?.forEach(D=>delete N[D]),{...N,...R,...A,...w}}});return u[P]=T.length>0?Q==="MANY"&&b==="false"?T:T[0]:s.query?.returnNulls?null:void 0,u},{}),l=d=>{let u=Object.keys(d),f=u.find(y=>y.endsWith(".$dataFields"));if(!f)throw new Error("No datafields");let F=d[f],$=f.split(".")[f.split(".").length-2];if(F.$metaData=$,F.length===0)throw new Error("No datafields");let Q=F.type,P={$thing:Q.label,$thingType:Q.root,[U]:d.queryPath.value},S={[`$${P.$thingType}`]:P.$thing},g=O(c,S),b=u.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(L=>L.path===y.split(".").pop())).map(y=>({$linkFields:d[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(L=>L.path===y.split(".").pop())?.cardinality})),T=u.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:d[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:F,schemaValue:P,currentSchema:g,linkFields:b,roleFields:T}},i=d=>d.map(u=>{let{dataFields:f,currentSchema:F,linkFields:$,roleFields:Q,schemaValue:P}=l(u),S=k(f,F),g=r($),b=m(Q),T=o?.$fields?.every(L=>!F?.idFields?.includes(L)&&!F?.idFields?.includes(L.$path));return {...g,...b,...P,...!s.query?.noMetadata&&o.$id?{$id:Array.isArray(o.$id)?S.id:o.$id}:{},...T?Object.fromEntries(Object.entries(S).filter(([L])=>!F?.idFields?.includes(L))):S}}),p=(d=>{let u=f=>{let F=i(f);return o.$id&&!Array.isArray(o.$id)||n[0].$filterByUnique?F[0]??null:F.length===0?null:F};return B?d.map(u):u(d)})(a);t.bqlRes=p;};var qn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Dn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,we=e=>{let n=e.toString().replace(qn,"").trim().split("=>")[0].split("{")[0].replace(Dn,"").trim(),o=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return o?(o.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(s=>s.includes("{")&&s.includes("}")?(s.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):s.trim()).filter(Boolean):[]};var pt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!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(n){let{fn:c}=t.default,a=we(c).filter(B=>!(B 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 be=async(e,t)=>{let{schema:n,enrichedBqlQuery:o}=e,{bqlRes:c}=t;if(!c)return;let a=(B=>produce(B,k=>traverse(k,({value:m})=>{if(isObject(m)){let r=m;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:i}=l,h=r[U];if(!h)throw new Error("[Internal] QueryPath is missing");let p=getNodeByPath(o,h),d=p.$fields.map(f=>f.$path),u=p.$excludedFields;i.forEach(f=>{if(u?.includes(f)||d.length>0&&!d.includes(f))return;let F=l.dataFields?.find($=>$.path===f);if(F?.default){let $=pt({currentThing:r,fieldSchema:F,mandatoryDependencies:!0});r[f]=$;}else if(r[f]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${f}`)}),u&&u.forEach(f=>{if(typeof f!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[f];});}}})))(c);t.bqlRes=a;};var Le=async(e,t)=>{let{config:n}=e,{bqlRes:o}=t;if(!o)return;let s=(k=>produce(k,m=>traverse(m,({value:r})=>{isObject(r);})))(o),B=(k=>produce(k,m=>traverse(m,({value:r})=>{if(isObject(r)){let l=r;Object.keys(l).forEach(i=>{l[i]===void 0&&delete l[i];}),Object.getOwnPropertySymbols(l).forEach(i=>{delete l[i];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(i=>{i.startsWith("$")&&delete l[i];});}})))(s);t.bqlRes=B;};var Wn={query:[ye,$e,Be,Fe,be,Le]},Qe=async(e,t,n={},o=!0)=>{for(let c of e){let s=await c(t,n);if(s&&Array.isArray(s))for(let a of s)await Qe(a.pipeline,a.req,a.res,!1);}return o&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Lt=(e,t,n,o)=>Qe(Wn.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:o},{});var ut=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.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 Ie=(e,t,n)=>{let o=isArray(e[t])?e[t]:[e[t]];if(!o.every(c=>typeof c=="object"))if(o.every(c=>typeof c=="string")){let c=ut(t,n),[s]=c,a=e.$op==="create"?"link":"replace",B=s.thing,k=s.thingType;if(o.some(m=>m.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:a,$thing:B,$thingType:k,$bzId:`S_${v4()}`};}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(o)}`)};var Ft=(e,t,n)=>{let o=O(n,t),{usedDataFields:c}=Z(o,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"&&c.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&c.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Qt=(e,t,n)=>{let o=O(n,t),{usedFields:c}=Z(o,t);return t.$op?(Ft(e,t,n),t.$op):t.$id||t.$filter?c.length>0?(Ft(e,{...t,$op:"update"},n),"update"):(Ft(e,{...t,$op:"link"},n),"link"):(Ft(e,{...t,$op:"create"},n),"create")};var Ce=(e,t)=>{let o=(isArray(e.$root)?e.$root:[e.$root]).map(c=>{let s=Qt(c,c,t);return {...{...c.$thing?{}:{$thing:c.$entity||c.$relation},...c.$thingType?{}:{$thingType:ue(c,t)},...c.$op?{}:{$op:s},...c.$bzId?{}:{$bzId:`R_${v4()}`}},...c}});e.$root=isArray(e.$root)?o:o[0];};var It=(e,t)=>{let n=t[kt];return isSet(n)?n.has("clean")?(Reflect.set(t,kt,n.add("clean")),!0):!1:(Reflect.set(t,kt,new Set(["clean"])),!0)};var Se=(e,t,n)=>{if(It("split_ids",e)){let o=(isArray(e[t])?e[t]:[e[t]]).flatMap(c=>{if(isObject(c)&&"$id"in c&&isArray(c.$id)){let s=c;if(O(n,s),!s.$bzId)throw new Error("[Internal Error] No bzId found");return s.$id.map((a,B)=>({...J(s),$id:a,$bzId:`${s.$bzId}_${B}`,...H(s)}))}return c});(o.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=o);}};var Ae=(e,t,n,o)=>{let c=(isArray(e[t])?e[t]:[e[t]]).map(s=>{let a=ut(t,n),[B]=a,k=Qt(e,{...s,$thing:B.thing,$thingType:B.thingType},o),m=s.$bzId?s.$bzId:s.$tempId?s.$tempId:`N_${v4()}`;if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);return {...s,[rt]:n,$thing:B.thing,$thingType:B.thingType,$op:k,$bzId:m}});e[t]=isArray(e[t])?c:c[0];};var Oe=(e,t,n)=>{let o=e[t];o&&(isArray(o)?o:[o]).forEach(c=>{let s=O(n,c),{unidentifiedFields:a}=Z(s,c),{computedFields:B,virtualFields:k}=s,m=listify(c,(i,h)=>h!==void 0?i:void 0),r=m.filter(i=>k?.includes(i));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(i=>!m.includes(i)).forEach(i=>{let h=s.dataFields?.find(F=>F.path===i),d=s.linkFields?.find(F=>F.path===i)?.oppositeLinkFieldsPlayedBy[0],u="roles"in s?de(s.roles,(F,$)=>F===i):void 0,f=h||d||u;if(!f)throw new Error(`no field Def for ${i}`);if(c.$op==="create"&&!c[i]){let F=pt({currentThing:c,fieldSchema:f,mandatoryDependencies:!0});c[i]=F;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(c)}`)});};var qe=(e,t,n)=>{let o=ut(t,n),[c]=o;e[t]={$thing:c.thing,$thingType:c.thingType,$op:"unlink",$bzId:`U_${v4()}`,[rt]:n};};var Pt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let o=`on${he(e.$op)}`;return n.pre.filter(a=>a.triggers[o]?.()).flatMap(a=>a.actions)}return []};var je=(e,t,n,o)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(s=>{if("$thing"in s){let{requiredFields:a,enumFields:B,fnValidatedFields:k,dataFields:m}=O(n,s);if("$op"in s&&s.$op==="create"&&a.forEach(r=>{if(!(r in s))throw new Error(`[Validations] Required field "${r}" is missing.`)}),("$op"in s&&s.$op==="update"||s.$op==="create")&&B.forEach(r=>{if(r in s){let l=m?.find(i=>i.path===r)?.validations?.enum;if(!l)throw new Error(`[Validations] Enum field "${r}" is missing enum options.`);if(isArray(s[r]))s[r].some(i=>{if(!l.includes(i))throw new Error(`[Validations] Option "${i}" is not a valid option for field "${r}".`)});else if(l&&!l.includes(s[r]))throw new Error(`[Validations] Option "${s[r]}" is not a valid option for field "${r}".`)}}),("$op"in s&&s.$op==="update"||s.$op==="create")&&k.forEach(r=>{if(r in s)try{let l=m?.find(i=>i.path===r)?.validations?.fn;if(!l)throw new Error("Missing validation function.");if(!l(s[r]))throw new Error("Failed validation function.")}catch(l){throw new Error(`[Validations:attribute:${r}] ${l.message}`)}}),isObject(s)&&"$thing"in s){let r=s.$thing,l=s,i=clone(J(e)),h=clone(J(l)),p=o.mutation?.context||{};Pt(l,n).forEach(u=>{if(u.type==="validate"){if(u.severity!=="error")return;try{let f=u.fn(h,i,p);if(f===!1)throw new Error(`${u.message}.`);if(f!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(f){throw new Error(`[Validations:thing:${r}] ${f.message}`)}}});}}});};var We=(e,t,n,o)=>{let c=(isArray(e[t])?e[t]:[e[t]]).map(s=>{if(Mt(s)){let a=Pt(s,n).filter(r=>r.type==="transform"),B=clone(J(e)),k=clone(J(s)),m=o.mutation?.context||{};return a.forEach(r=>{let l=r.fn(k,B,m);Object.keys(l).length!==0&&(s={...k,...l,...H(s)});}),s}});e[t]=isArray(e[t])?c:c[0];};var ir=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(It("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},or=(e,t)=>{},Zt=(e,t,n)=>{let c=produce({$rootWrap:{$root:e}},s=>traverse(s,({value:a,parent:B,key:k,meta:m})=>{if(!(!B||!k)&&isObject(a)){if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a))throw k==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}let r=a;Object.keys(r).forEach(l=>{if(ir(r,l),l!=="$root"&&l.startsWith("$"))return;let i=l!=="$root"?Wt(t,r,l):{fieldType:"rootField"};if(!i)throw new Error(`[Internal] Field ${l} not found in schema`);if("contentType"in i)return or();if(["rootField","linkField","roleField"].includes(i.fieldType)){if(["linkField","roleField"].includes(i.fieldType)&&Ie(r,l,i),i.fieldType==="rootField"){if(!("$root"in r))throw new Error(`[Internal] Field ${l} is a rootField but the object is not a root`);Ce(r,t);}let h=isArray(r[l])?r[l]:[r[l]],p=m.nodePath?.split(".").slice(1).join(".");h.forEach(u=>{if(u){if(i?.cardinality==="ONE"&&!u.$op&&!u.$id&&!u.$filter&&!u.$tempId&&r.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${p}.${l}`);if(u.$tempId&&!(u.$op===void 0||u.$op==="link"||u.$op==="create"||u.$op==="update"))throw new Error(`Invalid op ${u.$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(i.fieldType)&&(r[l]===null?qe(r,l,i):Ae(r,l,i,t)),Se(r,l,t),["rootField","linkField","roleField"].includes(i.fieldType)&&Oe(r,l,t),(isArray(r[l])?r[l]:[r[l]]).forEach(u=>{let f=O(t,u),{unidentifiedFields:F,usedLinkFields:$,usedFields:Q,fields:P}=Z(f,u);if(Q.forEach(S=>{if(!P.includes(S))throw new Error(`[Schema] Field ${S} not found in the schema`)}),F.length>0)throw new Error(`Unknown fields: [${F.join(",")}] in ${JSON.stringify(a)}`);if($.length>1){let S=f.linkFields?.filter(g=>$.includes(g.path));S?.some((g,b)=>S.some((T,y)=>{if(b!==y&&g.target!==T.target&&g.relation===T.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),We(r,l,t,n),je(r,l,t,n);}});}}));return isArray(c.$rootWrap.$root),c.$rootWrap.$root};var _e=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:o}=await Et(t,n),c=await o.transaction(TransactionType.WRITE);if(!c)throw new Error("Can't create transaction");let s=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;s&&await c.query.delete(s);let B=a&&c.query.insert(a);try{let k=B?await B.collect():void 0;return await c.commit(),await c.close(),{insertions:k}}catch(k){throw await c.close(),new Error(`Transaction failed: ${k.message}`)}};var Ve=async(e,t,n,o)=>{let c=[...t,...n],s=c.map(a=>{let B=e.insertions?.find(k=>k.get(`${a.$bzId}`))?.get(`${a.$bzId}`);if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!B&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let k=B?.asThing().iid;if(o.mutation?.noMetadata)return Object.entries(a).filter(([l,i])=>!l.startsWith("$")).reduce((l,[i,h])=>{if(a.$thingType==="relation"){let p=c.filter(d=>d.$id&&d.$bzId===h);if(p.length>1)throw new Error(`Multiple things with the same bzId ${h}`);return p.length===1?(l[i]=p[0].$id,l):(l[i]=h,l)}return l[i]=h,l},{});let m=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:k,...a,[a.path]:a.$id,...m}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(s)};var ve=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(s=>s.startsWith("$")).forEach(s=>delete n[s]),Object.keys(n).filter(s=>typeof s=="symbol").forEach(s=>delete n[s])),n);return produce(e,n=>traverse(n,t))};var Je=async(e,t)=>{let n=m=>{let r=[],l=[],i=u=>{if(u.$id)return u.$id;let f=O(t,u),{idFields:F}=f;if(!F)throw new Error(`no idFields: ${JSON.stringify(u)}`);let[$]=F;if(!$)throw new Error(`no idField: ${JSON.stringify(u)}`);let Q=f.dataFields?.find(g=>g.path===$),P=pt({currentThing:u,fieldSchema:Q,mandatoryDependencies:!0}),S=u[$]||u.$id||P;if(!S)throw new Error(`no idValue: ${JSON.stringify(u)}`);return S},h=u=>{if(u.$op==="create"){let f=i(u);if(r.find(F=>F.$id===f))throw new Error(`Duplicate id ${f} for node ${JSON.stringify(u)}`);if(l.find(F=>F.$bzId===u.$bzId))throw new Error(`Duplicate $bzid ${u.$bzId} for node ${JSON.stringify(u)}`);r.push({...u,$id:f});return}u.$tempId&&u.$op==="match"||r.push(u);},p=u=>{if(u.$op==="create"){let f=i(u);if(r.find(F=>F.$id===f),l.find(F=>F.$bzId===u.$bzId))throw new Error(`Duplicate %bzId ${u.$bzIdd} for edge ${JSON.stringify(u)}`);l.push({...u,$id:f});return}l.push(u);};return traverse(m,({value:u,parent:f,meta:F})=>{if(!isObject(u))return;let $=u;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let Q=O(t,$),{dataFields:P,roleFields:S,linkFields:g,usedFields:b}=Z(Q,$),T=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let M=b.filter(w=>P?.includes(w)),C=b.filter(w=>S?.includes(w)),E=b.filter(w=>g?.includes(w));if(M.length>0)return "update";if(C.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...shake(pick($,P||[""])),$op:T(),$bzId:$.$bzId};h(y);let L=$[rt];if(L?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let M=L.relation===$.$thing,C=M?$.$bzId:`LT_${v4()}`,w=fe(m,f,F).$bzId;if(!w)throw new Error("No parent id found");let I=()=>{if($.$op==="delete")return M?"match":"delete";if($.$op==="unlink")return M?"unlink":"delete";if($.$op==="link"||$.$op==="create")return M?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R=O(t,{$thing:L.relation,$thingType:"relation"});if(!Object.keys(R.roles).includes(L.plays))throw new Error(`[Wrong format] Field ${L.plays} is not a role of relation ${L.relation}`);let N={$bzId:C,$thing:L.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:I(),...M?{}:{[L.path]:$.$bzId},[L.plays]:w,[rt]:L,[at]:"linkField"};p(N),($.$op==="unlink"||I()==="unlink")&&M&&p({$thing:L.relation,$thingType:"relation",$bzId:C,$op:"match",[L.plays]:w,[rt]:L,[at]:"linkField"});}if($.$thingType==="relation"){let M=Bt($,(w,I)=>S.includes(w)),C=mapEntries(M,(w,I)=>isArray(I)?[w,I]:isObject(I)?[w,I.$bzId]:[w,I]),E=Bt(u,(w,I)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(M).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},I=O(t,$).roles,R=mapEntries(C,(N,D)=>{let z=I[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(K=>K.$bzId||K)]}return [N,D.$bzId||D]}),A={...E,$thing:$.$thing,$thingType:"relation",$op:w(),...R,$bzId:$.$bzId,[at]:"roleField"};p(A);return}if($.$op==="match"||$.$op==="update"&&Object.keys(M).length>0){let w=0;Object.entries(M).forEach(([I,R])=>{let A=isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;A.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let K={...E,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[I]:D.$bzId,$bzId:$.$bzId,[at]:"roleField"};p(K);});});}}}}}),[r,l]},[o,c]=n(e),s=o.reduce((m,r)=>{if(!r.$bzId)return [...m,r];let l=m.findIndex(i=>i.$bzId===r.$bzId);if(l===-1)return [...m,r];if(m[l].$op==="create"&&r.$op==="match")return m;if(m[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...m.slice(0,l),r,...m.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${m[l].$op}. Current: ${r.$op}`)},[]),a=c.reduce((m,r)=>{let l=m.find(i=>(i.$id&&i.$id===r.$id||i.$bzId&&i.$bzId===r.$bzId)&&i.$thing===r.$thing&&i.$op===r.$op);if(l){let i={...l};return Object.keys(r).forEach(p=>{if(typeof p=="symbol"||p.startsWith("$"))return;let d=l[p],u=r[p];Array.isArray(d)&&Array.isArray(u)?i[p]=Array.from(new Set([...d,...u])):!Array.isArray(d)&&Array.isArray(u)?d!==void 0?i[p]=Array.from(new Set([d,...u])):i[p]=u:Array.isArray(d)&&!Array.isArray(u)?u!==void 0&&(i[p]=Array.from(new Set([...d,u]))):d!==null&&u!==null&&d!==void 0&&u!==void 0?i[p]=Array.from(new Set([d,u])):d==null&&(i[p]=u);}),[...m.filter(p=>!((p.$id&&p.$id===r.$id||p.$bzId&&p.$bzId===r.$bzId)&&p.$thing===r.$thing&&p.$op===r.$op)),i]}return [...m,r]},[]);s.forEach(m=>{if((m.$thingType==="relation"||"relation"in m)&&a.filter(r=>r.$bzId===m.$bzId||r.$tempId&&r.$tempId===m.$tempId).length===0){if(m.$op==="delete"||m.$op==="match"||m.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(ve(m))}`)}});let B=[...s,...a];return new Set(B.filter(m=>m.$tempId).map(m=>m.$tempId)).forEach(m=>{if(B.filter(r=>r.$tempId===m&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:s,mergedEdges:a}};var Ze=async(e,t,n)=>{let o=i=>{let h=i.$op,p=`$${i.$bzId}`,d=O(n,i),{idFields:u,defaultDBConnector:f}=d,F=f?.path||i.$thing,$=i.$id,Q=u?.[0],P=listify(i,(C,E)=>{if(C.startsWith("$")||C===Q||E===void 0||E===null)return "";let w=d.dataFields?.find(A=>A.path===C);if(!w?.path)return "";let R=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${R} '${E}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${R} ${E}`;if(w.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${R} ${E.toISOString().replace("Z","")}`:`has ${R} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(C=>C),S=`${p}-atts`,g=listify(i,C=>{if(C.startsWith("$")||C===Q)return "";let E=d.dataFields?.find(R=>R.path===C);if(!E?.path)return "";let I=E.dbPath;return `{${S} isa ${I};}`}).filter(C=>C),b=isArray($)?`like '${$.join("|")}'`:`'${$}'`,T=$?[`has ${Q} ${b}`]:[],y=[...T,...P].filter(C=>C).join(","),L=()=>{if(h==="delete"||h==="unlink"||h==="match")return `${p} isa ${[F,...T].filter(C=>C).join(",")};`;if(h==="update"){if(!g.length)throw new Error("update without attributes");return `${p} isa ${[F,...T].filter(C=>C).join(",")}, has ${S};
|
|
59
|
-
${g.join(" or ")};`}return ""},M=()=>h==="update"||h==="link"||h==="match"?`${p} isa ${[F,...T].filter(C=>C).join(",")};`:"";if(Mt(i))return {op:h,deletionMatch:L(),insertionMatch:M(),insertion:h==="create"?`${p} isa ${[F,y].filter(C=>C).join(",")};`:h==="update"&&P.length?`${p} ${P.join(",")};`:"",deletion:h==="delete"?`${p} isa ${F};`:h==="update"&&g.length?`${p} has ${S};`:""};throw new Error("in attributes")},c=i=>{let h=i.$op,p=O(n,i),d=`$${i.$bzId}`,u=i.$id,f=p.defaultDBConnector?.path||i.$thing,F="roles"in p?listify(p.roles,E=>E):[],$="roles"in p?mapEntries(p.roles,(E,w)=>[E,w.dbConnector?.path||E]):{},Q=listify(i,(E,w)=>{if(!F.includes(E))return null;if(!("roles"in p))throw new Error("This should have roles! ");let I=$[E];return Array.isArray(w)?w.map(R=>({path:I,id:R})):{path:I,id:w}}).filter(E=>E).flat(),P=Q.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),S=Q.length>0?`( ${P.join(" , ")} )`:"",g=i[at];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=S?`${d} ${S} ${g==="linkField"||h==="delete"||h==="unlink"?`isa ${f}`:""}`:"",T=`${d} ${g==="linkField"||h==="delete"?`isa ${f}`:""}`,y=()=>b?h==="link"?`${b};`:h==="create"?`${b}, has id '${u}';`:"":"",L=()=>b&&h==="match"?`${b};`:"",M=()=>b?h==="delete"?`${b};`:h==="match"?`${b};`:"":"",C=()=>b?h==="delete"?`${T};`:h==="unlink"?`${d} ${S};`:"":"";return {deletionMatch:M(),insertionMatch:L(),deletion:C(),insertion:y(),op:""}},s=(i,h)=>{let p=h==="edges"?c:o;if(Array.isArray(i))return i.map(Q=>{let{preDeletionBatch:P,insertionMatch:S,deletionMatch:g,insertion:b,deletion:T}=p(Q);return shake({preDeletionBatch:P,insertionMatch:S,deletionMatch:g,insertion:b,deletion:T},y=>!y)}).filter(Q=>Q);let{preDeletionBatch:d,insertionMatch:u,deletionMatch:f,insertion:F,deletion:$}=p(i);return shake({preDeletionBatch:d,insertionMatch:u,deletionMatch:f,insertion:F,deletion:$},Q=>!Q)},a=s(e),B=Array.isArray(a)?a:[a],k=s(t,"edges"),m=Array.isArray(k)?k:[k],r=[...B,...m];return shake({insertionMatches:r.map(i=>i.insertionMatch).join(" ").trim(),deletionMatches:r.map(i=>i.deletionMatch).join(" ").trim(),insertions:r.map(i=>i.insertion).join(" ").trim(),deletions:r.map(i=>i.deletion).join(" ").trim()},i=>!i)};var mr=Symbol.for("grandChildOfCreate"),Ye=async(e,t,n,o)=>{let c=(g,b)=>Object.keys(g).filter(T=>T.startsWith("$")?!1:b?!O(t,g).dataFields?.find(L=>L.path===T):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let s=[];if(traverse(e,({parent:g,key:b,value:T})=>{g&&b&&!b.includes("$")&&isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(L=>{if(isObject(L)){if(g.$op!=="create")s.includes(L.$op)||s.push(L.$op);else if(L.$op==="delete"||L.$op==="unlink")throw new Error(`Cannot ${L.$op} under a create`)}}):!g&&isObject(T)&&(s.includes(T.$op)||s.push(T.$op));}),!s.includes("delete")&&!s.includes("unlink")&&!s.includes("replace")&&!s.includes("update")&&!s.includes("link"))return;let B=(g=>{let b=(T,y)=>{let L=[],M={},C=["$op","$bzId","$parentKey"],E=["$relation","$entity","$id",...C];for(let w in T)if(!C.includes(w)&&!(E.includes(w)&&!y))if(!w.includes("$")&&(isObject(T[w])||Array.isArray(T[w]))){let I=T[w];Array.isArray(I)&&I.length>0?I.forEach(R=>{L.push({$path:w,...b(R)});}):L.push({$path:w,...b(I)});}else M[w]=T[w];return {...M,$fields:L}};return g.map(T=>b(T,!0))})(Array.isArray(e)?e:[e]),k=await Lt(B,n,t,o),m=(g,b)=>{let T=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,L=y?.beforePath||"root",M=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${L}.${M}___${y.key}`,ids:T,key:b}}else return {beforePath:"root",ids:T,key:b}},r=(g,b)=>{let T=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${T}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,T,y]=g.split(/[[\]]/);return T.split(",").map(M=>`${b}${M}${y}`)}else return [g]},i={};(g=>produce(g,b=>traverse(b,T=>{let{key:y,parent:L}=T;if(L&&y&&L.$id&&!y.includes("$")){let M=m(L,y),C=r(M);if(Array.isArray(L[y])){let E=[];L[y].forEach(w=>{isObject(w)?(w.$objectPath=M,E.push(w.$id.toString())):w&&E.push(w.toString());}),i[C]={$objectPath:M,$ids:E};}else {let E=L[y];isObject(E)?(i[C]={$objectPath:M,$ids:[E.$id.toString()]},E.$objectPath=M):E&&(i[C]={$objectPath:M,$ids:[E.toString()]});}}})))(k||{});let p=g=>produce(g,b=>traverse(b,T=>{let{key:y,value:L,parent:M}=T;M&&y&&!y.includes("$")&&(Array.isArray(L)||isObject(L))&&!Array.isArray(M)&&(Array.isArray(M[y])?M[y].forEach(C=>{typeof C!="string"&&(C.$objectPath=m(M,y),C.$parentIsCreate=M.$op==="create",C[mr]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[y])&&(M[y].$parentIsCreate=M.$op==="create",M[y][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[y].$objectPath=m(M,y)));})),d=p(e),f=(g=>{let b=(M,C)=>{let E=[];M.filter(A=>A).forEach(A=>{let N=Object.keys(A).filter(D=>!D.startsWith("$")).length;if(Array.isArray(A.$id)&&N>0){let D=A.$id.map(z=>({...A,$id:z}));E=[...E,...D];}else E.push({...A});});let w=[],I=[],R=E.filter(A=>{let D=["delete","update","unlink"].includes(A.$op||""),z=c(A,!0).length;if((!A.$id||Array.isArray(A.$id)&&z>0||A.$filter)&&D)return !0;I.push({...A});});return R.length>0?R.forEach(A=>{let D=(j=>{let $t=(()=>{let _={};for(let x in j){let nt=O(t,j);!x.startsWith("$")&&nt.dataFields?.find(dt=>dt.path===x)&&(_[x]=j[x]);}return _})(),mt=Object.keys(j),et=mt.filter(_=>!_.startsWith("$")),Ot=[],bt=(_,x)=>{if(_===et.length){let dt={...x};mt.forEach(V=>{V.startsWith("$")&&(dt[V]=j[V]);}),Ot.push(dt);return}let nt={...x,[et[_]]:j[et[_]],...H(x),...$t};bt(_+1,nt),bt(_+1,x);};return bt(0,{...H(j)}),Ot})(A).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(ot=>!ot.startsWith("$")).length===0)),z=[],K=r(A.$objectPath),tt=i[K]?i[K].$ids:[],q=D.map((j,ot)=>{let $t=O(t,j),et=Object.keys(j).filter(x=>!x.includes("$")&&!$t.dataFields?.some(nt=>nt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):j[x]:[j[x]]).map(V=>{let qt=r(V.$objectPath);return {idsToKey:(Dt=>{let ie=[],gt=Dt.split("."),Bn=gt.slice(0,gt.length-1).join("."),En=gt.slice(gt.length-1,gt.length)[0].split("___")[1];for(let xt in i)if(xt.startsWith(Bn)&&xt.endsWith(En)){let jt=xt.split("."),Fn=jt.slice(jt.length-1,jt.length)[0].split("___")[0];ie.push(Fn);}return ie})(qt),key:x,multiple:V}})).filter(x=>x!==void 0),_=(x=>{let nt=x.map(V=>V.map(st=>st.idsToKey));return (V=>V.length>0?V.reduce((st,yt)=>st.concat(yt),[]).reduce((st,yt)=>st?yt.filter(Dt=>st.includes(Dt)):yt):[])(nt)})(et).filter(x=>!z.includes(x));if(z=[...z,..._],tt=tt.filter(x=>!_.includes(x)),ot===D.length-1&&tt.length>0)return {...j,$id:tt,$bzId:`T1_${v4()}`,...H(j)};if(_.length>0)return {...j,$id:_,$bzId:`T2_${v4()}`,...H(j)}}).filter(j=>j!==void 0),gn=(()=>{if(q.length===0&&!C?.$id)return R;if(q.length===0&&C?.$id){let j=Array.isArray(C.$id)?C.$id:[C.$id],ot=[];return j.forEach($t=>{let mt=r({...A.$objectPath,ids:$t}),et=i[mt];et&&ot.push({...A,$id:et.$ids,...H(A),$bzId:`T_${v4()}`});}),ot}else return q.filter(j=>j!==void 0)})();w=[...I,...gn].map(T);}):w=E.map(T),w},T=M=>{let C={...M,$bzId:M.$tempId??`T3_${v4()}`,...H(M)},E=O(t,M);return Object.keys(M).filter(w=>!w.includes("$")&&!E.dataFields?.some(I=>I.path===w)).forEach(w=>{let I=Array.isArray(M[w])?M[w]:[M[w]],R=b(I,M);C[w]=R.length>0?R:void 0;}),C},y=[];return g.forEach(M=>{y=[...y,...b([M])];}),y.map(M=>T(M))})(Array.isArray(d)?d:[d]),F=g=>g.map(b=>{let T=c(b,!0),y={...b};return T.forEach(L=>{let M=Array.isArray(b[L])?b[L]:[b[L]],C=[],E=[],w=[],I={},R=_t(t,b,L);M.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(I=q,Array.isArray(q.$id)?E=[...E,...q.$id]:E.push(q.$id)):q.$op==="create"&&R==="ONE"&&q.id?(I=q,Array.isArray(q.id)?w=[...E,...q.id]:w.push(q.id)):C.push(q);});let A=r(I.$objectPath),D=l(A).map(q=>i[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let K=z.filter(q=>!E.includes(q)),At=E.filter(q=>!z.includes(q)),tt=H(I);K.length>0&&C.push({...I,$op:"unlink",$id:K,$bzId:`T4_${v4()}`,id:void 0,...tt}),At.length>0&&At.forEach(q=>{C.push({...I,$op:"link",$id:q,$bzId:`T5_${v4()}`,...tt});}),w.length>0&&w.forEach(q=>{C.push({...I,$op:"create",id:q,$bzId:`T6_${v4()}`,...tt});}),y[L]=F(C);}),y}),$=p(F(p(f)));return (g=>produce(g,b=>traverse(b,T=>{let{key:y,value:L,parent:M}=T;y&&M&&!y?.includes("$")&&(Array.isArray(L)||isObject(L))&&!Array.isArray(M)&&(Array.isArray(L)?L:[L]).forEach(E=>{let w=i[r(E.$objectPath)],I=(N,D)=>N.every(z=>D.includes(z)),R=E.$id?Array.isArray(E.$id)?I(E.$id,w?w.$ids:[]):w?.$ids.includes(E.$id):w,A=_t(t,M,E.$objectPath.key);if(E.$op==="link"&&R&&A==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(E.$objectPath)}" because it is already occupied.`);if(E.$op)switch(E.$op){case"delete":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"update":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"unlink":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"link":if(R)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${E.$id}" because it is already linked to $id:"${M.$id}"`);break;}});})))($),(g=>produce(g,b=>traverse(b,T=>{let{value:y,meta:L}=T;isObject(y)&&(y[Symbol.for("path")]=L.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};function W(e){return {enumerable:!0,value:e}}function Ge(e){return {enumerable:!0,writable:!0,value:e}}var ht={},yr=()=>!0,Xe=()=>({}),en=e=>e,gr=(e,t,n,o)=>e.apply(n,o)&&t.apply(n,o),Br=(e,t,n,[o,c])=>t.call(n,e.call(n,o,c),c),it=(e,t)=>Object.freeze(Object.create(e,t));function tn(e,t,n){return e.reduce((o,c)=>function(...s){return n(o,c,this,s)},t)}function nn(e){return it(this,{fn:W(e)})}var rn={},G=nn.bind(rn);var on={},sn=nn.bind(on);function Rt(e,t){return t.filter(n=>e.isPrototypeOf(n))}function an(e,t,...n){let o=tn(Rt(on,n).map(s=>s.fn),yr,gr),c=tn(Rt(rn,n).map(s=>s.fn),en,Br);return it(this,{from:W(e),to:W(t),guards:W(o),reducers:W(c)})}var ln={},cn={},X=an.bind(ln);an.bind(cn,null);function Er(e,t,n){return Xt(t,e,n,this.immediates)||e}function dn(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Fr={enter:en};function pn(...e){let t=Rt(ln,e),n=Rt(cn,e),o={final:W(e.length===0),transitions:W(dn(t))};return n.length&&(o.immediates=W(n),o.enter=W(Er)),it(Fr,o)}var wr={enter(e,t,n){let o=this.fn.call(t,t.context,n);return Gt.isPrototypeOf(o)?it(un,{machine:W(o),transitions:W(this.transitions)}).enter(e,t,n):(o.then(c=>t.send({type:"done",data:c})).catch(c=>t.send({type:"error",error:c})),e)}},un={enter(e,t,n){if(t.child=te(this.machine,o=>{t.onChange(o),t.child==o&&o.machine.state.value.final&&(delete t.child,t.send({type:"done",data:o.context}));},t.context,n),t.child.machine.state.value.final){let o=t.child.context;return delete t.child,Xt(t,e,{type:"done",data:o},this.transitions.get("done"))}return e}};function ct(e,...t){let n=W(dn(t));return Gt.isPrototypeOf(e)?it(un,{machine:W(e),transitions:n}):it(wr,{fn:W(e),transitions:n})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function hn(e,t,n=Xe){return typeof e!="string"&&(n=t||Xe,t=e,e=Object.keys(t)[0]),ht._create&&ht._create(e,t),it(Gt,{context:W(n),current:W(e),states:W(t)})}function Xt(e,t,n,o){let{context:c}=e;for(let{to:s,guards:a,reducers:B}of o)if(a(c,n)){e.context=B.call(e,c,n);let k=t.original||t,m=it(k,{current:W(s),original:{value:k}});ht._onEnter&&ht._onEnter(t,s,e.context,c,n);let r=m.state.value;return e.machine=m,e.onChange(e),r.enter(m,e,n)}}function br(e,t){let n=t.type||t,{machine:o}=e,{value:c,name:s}=o.state;return c.transitions.has(n)?Xt(e,o,t,c.transitions.get(n))||o:(ht._send&&ht._send(n,s),o)}var Tr={send(e){br(this,e);}};function te(e,t,n,o){let c=Object.create(Tr,{machine:Ge(e),context:Ge(e.context(n,o)),onChange:W(t)});return c.send=c.send.bind(c),c.machine=c.machine.state.value.enter(c.machine,c,o),c}var fn=pn,ee=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Mr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),kr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Lr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Qr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Ir=async e=>Object.keys(e.bql.current).length?Zt(e.bql.current,e.schema,e.config):Zt(e.bql.raw,e.schema,e.config),Pr=async e=>Ye(e.bql.current,e.schema,e.config,e.handles),Cr=async e=>Je(e.bql.current,e.schema),Sr=async e=>Ze(e.bql.things,e.bql.edges,e.schema),Rr=async e=>_e(e.typeDB.tqlMutation,e.handles,e.config),Ar=async e=>Ve(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),Or=()=>!0,ft=X("error","error",G((e,t)=>({...e,error:t.error}))),qr=hn("enrich",{enrich:ct(Ir,X("done","preQuery",sn(Or),G(ee)),X("done","parseBQL",G(ee)),ft),preQuery:ct(Pr,X("done","parseBQL",G(ee)),ft),parseBQL:ct(Cr,X("done","buildMutation",G(kr)),ft),buildMutation:ct(Sr,X("done","runMutation",G(Lr)),ft),runMutation:ct(Rr,X("done","parseMutation",G(Qr)),ft),parseMutation:ct(Ar,X("done","success",G(Mr)),ft),success:fn(),error:fn()},e=>e),Dr=async e=>new Promise((t,n)=>{te(qr,o=>{o.machine.state.name==="success"&&t(o.context),o.machine.state.name==="error"&&n(o.context);},e);}),$n=async(e,t,n,o)=>Dr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:o,depthLevel:0,error:null});enableMapSet();var re=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async o=>{if(o.provider==="typeDB"&&o.dbName){let[c,s]=await tryit(TypeDB.coreDriver)(o.url);if(c){let a=`[BORM:${o.provider}:${o.dbName}:core] ${c.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await s.session(o.dbName,SessionType.DATA);t.typeDB.set(o.id,{client:s,session:a});}catch(a){let B=`[BORM:${o.provider}:${o.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(o.provider==="typeDBCluster"&&o.dbName){let[c,s]=await tryit(TypeDB.cloudDriver)(o.addresses,o.credentials);if(c){let a=`[BORM:${o.provider}:${o.dbName}:core] ${c.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(o.dbName,SessionType.DATA);t.typeDB.set(o.id,{client:s,session:a});}catch(a){let B=`[BORM:${o.provider}:${o.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=pe(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),se(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let o={...this.config,query:{...Nt.query,...this.config.query,...n}};return Lt(t,o,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let o={...this.config,mutation:{...Nt.mutation,...this.config.mutation,...n}},[c,s]=await tryit($n)(t,this.schema,o,this.dbHandles);if(c)throw console.error(c.error.stack.split(`
|
|
60
|
-
`).slice(0,4).join(`
|
|
61
|
-
`)),new Error(c.error.message);return s.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Hs=re;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
58
|
+
;`,c){let p=c.filter(f=>f.$fieldType==="data");p&&p.length>0&&d(p,o);let E=c.filter(f=>f.$fieldType==="link");E&&E.length>0&&a(E,o,o);let C=c.filter(f=>f.$fieldType==="role");C&&C.length>0&&l(C,o,o);}}})(t),e.tqlRequest=m?M:n;};var Ht=e=>{let t=e.dataFields?.map(l=>l.path)||[],n=e.linkFields?.map(l=>l.path)||[],s=Object.keys(e.roles||{})||[];return [...t,...n,...s]},Kt=(e,t)=>Object.keys(e||{}).some(s=>{if(!Array.isArray(e[s])){let d=t.idFields?.includes(s),l=t.dataFields?.some(a=>(a.dbPath===s||a.path===s)&&a?.validations?.unique);return d||l}return !1}),vt=(e,t)=>{let n=t.dataFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],s=t.linkFields?.map(a=>({path:a.path,dbPath:a.dbPath}))||[],d=Object.keys(t.roles||{}).map(a=>({path:a,dbPath:a}))||[],l=[...n,...s,...d];return Object.entries(e||{}).reduce((a,[m,M])=>{let k=l.find(r=>r.path===m);return a[k?.dbPath||m]=M,a},{})},ye=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let s=(r,i)=>typeof i=="string"?r.idFields?.includes(i):r.idFields?.includes(i.$path),d=(r,i,o,u,h)=>({$path:i,$dbPath:u,$thingType:"attribute",$as:r.$as||i,$var:i,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:h,$filterProcessed:!0}),l=(r,i,o,u,h)=>{let{target:c,oppositeLinkFieldsPlayedBy:$}=o;return $.map(p=>{let E=c==="role"?p.thingType:"relation",C=c==="role"?p.thing:o.relation,f={[`$${E}`]:C},Q=O(n,f),S=r?.$fields?.filter(w=>s(Q,w)).length===0,y=[];return typeof r!="string"?r.$fields?S?y=[...r.$fields,...Q.idFields]:y=r.$fields:y=Ht(Q):y=["id"],r.$excludedFields&&(y=y.filter(w=>s(Q,w)?!0:!r.$excludedFields.includes(w.$path))),{$thingType:E,$plays:o.plays,$playedBy:p,$path:p.path,$dbPath:h,$as:r.$as||i,$var:i,$thing:C,$fields:y,$excludedFields:r.$excludedFields,$fieldType:"link",$target:c,$intermediary:p.relation,$justId:u,$id:r.$id,$filter:vt(r.$filter,Q),$idNotIncluded:S,$filterByUnique:Kt(r.$filter,Q),$filterProcessed:!0}})},a=(r,i,o,u,h)=>o.playedBy.map(c=>{let{thing:$,thingType:p,relation:E}=c,C={[`$${p}`]:$},f=O(n,C),Q=r?.$fields?.filter(y=>f?.idFields?.includes(y)||f?.idFields?.includes(y.$path)).length===0,S=[];return typeof r!="string"?r.$fields?Q?S=[...r.$fields,...f.idFields]:S=r.$fields:S=Ht(f):S=["id"],r.$excludedFields&&(S=S.filter(y=>s(f,y)?!0:!r.$excludedFields.includes(y.$path))),{$thingType:p,$path:i,$dbPath:h,$as:r.$as||i,$var:i,$thing:$,$fields:S,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:u,$id:r.$id,$filter:vt(r.$filter,f),$idNotIncluded:Q,$filterByUnique:Kt(r.$filter,f),$playedBy:c,$filterProcessed:!0}}),m=(r,i)=>{let o=typeof r=="string"?r:r.$path,u=typeof r=="string",h=i.dataFields?.find(p=>p.path===o),c=i.linkFields?.find(p=>p.path===o),$=i.roles?.[o];if(h){let p=h.isVirtual&&h.default;return d(r,o,u,h.dbPath,p)}else {if(c)return l(r,o,c,u,c.dbPath);if($)return a(r,o,$,u,$.dbPath)}return null},k=(r=>produce(r,i=>traverse(i,o=>{let{value:u,meta:h}=o,c=u;if(isObject(c)){if(c.$id){let $=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},p=O(n,$);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=p.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),p?.idFields?.length===1){let[E]=p.idFields;c.$filter={...c.$filter,[E]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let $=O(n,c);if(!$?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=$.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c){let $=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[U]=h.nodePath;let p=O(n,$);if(c.$filter&&(c.$filterByUnique=Kt(c.$filter,p),c.$filterProcessed||(c.$filter=vt(c.$filter,p))),c.$fields){c.$fields.filter(f=>p?.idFields?.includes(f)||p?.idFields?.includes(f.$path)).length>0||(c.$fields=[...c.$fields,...Array.isArray(p.idFields)?p.idFields:[]],c.$idNotIncluded=!0);let C=c.$fields?.flatMap(f=>{let Q=m(f,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=C;}else {let C=Ht(p)?.flatMap(f=>{let Q=m(f,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=C;}c.$excludedFields&&(c.$fields=c.$fields.filter(E=>s(p,E)?!0:!c.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=k;};var wt=async(e,t)=>{let n=t.dbConnectors[0].id,s=e.typeDB?.get(n)?.session,d=e.typeDB?.get(n)?.client;if(!s||!s.isOpen()){if(!d)throw new Error("Client not found");s=await d.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:d,session:s});}return {client:d,session:s}};var Be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:s,tqlRequest:d,config:l}=e;if(!s)throw new Error("BQL request not parsed");if(!d)throw new Error("TQL request not built");let a=new TypeDBOptions;if(a.infer=!0,Array.isArray(d)){let M=await parallel(d.length,d,async k=>{let{session:r}=await wt(n,l),i=await r.transaction(TransactionType.READ,a);if(!i)throw new Error("Can't create transaction");let u=await i.query.fetch(k).collect();return await i.close(),u});t.rawTqlRes=M,t.isBatched=!0;}else {let{session:M}=await wt(n,l),k=await M.transaction(TransactionType.READ,a);if(!k)throw new Error("Can't create transaction");let i=await k.query.fetch(d).collect();await k.close(),t.rawTqlRes=i;}};var Ee=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,s=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,d=/filterByUnique:([a-zA-Z0-9_\-·]+)/,l=e.match(t),a=e.match(n),m=e.match(s),M=e.match(d);return {as:l?l[1]:null,justId:a?a[1]:null,idNotIncluded:m?m[1]:null,filterByUnique:M?M[1]:null}},On=e=>{try{let n=(d=>{let l=d.replace("$metadata:","");return l=l.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),l=l.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,m,M)=>/^{.*}$/.test(M)?`:${M}`:`:${m}"${M}"`),l=l.replace(/\[([^\]]+)\]/g,(a,m)=>`[${m.split(",").map(M=>M.trim().startsWith("{")&&M.trim().endsWith("}")?M.trim():`"${M.trim()}"`).join(",")}]`),l})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:s,schema:d,config:l}=e,{rawTqlRes:a,isBatched:m}=t;if(n){if(!a)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let M=(c,$)=>{let{$metaData:p}=c,{as:E}=On(p),C=Object.entries(c).filter(([f])=>f!=="type"&&!f.includes("$")).map(([f,Q])=>{let S=$.dataFields?.find(g=>g.path===f||g.dbPath===f),y=f==="id",w=Array.isArray(E)?E.find(g=>g[f])?.[f]:f,b;if(S?.cardinality==="ONE"){if(b=Q[0]?Q[0].value:l.query?.returnNulls?null:void 0,S.contentType==="DATE"&&(b=b&&`${b}Z`),y)return [[w,b],["$id",b]].filter(([g,P])=>P!==void 0)}else if(S?.cardinality==="MANY"){if(!isArray(Q))throw new Error("Typedb fetch has changed its format");if(Q.length===0)return l.query?.returnNulls?[[w,null]]:[];S.contentType==="DATE"?b=Q.map(g=>`${g.value}Z`):b=Q.map(g=>g.value);}return [[w,b]].filter(([g,P])=>P!==void 0)}).flat();return Object.fromEntries([...C])},k=c=>c.reduce(($,p)=>{let{$roleFields:E,$metaData:C,$cardinality:f}=p,{as:Q,justId:S,idNotIncluded:y,filterByUnique:w}=Ee(C),b=E.map(g=>{let{dataFields:P,currentSchema:T,linkFields:L,roleFields:B,schemaValue:I}=i(g),F=M(P,T);if(S==="T")return F.id;{let A=r(L),R=k(B),z={...F};return y==="true"&&T?.idFields?.forEach(N=>delete z[N]),{...z,...A,...R,...I}}});return b.length>0?$[Q]=f==="MANY"&&w==="false"?b:b[0]:l.query?.returnNulls&&($[Q]=null),$},{}),r=c=>c.reduce(($,p)=>{let{$linkFields:E,$metaData:C,$cardinality:f}=p,{as:Q,justId:S,idNotIncluded:y,filterByUnique:w}=Ee(C),b=E.map(g=>{let{dataFields:P,currentSchema:T,linkFields:L,roleFields:B,schemaValue:I}=i(g),F=M(P,T);if(S==="T")return F.id;{let A=r(L),R=k(B),z={...F};return y==="true"&&T.idFields?.forEach(N=>delete z[N]),{...z,...A,...R,...I}}});return $[Q]=b.length>0?f==="MANY"&&w==="false"?b:b[0]:l.query?.returnNulls?null:void 0,$},{}),i=c=>{let $=Object.keys(c),p=$.find(g=>g.endsWith(".$dataFields"));if(!p)throw new Error("No datafields");let E=c[p],C=p.split(".")[p.split(".").length-2];if(E.$metaData=C,E.length===0)throw new Error("No datafields");let f=E.type,Q={$thing:f.label,$thingType:f.root,[U]:c.queryPath.value},S={[`$${Q.$thingType}`]:Q.$thing},y=O(d,S),w=$.filter(g=>!g.endsWith(".$dataFields")&&y.linkFields?.some(P=>P.path===g.split(".").pop())).map(g=>({$linkFields:c[g],$key:g.split(".").pop(),$metaData:g.split(".")[g.split(".").length-2],$cardinality:y?.linkFields?.find(P=>P.path===g.split(".").pop())?.cardinality})),b=$.filter(g=>!g.endsWith(".$dataFields")&&y.roles?.[g.split(".").pop()]).map(g=>({$roleFields:c[g],$key:g.split(".").pop(),$metaData:g.split(".")[g.split(".").length-2],$cardinality:y.roles[g.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:Q,currentSchema:y,linkFields:w,roleFields:b}},o=c=>c.map($=>{let{dataFields:p,currentSchema:E,linkFields:C,roleFields:f,schemaValue:Q}=i($),S=M(p,E),y=r(C),w=k(f),b=s?.$fields?.every(P=>!E?.idFields?.includes(P)&&!E?.idFields?.includes(P.$path));return {...y,...w,...Q,...!l.query?.noMetadata&&s.$id?{$id:Array.isArray(s.$id)?S.id:s.$id}:{},...b?Object.fromEntries(Object.entries(S).filter(([P])=>!E?.idFields?.includes(P))):S}}),h=(c=>{let $=p=>{let E=o(p);return s.$id&&!Array.isArray(s.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return m?c.map($):$(c)})(a);t.bqlRes=h;};var qn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Dn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,we=e=>{let n=e.toString().replace(qn,"").trim().split("=>")[0].split("{")[0].replace(Dn,"").trim(),s=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return s?(s.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(l=>l.includes("{")&&l.includes("}")?(l.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(m=>m.split(":")[0].trim().replace(/['"[\]]/g,"")):l.trim()).filter(Boolean):[]};var ht=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!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(n){let{fn:d}=t.default,a=we(d).filter(m=>!(m 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 be=async(e,t)=>{let{schema:n,enrichedBqlQuery:s}=e,{bqlRes:d}=t;if(!d)return;let a=(m=>produce(m,M=>traverse(M,({value:k})=>{if(isObject(k)){let r=k;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let i=O(n,r),{virtualFields:o}=i,u=r[U];if(!u)throw new Error("[Internal] QueryPath is missing");let h=getNodeByPath(s,u),c=h.$fields.map(p=>p.$path),$=h.$excludedFields;o.forEach(p=>{if($?.includes(p)||c.length>0&&!c.includes(p))return;let E=i.dataFields?.find(C=>C.path===p);if(E?.default){let C=ht({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[p]=C;}else if(r[p]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${p}`)}),$&&$.forEach(p=>{if(typeof p!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[p];});}}})))(d);t.bqlRes=a;};var Le=async(e,t)=>{let{config:n}=e,{bqlRes:s}=t;if(!s)return;let l=(M=>produce(M,k=>traverse(k,({value:r})=>{isObject(r);})))(s),m=(M=>produce(M,k=>traverse(k,({value:r})=>{if(isObject(r)){let i=r;Object.keys(i).forEach(o=>{i[o]===void 0&&delete i[o];}),Object.getOwnPropertySymbols(i).forEach(o=>{delete i[o];}),n.query?.noMetadata===!0&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}})))(l);t.bqlRes=m;};var Wn={query:[ye,$e,Be,Fe,be,Le]},Qe=async(e,t,n={},s=!0)=>{for(let d of e){let l=await d(t,n);if(l&&Array.isArray(l))for(let a of l)await Qe(a.pipeline,a.req,a.res,!1);}return s&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Qt=(e,t,n,s)=>Qe(Wn.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:s},{});var ft=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.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 Ie=(e,t,n)=>{let s=isArray(e[t])?e[t]:[e[t]];if(!s.every(d=>typeof d=="object"))if(s.every(d=>typeof d=="string")){let d=ft(t,n),[l]=d,a=e.$op==="create"?"link":"replace",m=l.thing,M=l.thingType;if(s.some(k=>k.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:a,$thing:m,$thingType:M,$bzId:`S_${v4()}`};}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(s)} Parent: ${JSON.stringify(e,null,2)})`)};var ct=(e,t,n)=>{let s=O(n,t),{usedDataFields:d}=Z(s,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"&&d.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&d.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var It=(e,t,n)=>{let s=O(n,t),{usedFields:d}=Z(s,t);return t.$op?(ct(e,t,n),t.$op):t.$id||t.$filter?d.length>0?(ct(e,{...t,$op:"update"},n),"update"):(ct(e,{...t,$op:"link"},n),"link"):t.$tempId?d.length>0?(ct(e,{...t,$op:"create"},n),"create"):(ct(e,{...t,$op:"create"},n),"link"):(ct(e,{...t,$op:"create"},n),"create")};var Ce=(e,t)=>{let s=(isArray(e.$root)?e.$root:[e.$root]).map(d=>{let l=It(d,d,t);return {...{...d.$thing?{}:{$thing:d.$entity||d.$relation},...d.$thingType?{}:{$thingType:ue(d,t)},...d.$op?{}:{$op:l},...d.$bzId?{}:{$bzId:`R_${v4()}`}},...d}});e.$root=isArray(e.$root)?s:s[0];};var Pt=(e,t)=>{let n=t[Lt];return isSet(n)?n.has("clean")?(Reflect.set(t,Lt,n.add("clean")),!0):!1:(Reflect.set(t,Lt,new Set(["clean"])),!0)};var Se=(e,t,n)=>{if(Pt("split_ids",e)){let s=(isArray(e[t])?e[t]:[e[t]]).flatMap(d=>{if(isObject(d)&&"$id"in d&&isArray(d.$id)){let l=d;if(O(n,l),!l.$bzId)throw new Error("[Internal Error] No bzId found");return l.$id.map((a,m)=>({...J(l),$id:a,$bzId:`${l.$bzId}_${m}`,...v(l)}))}return d});(s.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=s);}};var Re=(e,t,n,s)=>{let d=(isArray(e[t])?e[t]:[e[t]]).map(l=>{let a=ft(t,n),[m]=a,M=It(e,{...l,$thing:m.thing,$thingType:m.thingType},s),k=l.$bzId?l.$bzId:l.$tempId?l.$tempId:`N_${v4()}`;if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);return {...l,[it]:n,$thing:m.thing,$thingType:m.thingType,$op:M,$bzId:k}});e[t]=isArray(e[t])?d:d[0];};var Oe=(e,t,n)=>{let s=e[t];s&&(isArray(s)?s:[s]).forEach(d=>{let l=O(n,d),{unidentifiedFields:a}=Z(l,d),{computedFields:m,virtualFields:M}=l,k=listify(d,(o,u)=>u!==void 0?o:void 0),r=k.filter(o=>M?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(m.filter(o=>!k.includes(o)).forEach(o=>{let u=l.dataFields?.find(E=>E.path===o),c=l.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],$="roles"in l?de(l.roles,(E,C)=>E===o):void 0,p=u||c||$;if(!p)throw new Error(`no field Def for ${o}`);if(d.$op==="create"&&!d[o]){let E=ht({currentThing:d,fieldSchema:p,mandatoryDependencies:!0});d[o]=E;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(d)}`)});};var Ct=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let s=`on${he(e.$op)}`;return n.pre.filter(a=>!a.triggers||a.triggers[s]?.()).flatMap(a=>a.actions)}return []};var xe=(e,t,n,s)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(l=>{if("$thing"in l){let{requiredFields:a,enumFields:m,fnValidatedFields:M,dataFields:k}=O(n,l);if("$op"in l&&l.$op==="create"&&a.forEach(r=>{if(!(r in l))throw new Error(`[Validations] Required field "${r}" is missing.`)}),("$op"in l&&l.$op==="update"||l.$op==="create")&&m.forEach(r=>{if(r in l){let i=k?.find(o=>o.path===r)?.validations?.enum;if(!i)throw new Error(`[Validations] Enum field "${r}" is missing enum options.`);if(isArray(l[r]))l[r].some(o=>{if(!i.includes(o))throw new Error(`[Validations] Option "${o}" is not a valid option for field "${r}".`)});else if(i&&!i.includes(l[r]))throw new Error(`[Validations] Option "${l[r]}" is not a valid option for field "${r}".`)}}),("$op"in l&&l.$op==="update"||l.$op==="create")&&M.forEach(r=>{if(r in l)try{let i=k?.find(o=>o.path===r)?.validations?.fn;if(!i)throw new Error("Missing validation function.");if(!i(l[r]))throw new Error("Failed validation function.")}catch(i){throw new Error(`[Validations:attribute:${r}] ${i.message}`)}}),isObject(l)&&"$thing"in l){let r=l.$thing,i=l,o=clone(J(e)),u=clone(J(i)),h=s.mutation?.context||{};Ct(i,n).forEach($=>{if($.type==="validate"){if($.severity!=="error")return;try{let p=$.fn(u,o,h);if(p===!1)throw new Error(`${$.message}.`);if(p!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(p){throw new Error(`[Validations:thing:${r}] ${p.message}`)}}});}}});};var ze=(e,t,n,s)=>{let d=(isArray(e[t])?e[t]:[e[t]]).map(l=>{if(kt(l)){let a=Ct(l,n).filter(r=>r.type==="transform"),m=clone(J(e)),M=clone(J(l)),k=s.mutation?.context||{};return a.forEach(r=>{let i=r.fn(M,m,k);Object.keys(i).length!==0&&(l={...M,...i,...v(l)});}),l}});e[t]=isArray(e[t])?d:d[0];};var We=(e,t,n)=>{let s=ft(t,n),[d]=s;e[t]={$thing:d.thing,$thingType:d.thingType,$op:"unlink",$bzId:`U_${v4()}`,[it]:n};};var ir=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Pt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},or=(e,t)=>{},Zt=(e,t,n)=>{let d=produce({$rootWrap:{$root:e}},l=>traverse(l,({value:a,parent:m,key:M,meta:k})=>{if(!(!m||!M)&&isObject(a)){if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a))throw M==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}let r=a;Object.keys(r).forEach(i=>{if(ir(r,i),i!=="$root"&&i.startsWith("$"))return;let o=i!=="$root"?Wt(t,r,i):{fieldType:"rootField"};if(!o)throw new Error(`[Internal] Field ${i} not found in schema`);if("contentType"in o)return or();if(["rootField","linkField","roleField"].includes(o.fieldType)){if(["linkField","roleField"].includes(o.fieldType)&&(r[i]===null?We(r,i,o):Ie(r,i,o)),o.fieldType==="rootField"){if(!("$root"in r))throw new Error(`[Internal] Field ${i} is a rootField but the object is not a root`);Ce(r,t);}let u=isArray(r[i])?r[i]:[r[i]],h=k.nodePath?.split(".").slice(1).join(".");u.forEach($=>{if($){if(o?.cardinality==="ONE"&&!$.$op&&!$.$id&&!$.$filter&&!$.$tempId&&r.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${h}.${i}`);if($.$tempId&&!($.$op===void 0||$.$op==="link"||$.$op==="create"||$.$op==="update"))throw new Error(`Invalid op ${$.$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(o.fieldType)&&Re(r,i,o,t),Se(r,i,t),["rootField","linkField","roleField"].includes(o.fieldType)&&Oe(r,i,t),(isArray(r[i])?r[i]:[r[i]]).forEach($=>{let p=O(t,$),{unidentifiedFields:E,usedLinkFields:C,usedFields:f,fields:Q}=Z(p,$);if(f.forEach(S=>{if(!Q.includes(S))throw new Error(`[Schema] Field ${S} not found in the schema`)}),E.length>0)throw new Error(`Unknown fields: [${E.join(",")}] in ${JSON.stringify(a)}`);if(C.length>1){let S=p.linkFields?.filter(y=>C.includes(y.path));S?.some((y,w)=>S.some((b,g)=>{if(w!==g&&y.target!==b.target&&y.relation===b.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),ze(r,i,t,n),xe(r,i,t,n);}});}}));return console.log("After enrich",d.$rootWrap.$root),isArray(d.$rootWrap.$root),d.$rootWrap.$root};var _e=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:s}=await wt(t,n),d=await s.transaction(TransactionType.WRITE);if(!d)throw new Error("Can't create transaction");let l=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;l&&await d.query.delete(l);let m=a&&d.query.insert(a);try{let M=m?await m.collect():void 0;return await d.commit(),await d.close(),{insertions:M}}catch(M){throw await d.close(),new Error(`Transaction failed: ${M.message}`)}};var Ve=async(e,t,n,s)=>{let d=[...t,...n],l=d.map(a=>{let m=e.insertions?.find(M=>M.get(`${a.$bzId}`))?.get(`${a.$bzId}`);if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!m&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let M=m?.asThing().iid;if(s.mutation?.noMetadata)return Object.entries(a).filter(([i,o])=>!i.startsWith("$")).reduce((i,[o,u])=>{if(a.$thingType==="relation"){let h=d.filter(c=>c.$id&&c.$bzId===u);if(h.length>1)throw new Error(`Multiple things with the same bzId ${u}`);return h.length===1?(i[o]=h[0].$id,i):(i[o]=u,i)}return i[o]=u,i},{});let k=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:M,...a,[a.path]:a.$id,...k}}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(l)};var He=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(l=>l.startsWith("$")).forEach(l=>delete n[l]),Object.keys(n).filter(l=>typeof l=="symbol").forEach(l=>delete n[l])),n);return produce(e,n=>traverse(n,t))};var Je=async(e,t)=>{let n=r=>{let i=[],o=[],u=p=>{if(p.$id)return p.$id;let E=O(t,p),{idFields:C}=E;if(!C)throw new Error(`no idFields: ${JSON.stringify(p)}`);let[f]=C;if(!f)throw new Error(`no idField: ${JSON.stringify(p)}`);let Q=E.dataFields?.find(w=>w.path===f),S=ht({currentThing:p,fieldSchema:Q,mandatoryDependencies:!0}),y=p[f]||p.$id||S;if(!y)throw new Error(`no idValue: ${JSON.stringify(p)}`);return y},h=p=>{if(p.$op==="create"){let E=u(p);if(i.find(C=>C.$id===E))throw new Error(`Duplicate id ${E} for node ${JSON.stringify(p)}`);if(o.find(C=>C.$bzId===p.$bzId))throw new Error(`Duplicate $bzid ${p.$bzId} for node ${JSON.stringify(p)}`);i.push({...p,$id:E});return}p.$tempId&&p.$op==="match"||i.push(p);},c=p=>{if(p.$op==="create"){let E=u(p);if(i.find(C=>C.$id===E),o.find(C=>C.$bzId===p.$bzId))throw new Error(`Duplicate %bzId ${p.$bzIdd} for edge ${JSON.stringify(p)}`);o.push({...p,$id:E});return}o.push(p);};return traverse(r,({value:p,parent:E,meta:C})=>{if(!isObject(p))return;let f=p;if(f.$thing){if(!f.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(f)}`);if(!f.$bzId)throw new Error("[internal error] BzId not found");let Q=O(t,f),{dataFields:S,roleFields:y,linkFields:w,usedFields:b}=Z(Q,f),g=()=>{if(f.$op==="create"||f.$op==="delete")return f.$op;if(f.$op==="update"){let L=b.filter(F=>S?.includes(F)),B=b.filter(F=>y?.includes(F)),I=b.filter(F=>w?.includes(F));if(L.length>0)return "update";if(B.length>0||I.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(f)}`)}return "match"},P={...f.$id&&{$id:f.$id},...f.$tempId&&{$tempId:f.$tempId},...f.$filter&&{$filter:f.$filter},$thing:f.$thing,...f.$thingType&&{$thingType:f.$thingType},...shake(pick(f,S||[""])),$op:g(),$bzId:f.$bzId};h(P);let T=f[it];if(T?.fieldType==="linkField"){if((f.$op==="link"||f.$op==="unlink")&&(f.$id||f.$filter)){if(f.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");i.push({...f,$op:"match"});}let L=T.relation===f.$thing,B=L?f.$bzId:`LT_${v4()}`,F=fe(r,E,C).$bzId;if(!F)throw new Error("No parent id found");let A=()=>{if(f.$op==="delete")return L?"match":"delete";if(f.$op==="unlink")return L?"unlink":"delete";if(f.$op==="link"||f.$op==="create")return L?"link":"create";if(f.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R=O(t,{$thing:T.relation,$thingType:"relation"});if(!Object.keys(R.roles).includes(T.plays))throw new Error(`[Wrong format] Field ${T.plays} is not a role of relation ${T.relation}`);let N={$bzId:B,$thing:T.relation,$thingType:"relation",...f.$tempId?{$tempId:f.$tempId}:{},$op:A(),...L?{}:{[T.path]:f.$bzId},[T.plays]:F,[it]:T,[lt]:"linkField"};c(N),(f.$op==="unlink"||A()==="unlink")&&L&&c({$thing:T.relation,$thingType:"relation",$bzId:B,$op:"match",[T.plays]:F,[it]:T,[lt]:"linkField"});}if(f.$thingType==="relation"){let L=Ft(f,(F,A)=>y.includes(F)),B=mapEntries(L,(F,A)=>isArray(A)?[F,A]:isObject(A)?[F,A.$bzId]:[F,A]),I=Ft(p,(F,A)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(L).filter(F=>!F.startsWith("$")).length>0){if(f.$op==="create"||f.$op==="delete"){let F=()=>{if(f.$op==="create")return "link";if(f.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},A=O(t,f).roles,R=mapEntries(B,(N,D)=>{let _=A[N]?.cardinality;if(!_)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(_==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(tt=>tt.$bzId||tt)]}return [N,D.$bzId||D]}),z={...I,$thing:f.$thing,$thingType:"relation",$op:F(),...R,$bzId:f.$bzId,[lt]:"roleField"};c(z);return}if(f.$op==="match"||f.$op==="update"&&Object.keys(L).length>0){let F=0;Object.entries(L).forEach(([A,R])=>{let z=isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;z.forEach(D=>{if(!D)return;let _=N(D.$op);if(_==="replace")throw new Error("Not supported yet: replace on roleFields");if(_==="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 tt={...I,$thing:f.$thing,$thingType:"relation",$op:_==="delete"?"unlink":_,[A]:D.$bzId,$bzId:f.$bzId,[lt]:"roleField"};c(tt);});});}}}}}),[i,o]},[s,d]=n(e),l=s.reduce((r,i)=>{if(!i.$bzId)return [...r,i];let o=r.findIndex(u=>u.$bzId===i.$bzId);if(o===-1)return [...r,i];if(r[o].$op==="create"&&i.$op==="match")return r;if(r[o].$op==="match"&&(i.$op==="create"||i.$op==="match"))return [...r.slice(0,o),i,...r.slice(o+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${i.$tempId}". Existing: ${r[o].$op}. Current: ${i.$op}`)},[]),a=d.reduce((r,i)=>{let o=r.find(u=>(u.$id&&u.$id===i.$id||u.$bzId&&u.$bzId===i.$bzId)&&u.$thing===i.$thing&&u.$op===i.$op);if(o){let u={...o};return Object.keys(i).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let $=o[c],p=i[c];Array.isArray($)&&Array.isArray(p)?u[c]=Array.from(new Set([...$,...p])):!Array.isArray($)&&Array.isArray(p)?$!==void 0?u[c]=Array.from(new Set([$,...p])):u[c]=p:Array.isArray($)&&!Array.isArray(p)?p!==void 0&&(u[c]=Array.from(new Set([...$,p]))):$!==null&&p!==null&&$!==void 0&&p!==void 0?u[c]=Array.from(new Set([$,p])):$==null&&(u[c]=p);}),[...r.filter(c=>!((c.$id&&c.$id===i.$id||c.$bzId&&c.$bzId===i.$bzId)&&c.$thing===i.$thing&&c.$op===i.$op)),u]}return [...r,i]},[]);l.forEach(r=>{if((r.$thingType==="relation"||"relation"in r)&&a.filter(i=>i.$bzId===r.$bzId||i.$tempId&&i.$tempId===r.$tempId).length===0){if(r.$op==="delete"||r.$op==="match"||r.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(He(r))}`)}});let m=[...l,...a],M=new Set(m.filter(r=>r.$tempId).map(r=>r.$tempId)),k=Array.from(M).filter(r=>!m.some(i=>i.$tempId===r&&i.$op==="create"));if(k.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${k.join(", ")}`);return {mergedThings:l,mergedEdges:a}};var Ze=async(e,t,n)=>{let s=o=>{let u=o.$op,h=`$${o.$bzId}`,c=O(n,o),{idFields:$,defaultDBConnector:p}=c,E=p?.path||o.$thing,C=o.$id,f=$?.[0],Q=listify(o,(L,B)=>{if(L.startsWith("$")||L===f||B===void 0||B===null)return "";let I=c.dataFields?.find(R=>R.path===L);if(!I?.path)return "";let A=I.dbPath;if(["TEXT","ID","EMAIL"].includes(I.contentType))return `has ${A} '${B}'`;if(["NUMBER","BOOLEAN"].includes(I.contentType))return `has ${A} ${B}`;if(I.contentType==="DATE"){if(Number.isNaN(B.valueOf()))throw new Error("Invalid format, Nan Date");return B instanceof Date?`has ${A} ${B.toISOString().replace("Z","")}`:`has ${A} ${new Date(B).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${I.contentType}`)}).filter(L=>L),S=`${h}-atts`,y=listify(o,L=>{if(L.startsWith("$")||L===f)return "";let B=c.dataFields?.find(A=>A.path===L);if(!B?.path)return "";let F=B.dbPath;return `{${S} isa ${F};}`}).filter(L=>L),w=isArray(C)?`like '${C.join("|")}'`:`'${C}'`,b=C?[`has ${f} ${w}`]:[],g=[...b,...Q].filter(L=>L).join(","),P=()=>{if(u==="delete"||u==="unlink"||u==="match")return `${h} isa ${[E,...b].filter(L=>L).join(",")};`;if(u==="update"){if(!y.length)throw new Error("update without attributes");return `${h} isa ${[E,...b].filter(L=>L).join(",")}, has ${S};
|
|
59
|
+
${y.join(" or ")};`}return ""},T=()=>u==="update"||u==="link"||u==="match"?`${h} isa ${[E,...b].filter(L=>L).join(",")};`:"";if(kt(o))return {op:u,deletionMatch:P(),insertionMatch:T(),insertion:u==="create"?`${h} isa ${[E,g].filter(L=>L).join(",")};`:u==="update"&&Q.length?`${h} ${Q.join(",")};`:"",deletion:u==="delete"?`${h} isa ${E};`:u==="update"&&y.length?`${h} has ${S};`:""};throw new Error("in attributes")},d=o=>{let u=o.$op,h=O(n,o),c=`$${o.$bzId}`,$=o.$id,p=h.defaultDBConnector?.path||o.$thing,E="roles"in h?listify(h.roles,B=>B):[],C="roles"in h?mapEntries(h.roles,(B,I)=>[B,I.dbConnector?.path||B]):{},f=listify(o,(B,I)=>{if(!E.includes(B))return null;if(!("roles"in h))throw new Error("This should have roles! ");let F=C[B];return Array.isArray(I)?I.map(A=>({path:F,id:A})):{path:F,id:I}}).filter(B=>B).flat(),Q=f.map(B=>{if(!B?.path)throw new Error("Object without path");return `${B.path}: $${B.id}`}),S=f.length>0?`( ${Q.join(" , ")} )`:"",y=o[lt];if(!y)throw new Error("[internal error] Symbol edgeType not defined");let w=S?`${c} ${S} ${y==="linkField"||u==="delete"||u==="unlink"?`isa ${p}`:""}`:"",b=`${c} ${y==="linkField"||u==="delete"?`isa ${p}`:""}`,g=()=>w?u==="link"?`${w};`:u==="create"?`${w}, has id '${$}';`:"":"",P=()=>w&&u==="match"?`${w};`:"",T=()=>w?u==="delete"?`${w};`:u==="match"?`${w};`:"":"",L=()=>w?u==="delete"?`${b};`:u==="unlink"?`${c} ${S};`:"":"";return {deletionMatch:T(),insertionMatch:P(),deletion:L(),insertion:g(),op:""}},l=(o,u)=>{let h=u==="edges"?d:s;if(Array.isArray(o))return o.map(f=>{let{preDeletionBatch:Q,insertionMatch:S,deletionMatch:y,insertion:w,deletion:b}=h(f);return shake({preDeletionBatch:Q,insertionMatch:S,deletionMatch:y,insertion:w,deletion:b},g=>!g)}).filter(f=>f);let{preDeletionBatch:c,insertionMatch:$,deletionMatch:p,insertion:E,deletion:C}=h(o);return shake({preDeletionBatch:c,insertionMatch:$,deletionMatch:p,insertion:E,deletion:C},f=>!f)},a=l(e),m=Array.isArray(a)?a:[a],M=l(t,"edges"),k=Array.isArray(M)?M:[M],r=[...m,...k];return shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var mr=Symbol.for("grandChildOfCreate"),Ye=async(e,t,n,s)=>{let d=(y,w)=>Object.keys(y).filter(b=>b.startsWith("$")?!1:w?!O(t,y).dataFields?.find(P=>P.path===b):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let l=[];if(traverse(e,({parent:y,key:w,value:b})=>{y&&w&&!w.includes("$")&&isObject(y)?(Array.isArray(y[w])?y[w]:[y[w]]).forEach(P=>{if(isObject(P)){if(y.$op!=="create")l.includes(P.$op)||l.push(P.$op);else if(P.$op==="delete"||P.$op==="unlink")throw new Error(`Cannot ${P.$op} under a create`)}}):!y&&isObject(b)&&(l.includes(b.$op)||l.push(b.$op));}),!l.includes("delete")&&!l.includes("unlink")&&!l.includes("replace")&&!l.includes("update")&&!l.includes("link"))return;let m=(y=>{let w=(b,g)=>{let P=[],T={},L=["$op","$bzId","$parentKey"],B=["$relation","$entity","$id",...L];for(let I in b)if(!L.includes(I)&&!(B.includes(I)&&!g))if(!I.includes("$")&&(isObject(b[I])||Array.isArray(b[I]))){let F=b[I];Array.isArray(F)&&F.length>0?F.forEach(A=>{P.push({$path:I,...w(A)});}):P.push({$path:I,...w(F)});}else T[I]=b[I];return {...T,$fields:P}};return y.map(b=>w(b,!0))})(Array.isArray(e)?e:[e]),M=await Qt(m,n,t,s),k=(y,w)=>{let b=y.$id||y.id||y.$bzId;if(y.$objectPath){let{$objectPath:g}=y,P=g?.beforePath||"root",T=Array.isArray(g.ids)?`[${g.ids}]`:g.ids;return {beforePath:`${P}.${T}___${g.key}`,ids:b,key:w}}else return {beforePath:"root",ids:b,key:w}},r=(y,w)=>{let b=y?.beforePath||"root",g=w||(Array.isArray(y?.ids)?`[${y?.ids}]`:y?.ids);return `${b}.${g}___${y?.key}`},i=y=>{if(y.includes("[")&&y.includes("]")){let[w,b,g]=y.split(/[[\]]/);return b.split(",").map(T=>`${w}${T}${g}`)}else return [y]},o={};(y=>produce(y,w=>traverse(w,b=>{let{key:g,parent:P}=b;if(P&&g&&P.$id&&!g.includes("$")){let T=k(P,g),L=r(T);if(Array.isArray(P[g])){let B=[];P[g].forEach(I=>{isObject(I)?(I.$objectPath=T,B.push(I.$id.toString())):I&&B.push(I.toString());}),o[L]={$objectPath:T,$ids:B};}else {let B=P[g];isObject(B)?(o[L]={$objectPath:T,$ids:[B.$id.toString()]},B.$objectPath=T):B&&(o[L]={$objectPath:T,$ids:[B.toString()]});}}})))(M||{});let h=y=>produce(y,w=>traverse(w,b=>{let{key:g,value:P,parent:T}=b;T&&g&&!g.includes("$")&&(Array.isArray(P)||isObject(P))&&!Array.isArray(T)&&(Array.isArray(T[g])?T[g].forEach(L=>{typeof L!="string"&&(L.$objectPath=k(T,g),L.$parentIsCreate=T.$op==="create",L[mr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[g])&&(T[g].$parentIsCreate=T.$op==="create",T[g][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[g].$objectPath=k(T,g)));})),c=h(e),p=(y=>{let w=(T,L)=>{let B=[];T.filter(R=>R).forEach(R=>{let z=Object.keys(R).filter(N=>!N.startsWith("$")).length;if(Array.isArray(R.$id)&&z>0){let N=R.$id.map(D=>({...R,$id:D}));B=[...B,...N];}else B.push({...R});});let I=[],F=[],A=B.filter(R=>{let N=["delete","update","unlink"].includes(R.$op||""),D=d(R,!0).length;if((!R.$id||Array.isArray(R.$id)&&D>0||R.$filter)&&N)return !0;F.push({...R});});return A.length>0?A.forEach(R=>{let N=(j=>{let yt=(()=>{let V={};for(let x in j){let rt=O(t,j);!x.startsWith("$")&&rt.dataFields?.find(ut=>ut.path===x)&&(V[x]=j[x]);}return V})(),gt=Object.keys(j),nt=gt.filter(V=>!V.startsWith("$")),Ot=[],Tt=(V,x)=>{if(V===nt.length){let ut={...x};gt.forEach(H=>{H.startsWith("$")&&(ut[H]=j[H]);}),Ot.push(ut);return}let rt={...x,[nt[V]]:j[nt[V]],...v(x),...yt};Tt(V+1,rt),Tt(V+1,x);};return Tt(0,{...v(j)}),Ot})(R).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(st=>!st.startsWith("$")).length===0)),D=[],_=r(R.$objectPath),et=o[_]?o[_].$ids:[],q=N.map((j,st)=>{let yt=O(t,j),nt=Object.keys(j).filter(x=>!x.includes("$")&&!yt.dataFields?.some(rt=>rt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(H=>!H.$id||Array.isArray(H.$id)||H.$filter):j[x]:[j[x]]).map(H=>{let qt=r(H.$objectPath);return {idsToKey:(Dt=>{let ie=[],Et=Dt.split("."),Bn=Et.slice(0,Et.length-1).join("."),En=Et.slice(Et.length-1,Et.length)[0].split("___")[1];for(let xt in o)if(xt.startsWith(Bn)&&xt.endsWith(En)){let jt=xt.split("."),Fn=jt.slice(jt.length-1,jt.length)[0].split("___")[0];ie.push(Fn);}return ie})(qt),key:x,multiple:H}})).filter(x=>x!==void 0),V=(x=>{let rt=x.map(H=>H.map(at=>at.idsToKey));return (H=>H.length>0?H.reduce((at,Bt)=>at.concat(Bt),[]).reduce((at,Bt)=>at?Bt.filter(Dt=>at.includes(Dt)):Bt):[])(rt)})(nt).filter(x=>!D.includes(x));if(D=[...D,...V],et=et.filter(x=>!V.includes(x)),st===N.length-1&&et.length>0)return {...j,$id:et,$bzId:`T1_${v4()}`,...v(j)};if(V.length>0)return {...j,$id:V,$bzId:`T2_${v4()}`,...v(j)}}).filter(j=>j!==void 0),gn=(()=>{if(q.length===0&&!L?.$id)return A;if(q.length===0&&L?.$id){let j=Array.isArray(L.$id)?L.$id:[L.$id],st=[];return j.forEach(yt=>{let gt=r({...R.$objectPath,ids:yt}),nt=o[gt];nt&&st.push({...R,$id:nt.$ids,...v(R),$bzId:`T_${v4()}`});}),st}else return q.filter(j=>j!==void 0)})();I=[...F,...gn].map(b);}):I=B.map(b),I},b=T=>{let L={...T,$bzId:T.$tempId??`T3_${v4()}`,...v(T)},B=O(t,T);return Object.keys(T).filter(I=>!I.includes("$")&&!B.dataFields?.some(F=>F.path===I)).forEach(I=>{let F=Array.isArray(T[I])?T[I]:[T[I]],A=w(F,T);L[I]=A.length>0?A:void 0;}),L},g=[];return y.forEach(T=>{g=[...g,...w([T])];}),g.map(T=>b(T))})(Array.isArray(c)?c:[c]),E=y=>y.map(w=>{let b=d(w,!0),g={...w};return b.forEach(P=>{let T=Array.isArray(w[P])?w[P]:[w[P]],L=[],B=[],I=[],F={},A=_t(t,w,P);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(F=q,Array.isArray(q.$id)?B=[...B,...q.$id]:B.push(q.$id)):q.$op==="create"&&A==="ONE"&&q.id?(F=q,Array.isArray(q.id)?I=[...B,...q.id]:I.push(q.id)):L.push(q);});let R=r(F.$objectPath),N=i(R).map(q=>o[q]),D=[];N.filter(q=>q!=null).forEach(q=>{D=[...D,...q.$ids];});let _=D.filter(q=>!B.includes(q)),tt=B.filter(q=>!D.includes(q)),et=v(F);_.length>0&&L.push({...F,$op:"unlink",$id:_,$bzId:`T4_${v4()}`,id:void 0,...et}),tt.length>0&&tt.forEach(q=>{L.push({...F,$op:"link",$id:q,$bzId:`T5_${v4()}`,...et});}),I.length>0&&I.forEach(q=>{L.push({...F,$op:"create",id:q,$bzId:`T6_${v4()}`,...et});}),g[P]=E(L);}),g}),C=h(E(h(p)));return (y=>produce(y,w=>traverse(w,b=>{let{key:g,value:P,parent:T}=b;g&&T&&!g?.includes("$")&&(Array.isArray(P)||isObject(P))&&!Array.isArray(T)&&(Array.isArray(P)?P:[P]).forEach(B=>{let I=o[r(B.$objectPath)],F=(z,N)=>z.every(D=>N.includes(D)),A=B.$id?Array.isArray(B.$id)?F(B.$id,I?I.$ids:[]):I?.$ids.includes(B.$id):I,R=_t(t,T,B.$objectPath.key);if(B.$op==="link"&&A&&R==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(B.$objectPath)}" because it is already occupied.`);if(B.$op)switch(B.$op){case"delete":if(!A&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${B.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!A&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${B.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!A&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${B.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(A)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${B.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))(C),(y=>produce(y,w=>traverse(w,b=>{let{value:g,meta:P}=b;isObject(g)&&(g[Symbol.for("path")]=P.nodePath,delete g.$objectPath,delete g.$parentIsCreate);})))(C)};function W(e){return {enumerable:!0,value:e}}function Ge(e){return {enumerable:!0,writable:!0,value:e}}var $t={},yr=()=>!0,Xe=()=>({}),en=e=>e,gr=(e,t,n,s)=>e.apply(n,s)&&t.apply(n,s),Br=(e,t,n,[s,d])=>t.call(n,e.call(n,s,d),d),ot=(e,t)=>Object.freeze(Object.create(e,t));function tn(e,t,n){return e.reduce((s,d)=>function(...l){return n(s,d,this,l)},t)}function nn(e){return ot(this,{fn:W(e)})}var rn={},G=nn.bind(rn);var on={},sn=nn.bind(on);function Rt(e,t){return t.filter(n=>e.isPrototypeOf(n))}function an(e,t,...n){let s=tn(Rt(on,n).map(l=>l.fn),yr,gr),d=tn(Rt(rn,n).map(l=>l.fn),en,Br);return ot(this,{from:W(e),to:W(t),guards:W(s),reducers:W(d)})}var ln={},cn={},X=an.bind(ln);an.bind(cn,null);function Er(e,t,n){return Xt(t,e,n,this.immediates)||e}function dn(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Fr={enter:en};function pn(...e){let t=Rt(ln,e),n=Rt(cn,e),s={final:W(e.length===0),transitions:W(dn(t))};return n.length&&(s.immediates=W(n),s.enter=W(Er)),ot(Fr,s)}var wr={enter(e,t,n){let s=this.fn.call(t,t.context,n);return Gt.isPrototypeOf(s)?ot(un,{machine:W(s),transitions:W(this.transitions)}).enter(e,t,n):(s.then(d=>t.send({type:"done",data:d})).catch(d=>t.send({type:"error",error:d})),e)}},un={enter(e,t,n){if(t.child=te(this.machine,s=>{t.onChange(s),t.child==s&&s.machine.state.value.final&&(delete t.child,t.send({type:"done",data:s.context}));},t.context,n),t.child.machine.state.value.final){let s=t.child.context;return delete t.child,Xt(t,e,{type:"done",data:s},this.transitions.get("done"))}return e}};function pt(e,...t){let n=W(dn(t));return Gt.isPrototypeOf(e)?ot(un,{machine:W(e),transitions:n}):ot(wr,{fn:W(e),transitions:n})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function hn(e,t,n=Xe){return typeof e!="string"&&(n=t||Xe,t=e,e=Object.keys(t)[0]),$t._create&&$t._create(e,t),ot(Gt,{context:W(n),current:W(e),states:W(t)})}function Xt(e,t,n,s){let{context:d}=e;for(let{to:l,guards:a,reducers:m}of s)if(a(d,n)){e.context=m.call(e,d,n);let M=t.original||t,k=ot(M,{current:W(l),original:{value:M}});$t._onEnter&&$t._onEnter(t,l,e.context,d,n);let r=k.state.value;return e.machine=k,e.onChange(e),r.enter(k,e,n)}}function br(e,t){let n=t.type||t,{machine:s}=e,{value:d,name:l}=s.state;return d.transitions.has(n)?Xt(e,s,t,d.transitions.get(n))||s:($t._send&&$t._send(n,l),s)}var Tr={send(e){br(this,e);}};function te(e,t,n,s){let d=Object.create(Tr,{machine:Ge(e),context:Ge(e.context(n,s)),onChange:W(t)});return d.send=d.send.bind(d),d.machine=d.machine.state.value.enter(d.machine,d,s),d}var fn=pn,ee=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Mr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),kr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Lr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Qr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Ir=async e=>Object.keys(e.bql.current).length?Zt(e.bql.current,e.schema,e.config):Zt(e.bql.raw,e.schema,e.config),Pr=async e=>Ye(e.bql.current,e.schema,e.config,e.handles),Cr=async e=>Je(e.bql.current,e.schema),Sr=async e=>Ze(e.bql.things,e.bql.edges,e.schema),Ar=async e=>_e(e.typeDB.tqlMutation,e.handles,e.config),Rr=async e=>Ve(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),Or=()=>!0,mt=X("error","error",G((e,t)=>({...e,error:t.error}))),qr=hn("enrich",{enrich:pt(Ir,X("done","preQuery",sn(Or),G(ee)),X("done","parseBQL",G(ee)),mt),preQuery:pt(Pr,X("done","parseBQL",G(ee)),mt),parseBQL:pt(Cr,X("done","buildMutation",G(kr)),mt),buildMutation:pt(Sr,X("done","runMutation",G(Lr)),mt),runMutation:pt(Ar,X("done","parseMutation",G(Qr)),mt),parseMutation:pt(Rr,X("done","success",G(Mr)),mt),success:fn(),error:fn()},e=>e),Dr=async e=>new Promise((t,n)=>{te(qr,s=>{s.machine.state.name==="success"&&t(s.context),s.machine.state.name==="error"&&n(s.context);},e);}),$n=async(e,t,n,s)=>Dr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:s,depthLevel:0,error:null});enableMapSet();var re=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async s=>{if(s.provider==="typeDB"&&s.dbName){let[d,l]=await tryit(TypeDB.coreDriver)(s.url);if(d){let a=`[BORM:${s.provider}:${s.dbName}:core] ${d.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await l.session(s.dbName,SessionType.DATA);t.typeDB.set(s.id,{client:l,session:a});}catch(a){let m=`[BORM:${s.provider}:${s.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(m)}}if(s.provider==="typeDBCluster"&&s.dbName){let[d,l]=await tryit(TypeDB.cloudDriver)(s.addresses,s.credentials);if(d){let a=`[BORM:${s.provider}:${s.dbName}:core] ${d.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await l.session(s.dbName,SessionType.DATA);t.typeDB.set(s.id,{client:l,session:a});}catch(a){let m=`[BORM:${s.provider}:${s.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(m)}}}));let n=pe(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),se(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let s={...this.config,query:{...Nt.query,...this.config.query,...n}};return Qt(t,s,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let s={...this.config,mutation:{...Nt.mutation,...this.config.mutation,...n}},[d,l]=await tryit($n)(t,this.schema,s,this.dbHandles);if(d){let m=new Error(d.error.message);throw m.stack=d.error.stack,m}return l.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Ks=re;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
62
60
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
63
61
|
//! Todo: Sandbox the function in computeFunction()
|
|
64
62
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
65
63
|
//!old
|
|
66
64
|
|
|
67
|
-
export {
|
|
65
|
+
export { Ks as default };
|