@blitznocode/blitz-orm 0.8.4 → 0.8.7
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 +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +50 -49
- package/dist/index.mjs +52 -51
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -393,12 +393,12 @@ type PreHook = {
|
|
|
393
393
|
};
|
|
394
394
|
type Action = {
|
|
395
395
|
type: 'validate';
|
|
396
|
-
fn: (
|
|
396
|
+
fn: (currentNode: FilledBQLMutationBlock, parentNode: FilledBQLMutationBlock) => boolean;
|
|
397
397
|
severity: 'error' | 'warning' | 'info';
|
|
398
398
|
message: string;
|
|
399
399
|
} | {
|
|
400
400
|
type: 'transform';
|
|
401
|
-
fn: (
|
|
401
|
+
fn: (currentNode: FilledBQLMutationBlock, parentNode?: FilledBQLMutationBlock) => Partial<FilledBQLMutationBlock>;
|
|
402
402
|
};
|
|
403
403
|
|
|
404
404
|
type ContentTypeToType<C extends keyof ContentTypeMapping> = ContentTypeMapping[C];
|
|
@@ -459,6 +459,7 @@ declare class BormClient {
|
|
|
459
459
|
private config;
|
|
460
460
|
private dbHandles?;
|
|
461
461
|
constructor({ schema, config }: BormProps);
|
|
462
|
+
getDbHandles: () => DBHandles | undefined;
|
|
462
463
|
init: () => Promise<void>;
|
|
463
464
|
introspect: () => Promise<BormSchema>;
|
|
464
465
|
define: () => Promise<void>;
|
package/dist/index.d.ts
CHANGED
|
@@ -393,12 +393,12 @@ type PreHook = {
|
|
|
393
393
|
};
|
|
394
394
|
type Action = {
|
|
395
395
|
type: 'validate';
|
|
396
|
-
fn: (
|
|
396
|
+
fn: (currentNode: FilledBQLMutationBlock, parentNode: FilledBQLMutationBlock) => boolean;
|
|
397
397
|
severity: 'error' | 'warning' | 'info';
|
|
398
398
|
message: string;
|
|
399
399
|
} | {
|
|
400
400
|
type: 'transform';
|
|
401
|
-
fn: (
|
|
401
|
+
fn: (currentNode: FilledBQLMutationBlock, parentNode?: FilledBQLMutationBlock) => Partial<FilledBQLMutationBlock>;
|
|
402
402
|
};
|
|
403
403
|
|
|
404
404
|
type ContentTypeToType<C extends keyof ContentTypeMapping> = ContentTypeMapping[C];
|
|
@@ -459,6 +459,7 @@ declare class BormClient {
|
|
|
459
459
|
private config;
|
|
460
460
|
private dbHandles?;
|
|
461
461
|
constructor({ schema, config }: BormProps);
|
|
462
|
+
getDbHandles: () => DBHandles | undefined;
|
|
462
463
|
init: () => Promise<void>;
|
|
463
464
|
introspect: () => Promise<BormSchema>;
|
|
464
465
|
define: () => Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -6,59 +6,60 @@ var immer = require('immer');
|
|
|
6
6
|
var objectTraversal = require('object-traversal');
|
|
7
7
|
var uuid = require('uuid');
|
|
8
8
|
|
|
9
|
-
var
|
|
10
|
-
`,Object.keys(
|
|
11
|
-
`;let
|
|
12
|
-
`,
|
|
13
|
-
`),
|
|
14
|
-
`,
|
|
9
|
+
var ke={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Nt=d=>{let r=[],l=new Map;return d.forEach(a=>{let{dbPath:F,contentType:f}=a,y=`${F}-${f}`;l.has(y)||(l.set(y,!0),r.push(a));}),r},De=async(d,r,l)=>{let F=(()=>{let c="",t=[];c+=`
|
|
10
|
+
`,Object.keys(r.entities).forEach(w=>{let k=r.entities[w],{idFields:q,dataFields:b,linkFields:T,name:L}=k,h=[],S=[],$=[];if(k.extends){let g=r.entities[k.extends];g.dataFields&&g.dataFields.forEach(m=>{h.push(m.dbPath);}),g.linkFields&&g.linkFields.forEach(m=>{S.push(m.path);}),g.idFields&&g.idFields.forEach(m=>{$.push(m);});}c+=`${L} sub ${k.extends?k.extends:"entity"},
|
|
11
|
+
`;let E=[];if(q&&q.length>0){let g=new Set(q),Q=Array.from(g).map(I=>`${I}`).join(", ");$.includes(Q)||(c+=` owns ${Q} @key,
|
|
12
|
+
`,E.push(Q));}if(b&&b.length>0&&b.forEach(g=>{!h.includes(g.dbPath)&&!E.includes(g.dbPath)&&(c+=` owns ${g.dbPath},
|
|
13
|
+
`),t.push({dbPath:g.dbPath,contentType:g.contentType});}),T&&T.length>0){let g=[];T.forEach(m=>{let{relation:Q,plays:I}=m;!S.includes(m.path)&&!g.includes(`${Q}:${I}`)&&(c+=` plays ${Q}:${I},
|
|
14
|
+
`,g.push(`${Q}:${I}`));});}c=c.replace(/,\s*$/,`;
|
|
15
15
|
`),c+=`
|
|
16
|
-
`;}),Object.keys(
|
|
17
|
-
`;let
|
|
18
|
-
`,
|
|
19
|
-
`),
|
|
20
|
-
`);}),
|
|
21
|
-
`,
|
|
16
|
+
`;}),Object.keys(r.relations).forEach(w=>{let k=r.relations[w],{idFields:q,dataFields:b,roles:T,name:L,linkFields:h}=k,S=[],$=[],E=[],g=[];if(k.extends){let Q=r.relations[k.extends];Q.dataFields&&Q.dataFields.forEach(I=>{S.push(I.dbPath);}),Q.linkFields&&Q.linkFields.forEach(I=>{$.push(I.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(O=>{E.push(O.name);}),Q.idFields&&Q.idFields.forEach(I=>{g.push(I);});}c+=`${L} sub ${k.extends?k.extends:"relation"},
|
|
17
|
+
`;let m=[];if(q&&q.length>0){let Q=new Set(q),O=Array.from(Q).map(j=>`${j}`).join(", ");g.includes(O)||(c+=` owns ${O} @key,
|
|
18
|
+
`,m.push(O));}if(b&&b.length>0&&b.forEach(Q=>{!S.includes(Q.dbPath)&&!m.includes(Q.dbPath)&&(c+=` owns ${Q.dbPath},
|
|
19
|
+
`),t.push({dbPath:Q.dbPath,contentType:Q.contentType});}),T&&Object.keys(T).forEach(Q=>{E.includes(Q)||(c+=` relates ${Q},
|
|
20
|
+
`);}),h&&h.length>0){let Q=[];h.forEach(I=>{let{plays:O}=I;!$.includes(I.path)&&!Q.includes(`${k}:${O}`)&&(c+=` plays ${I.relation}:${O},
|
|
21
|
+
`,Q.push(`${k}:${O}`));});}c=c.replace(/,\s*$/,`;
|
|
22
22
|
`),c+=`
|
|
23
|
-
`;});let
|
|
23
|
+
`;});let o=`define
|
|
24
24
|
|
|
25
|
-
`;return
|
|
26
|
-
`,
|
|
27
|
-
`:
|
|
28
|
-
`,
|
|
29
|
-
`):
|
|
30
|
-
`:
|
|
31
|
-
`:
|
|
32
|
-
`);}),`${
|
|
25
|
+
`;return Nt(t).forEach(w=>{o+=`${w.dbPath} sub attribute,
|
|
26
|
+
`,w.contentType==="TEXT"||w.contentType==="ID"?o+=` value string;
|
|
27
|
+
`:w.contentType==="EMAIL"?(o+=` value string,
|
|
28
|
+
`,o+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
29
|
+
`):w.contentType==="DATE"?o+=` value datetime;
|
|
30
|
+
`:w.contentType==="BOOLEAN"?o+=` value boolean;
|
|
31
|
+
`:w.contentType==="NUMBER"&&(o+=` value long;
|
|
32
|
+
`);}),`${o}
|
|
33
33
|
|
|
34
|
-
${c}`})(),p=l.dbConnectors[0].id,y=d.typeDB.get(p)?.session,b=d.typeDB.get(p)?.client;if(!y){console.log("Session Status: ","NO SESSION");return}await y.close();let[{dbName:E}]=l.dbConnectors;await(await b.databases.get(E)).delete(),await b.databases.create(E);let e=await b.session(l.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),s=await e.transaction(typedbDriver.TransactionType.WRITE);await s.query.define(w),await s.commit(),await s.close();let h=await e.transaction(typedbDriver.TransactionType.READ);(await(await h.query.match("match $a sub thing;")).collect()).forEach(async c=>{c.get("a");}),await h.close();};var _t=(l,o,d)=>d?o:`${l}\xB7${o}`;var ft=(l,o)=>Object.values(Object.fromEntries(Object.entries(l).filter(([d,a])=>o(d,a))))[0],it=(l,o)=>Object.fromEntries(Object.entries(l).filter(([d,a])=>o(d,a))),Wt=l=>{let o=[],d=immer.produce(l,w=>objectTraversal.traverse(w,({key:p,value:y,meta:b})=>{if(b.depth===2&&(p&&(y.dataFields=y.dataFields?.map(E=>({...E,cardinality:E.cardinality||"ONE",dbPath:_t(p,E.path,E.shared)}))),y.extends)){let E=w.entities[y.extends]||w.relations[y.extends];if(y.allExtends=[y.extends,...E.allExtends||[]],y.idFields=E.idFields?(y.idFields||[]).concat(E.idFields):y.idFields,y.dataFields=E.dataFields?(y.dataFields||[]).concat(E.dataFields.map(A=>{let e=y.extends,s=l.entities[e]||l.relations[e];for(;!s.dataFields?.find(h=>h.path===A.path);)e=s.extends,s=l.entities[e]||l.relations[e];return {...A,dbPath:_t(e,A.path,A.shared)}})):y.dataFields,y.linkFields=E.linkFields?(y.linkFields||[]).concat(E.linkFields):y.linkFields,"roles"in E){let A=y,e=E;A.roles=A.roles||{},A.roles={...A.roles,...e.roles},Object.keys(A.roles).length===0&&(A.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(l,({key:w,value:p,meta:y})=>{if(w==="linkFields"){let E=(()=>{if(!y.nodePath)throw new Error("No path");let[e,s]=y.nodePath.split(".");return {thing:s,thingType:e==="entities"?"entity":e==="relations"?"relation":""}})(),A=Array.isArray(p)?p.map(e=>({...e,...E})):[{...p,...E}];o.push(...A);}}),immer.produce(d,w=>objectTraversal.traverse(w,({value:p,key:y,meta:b})=>{if(b.depth===2&&p.idFields&&!p.id){p.name=y;let E=()=>{if(b.nodePath?.split(".")[0]==="entities")return "entity";if(b.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=E(),p.computedFields=[],p.virtualFields=[],p.requiredFields=[],p.enumFields=[],p.fnValidatedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([e,s])=>{s.playedBy=o.filter(h=>h.relation===y&&h.plays===e)||[],s.name=e;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(e=>{if(e.target==="relation"){e.oppositeLinkFieldsPlayedBy=[{plays:e.path,thing:e.relation,thingType:"relation"}];return}let s=o.filter(r=>r.relation===e.relation&&r.plays!==e.plays)||[];e.oppositeLinkFieldsPlayedBy=s;let{filter:h}=e;e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>r.target==="role"),h&&Array.isArray(h)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>h.some(u=>r.thing===u.$role)),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>h.some(u=>r.thing===u.$thing))),h&&!Array.isArray(h)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>r.$role===h.$role),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>r.thing===h.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(E=>E.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${y} path:${b.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${y}, path:${b.nodePath}`)}if(b.depth===4){let[E,A]=b.nodePath?.split(".")||[],e=w[E][A];p.validations&&(p.validations.required&&e.requiredFields.push(p.path),p.validations.enum&&e.enumFields.push(p.path),p.validations.fn&&e.fnValidatedFields.push(p.path)),(p.default||p.computedValue)&&(p.isVirtual?e.virtualFields.push(p.path):e.computedFields.push(p.path));}}))},Rt=(l,o,d)=>{let a=D(l,o),w=a.linkFields?.find(b=>b.path===d);if(w)return w.cardinality;let p=a.dataFields?.find(b=>b.path===d);if(p)return p.cardinality;let y=a.roles[d];if(y)return y.cardinality},D=(l,o)=>{if(o.$thing){if(!o.$thingType)throw new Error("Missing $thingType in node$: {JSON.stringify(node, null, 2)");if(o.$thingType==="entity"){if(!(o.$thing in l.entities))throw new Error(`Missing entity '${o.$thing}' in the schema`);return l.entities[o.$thing]}if(o.$thingType==="relation"){if(!(o.$thing in l.relations))throw new Error(`Missing relation '${o.$thing}' in the schema`);return l.relations[o.$thing]}throw new Error(`Wrong schema or query for ${JSON.stringify(o,null,2)}`)}if(o.$entity){if(!(o.$entity in l.entities))throw new Error(`Missing entity '${o.$entity}' in the schema`);return l.entities[o.$entity]}if(o.$relation){if(!(o.$relation in l.relations))throw new Error(`Missing relation '${o.$relation}' in the schema`);return l.relations[o.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(o,null,2)}`)},J=(l,o)=>{let d=l.dataFields?.map(u=>u.path)||[],a=l.linkFields?.map(u=>u.path)||[],w="roles"in l?radash.listify(l.roles,u=>u):[],p=[...d||[],...a||[],...w||[]],b=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!o)return {fields:p,dataFields:d,roleFields:w,linkFields:a};let E=o.$fields?o.$fields.map(u=>{if(typeof u=="string")return u;if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error(" Wrongly structured query")}):radash.listify(o,u=>u),A=o.$filter?radash.listify(o.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&d?.includes(u)):[],e=o.$filter?radash.listify(o.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...w||[],...a||[]].includes(u)):[],s=[...E,...A].filter(u=>!b.includes(u)).filter(u=>u),h=o.$filter?it(o.$filter,(u,n)=>A.includes(u)):{},r=o.$filter?it(o.$filter,(u,n)=>e.includes(u)):{};return {fields:p,dataFields:d,roleFields:w,linkFields:a,usedFields:E,usedLinkFields:a.filter(u=>E.includes(u)),usedRoleFields:w.filter(u=>E.includes(u)),unidentifiedFields:s,...A.length?{localFilters:h}:{},...e.length?{nestedFilters:r}:{}}};var qt=l=>l!==null;var Ht=l=>{if(typeof l!="string")throw new Error("capitalizeFirstLetter: string is not a string");return l.charAt(0).toUpperCase()+l.slice(1).toLowerCase()};var Ut=async(l,o)=>{let{bqlRequest:d,config:a,tqlRequest:w}=l,{rawTqlRes:p}=o;if(d){if(!p)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:y}=d;if(!y){if(p.insertions?.length===0&&!w?.deletions){o.bqlRes={};return}let{mutation:b}=d;if(!b)throw new Error("TQL mutation not executed");let A=[...b.things,...b.edges].map(e=>{let s=p.insertions?.find(h=>h.get(`${e.$bzId}`))?.get(`${e.$bzId}`);if(e.$op==="create"||e.$op==="update"||e.$op==="link"){let h=s?.asThing().iid;return a.mutation?.noMetadata?radash.mapEntries(e,(r,u)=>[r.toString().startsWith("$")?Symbol.for(r):r,u]):{$dbId:h,...e,[e.path]:e.$id}}if(e.$op==="delete"||e.$op==="unlink")return e;if(e.$op!=="match")throw new Error(`Unsupported op ${e.$op}`)}).filter(e=>e);o.bqlRes=A;return}};var Ue=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Ke=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Kt=l=>{let d=l.toString().replace(Ue,"").trim().split("=>")[0].split("{")[0].replace(Ke,"").trim(),a=d.substring(d.indexOf("(")+1,d.lastIndexOf(")")).trim();return a?(a.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(p=>p.includes("{")&&p.includes("}")?(p.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(b=>b.split(":")[0].trim().replace(/['"[\]]/g,"")):p.trim()).filter(Boolean):[]};var Z=({currentThing:l,fieldSchema:o,mandatoryDependencies:d=!1})=>{if(!o||!o.default||!("fn"in o.default||"value"in o.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${o}`);if(o.default.type==="value")return o.default.value;if(d){let{fn:w}=o.default,y=Kt(w).filter(b=>!(b in l));if(y.length)throw new Error(`Virtual field: Missing arguments ${y.join(", ")}`)}return "default"in o?o.default?.fn(l):void 0},Jt=()=>{};var Ze=(l,o)=>l.length===1&&typeof l[0]!="string"&&l[0].$id===o?l[0]:l,Yt=l=>typeof l=="string"||!!l.$show,Gt=(l,o)=>immer.produce(l,d=>objectTraversal.traverse(d,({value:a})=>{if(Array.isArray(a)||typeof a!="object"||a===null)return;a.$tempId&&(a.$tempId=`_:${a.$tempId}`),a.$fields&&delete a.$fields,a.$filter&&delete a.$filter,a.$show&&delete a.$show,a.$bzId&&delete a.$bzId,o.query?.noMetadata&&(a.$entity||a.$relation)&&(delete a.$entity,delete a.$relation,delete a.$id),Object.getOwnPropertySymbols(a).forEach(p=>{delete a[p];}),a.$excludedFields&&(a.$excludedFields.forEach(p=>{delete a[p];}),delete a.$excludedFields);})),Pt=(l,o,d,a)=>l.map(([w,p])=>{if(!o||!o.includes(w))return null;if(!d.$fields||d.$fields.includes(a))return w;let y=d.$fields.find(b=>radash.isObject(b)&&b.$path===a);if(y){let b={...it(p,(A,e)=>A.startsWith("$"))},E=y.$fields?{...b,$fields:y.$fields}:b;if(y.$id){if(Array.isArray(y.$id))return y.$id.includes(w)?E:null;if(y.$id===w)return E}if(E.$fields&&E.$fields.includes("id")&&!E.$show){let A="";return E.$fields.forEach(e=>{e==="id"?A=E.$id:A=E;}),A}return E}return null}).filter(w=>w),Ye=(l,o)=>{let d={};return o.forEach(a=>{d[a.$bzId]=a.$id;}),l.forEach(a=>{Object.keys(a).forEach(w=>{d[a[w]]&&w!=="$tempId"&&(a[w]=d[a[w]]);});}),l},Ge=(l,o)=>{let d=o.map(w=>w.$bzId),a=!1;return l.forEach(w=>{Object.keys(w).forEach(p=>{d.includes(w[p])&&(a=!0);});}),a},ee=async(l,o)=>{let{bqlRequest:d,config:a,schema:w}=l,{cache:p}=o;if(!d)throw new Error("BQL request not parsed");let{query:y}=d;if(!y){let c=o.bqlRes[0]?o.bqlRes:[o.bqlRes],i=l.bqlRequest?.mutation?.things;if(Ge(c,i)){let F=Ye(c,i);o.bqlRes=F[1]?F:F[0];}let R=Gt(o.bqlRes,a);o.bqlRes=R;return}if(!p)return;let b="$entity"in y?y.$entity:y.$relation,E=p.entities.get(b.name);if(!E){o.bqlRes=null;return}let e=radash.listify(y.$filter,c=>c).some(c=>b.dataFields?.find(i=>i.path===c)?.validations?.unique),s=!Array.isArray(d.query)&&(d.query?.$id&&!Array.isArray(d.query?.$id)||e);if(Array.isArray(l.rawBqlRequest))throw new Error("Query arrays not implemented yet");let h=E,r=[...h].length?[...h].map(([c,i])=>({...l.rawBqlRequest,$id:c})):l.rawBqlRequest,u=immer.produce(r,c=>objectTraversal.traverse(c,({value:i})=>{let t=i;if(!t?.$entity&&!t?.$relation)return;let R="$entity"in t?t.$entity:t.$relation;if(R){let F=Array.isArray(t.$id)?t.$id:[t.$id],T="$relation"in t?w.relations[t.$relation]:w.entities[t.$entity],{dataFields:O,roleFields:B,fields:k}=J(T);a.query?.returnNulls&&(t.$fields?t.$fields.map(m=>typeof m=="string"?m:m.$path):k).forEach(m=>{t[m]=null;});let M=p.entities.get(R);if(!M)return;[...M].forEach(([$,m])=>{if(F.includes($)){let q=t.$fields?t.$fields:O,{virtualFields:S}=T;S?.forEach(Q=>{if(q?.includes(Q)&&(t[Q]===void 0||t[Q]===null)){let I=T.dataFields?.find(x=>x.path===Q),N=Z({currentThing:m,fieldSchema:I});t[Q]=N;}}),radash.listify(m,(Q,I)=>{Q.startsWith("$")||q?.includes(Q)&&(t[Q]=I);});let g=p.roleLinks.get($),L=t.$fields?t.$fields.filter(Q=>typeof Q=="string"):B,P=t.$fields?.filter(Q=>typeof Q=="object")?.map(Q=>Q.$path)||[];Object.entries(g||{}).forEach(([Q,I])=>{if(![...L,...P].includes(Q))return;if(!("roles"in T))throw new Error("No roles in schema");let N=Array.isArray(I)?[...new Set(I)]:[I],{cardinality:x,playedBy:v}=T.roles[Q],W=[...new Set(v?.map(C=>C.thing))]?.flatMap(C=>{let wt=p.entities.get(C);return wt?Pt([...wt],N,t,Q):[]});if(W?.length){if(W.length===1&&W[0]===t.$id)return;if(x==="ONE"){t[Q]=W[0];return}t[Q]=W.filter(C=>typeof C=="string"||typeof C=="object"&&C?.$show);}});}});let f=T.linkFields;f&&f.forEach($=>{let m=p.relations.get($.relation),q=$.oppositeLinkFieldsPlayedBy;if(!m)return null;if($.target==="relation"){let S=[...m].reduce((g,L)=>{let P=L.get($.plays)?.id;if(P&&P===F[0]){let Q=L.get($.relation);if(!Q)return g;g[Q.entityName]||(g[Q.entityName]=new Set),g[Q.entityName].add(Q.id);}return g},{});return Object.entries(S).map(([g,L])=>{let P=p.entities.get(g);if(!P)return null;let Q=Pt([...P],[...L.values()],t,$.path).filter(qt).filter(Yt);if(Q.length===0)return null;if(Q&&Q.length){if($.cardinality==="ONE")return t[$.path]=Q[0],null;t[$.path]=Q;}return null}),null}return $.target==="role"&&q.forEach(S=>{if(!m)return;let g=[...m].reduce((L,P)=>{let Q=P.get($.plays)?.id;if(Q&&Q===F[0]){let I=P.get(S.plays);if(!I)return L;L[I.entityName]||(L[I.entityName]=new Set),L[I.entityName].add(I.id);}return L},{});Object.entries(g).forEach(([L,P])=>{let Q=p.entities.get(L);if(!Q)return;let I=Pt([...Q],[...P.values()],t,$.path).filter(qt).filter(Yt);if(I.length!==0&&I&&I.length){if($.cardinality==="ONE"){t[$.path]=I[0];return}t[$.path]=I;let N={},x=Y=>(Y.$path===$.path&&(N=Y),Y?.$fields?.forEach(x)),v="";y.$fields?.forEach(x),N&&(Array.isArray(N.$id)||(v=N.$id)),t[$.path]=Ze(I,v);}});}),null});}})),n=Gt(u,a);o.bqlRes=s?n[0]:n;};var ie=async l=>{let{bqlRequest:o,schema:d}=l;if(!o)throw new Error("BQL request not parsed");let{mutation:a}=o;if(!a)throw new Error("BQL request is not a mutation");let w=r=>{let u=r.$op,n=`$${r.$bzId}`,c=D(d,r),{idFields:i,defaultDBConnector:t}=c,R=t?.path||r.$entity||r.$relation,F=r.$id,T=i?.[0],O=radash.listify(r,(g,L)=>{if(g.startsWith("$")||g===T||L===void 0||L===null)return "";let P=c.dataFields?.find(N=>N.path===g);if(!P?.path)return "";let I=P.dbPath;if(["TEXT","ID","EMAIL"].includes(P.contentType))return `has ${I} '${L}'`;if(["NUMBER","BOOLEAN"].includes(P.contentType))return `has ${I} ${L}`;if(P.contentType==="DATE"){if(Number.isNaN(L.valueOf()))throw new Error("Invalid format, Nan Date");return L instanceof Date?`has ${I} ${L.toISOString().replace("Z","")}`:`has ${I} ${new Date(L).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${P.contentType}`)}).filter(g=>g),B=`${n}-atts`,k=radash.listify(r,g=>{if(g.startsWith("$")||g===T)return "";let L=c.dataFields?.find(I=>I.path===g);if(!L?.path)return "";let Q=L.dbPath;return `{${B} isa ${Q};}`}).filter(g=>g),M=r[Symbol.for("isLocalId")],f=radash.isArray(F)?`like '${F.join("|")}'`:`'${F}'`,$=!M&&F?[`has ${T} ${f}`]:[],m=[...$,...O].filter(g=>g).join(","),q=()=>{if(u==="delete"||u==="unlink"||u==="match")return `${n} isa ${[R,...$].filter(g=>g).join(",")};`;if(u==="update"){if(!k.length)throw new Error("update without attributes");return `${n} isa ${[R,...$].filter(g=>g).join(",")}, has ${B};
|
|
35
|
-
${k.join(" or ")};`}return ""},S=()=>u==="update"||u==="link"||u==="match"?`${n} isa ${[R,...$].filter(g=>g).join(",")};`:"";if(r.$entity||r.$relation)return {op:u,deletionMatch:q(),insertionMatch:S(),insertion:u==="create"?`${n} isa ${[R,m].filter(g=>g).join(",")};`:u==="update"&&O.length?`${n} ${O.join(",")};`:"",deletion:u==="delete"?`${n} isa ${R};`:u==="update"&&k.length?`${n} has ${B};`:""};throw new Error("in attributes")},p=r=>{let u=r.$op,n=D(d,r),c=`$${r.$bzId}`,i=r.$id,t=n.defaultDBConnector?.path||r.$relation,R="roles"in n?radash.listify(n.roles,g=>g):[],F=r.$relation&&"roles"in n&&radash.mapEntries(n.roles,(g,L)=>[g,L.dbConnector?.path||g]),T=radash.listify(r,(g,L)=>{if(!R.includes(g))return null;if(!("roles"in n))throw new Error("This should have roles! ");let P=F[g];return Array.isArray(L)?L.map(Q=>({path:P,id:Q})):{path:P,id:L}}).filter(g=>g).flat(),O=T.map(g=>{if(!g?.path)throw new Error("Object without path");return `${g.path}: $${g.id}`}),B=T.length>0?`( ${O.join(" , ")} )`:"",k=r[Symbol.for("edgeType")];if(!k)throw new Error("[internal error] Symbol edgeType not defined");let M=B?`${c} ${B} ${k==="linkField"||u==="delete"||u==="unlink"?`isa ${t}`:""}`:"",f=`${c} ${k==="linkField"||u==="delete"?`isa ${t}`:""}`,$=()=>M?u==="link"?`${M};`:u==="create"?`${M}, has id '${i}';`:"":"",m=()=>M&&u==="match"?`${M};`:"",q=()=>M?u==="delete"?`${M};`:u==="match"?`${M};`:"":"",S=()=>M?u==="delete"?`${f};`:u==="unlink"?`${c} ${B};`:"":"";return {deletionMatch:q(),insertionMatch:m(),deletion:S(),insertion:$(),op:""}},y=(r,u)=>{let n=u==="edges"?p:w;if(Array.isArray(r))return r.map(T=>{let{preDeletionBatch:O,insertionMatch:B,deletionMatch:k,insertion:M,deletion:f}=n(T);return radash.shake({preDeletionBatch:O,insertionMatch:B,deletionMatch:k,insertion:M,deletion:f},$=>!$)}).filter(T=>T);let{preDeletionBatch:c,insertionMatch:i,deletionMatch:t,insertion:R,deletion:F}=n(r);return radash.shake({preDeletionBatch:c,insertionMatch:i,deletionMatch:t,insertion:R,deletion:F},T=>!T)},b=y(a.things),E=Array.isArray(b)?b:[b],A=y(a.edges,"edges"),e=Array.isArray(A)?A:[A],s=[...E,...e],h=radash.shake({insertionMatches:s.map(r=>r.insertionMatch).join(" ").trim(),deletionMatches:s.map(r=>r.deletionMatch).join(" ").trim(),insertions:s.map(r=>r.insertion).join(" ").trim(),deletions:s.map(r=>r.deletion).join(" ").trim()},r=>!r);l.tqlRequest=h;};var oi=l=>{if(!l.startsWith("_:"))throw new Error("ID must start with '_:'.");let o=l.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(o))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(l.length>36)throw new Error("$tempId must not be longer than 36 characters.");return o},re=async l=>{let{rawBqlRequest:o,schema:d}=l,w=(s=>immer.produce(s,h=>objectTraversal.traverse(h,({value:r,key:u,parent:n})=>{if(radash.isObject(r)&&(r=radash.shake(r,c=>c===void 0)),u==="$tempId"&&(n[u]=oi(r)),n&&radash.isArray(r)){if(!r.some(i=>typeof i=="object"&&"$id"in i))return;let c=r.flatMap(i=>typeof i=="string"?i:typeof i=="object"&&"$id"in i&&radash.isArray(i.$id)?i.$id.map(t=>({...i,$id:t})):i);n[u]=c;}})))(o),y=(s=>immer.produce(s,h=>objectTraversal.traverse(h,({value:r,meta:u,key:n})=>{if(radash.isObject(r)){if(r.$arrayOp)throw new Error("Array op not supported yet");if(n==="$filter"||u.nodePath?.includes(".$filter."))return;let c=r;if(c.$op==="create"&&c.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let i=D(d,c),R=u.nodePath?.split(".")?.filter(f=>Number.isNaN(parseInt(f,10))).join(".");if(!i)throw new Error(`Schema not found for ${c.$entity||c.$relation}`);c.$bzId=c.$tempId??`T_${uuid.v4()}`,c[Symbol.for("schema")]=i,c[Symbol.for("dbId")]=i.defaultDBConnector.id;let{usedLinkFields:F,usedRoleFields:T}=J(i,c),O=F.map(f=>({fieldType:"linkField",path:f,schema:i.linkFields.find($=>$.path===f)})),B=i.thingType==="relation"?T.map(f=>({fieldType:"roleField",path:f,schema:ft(i.roles,$=>$===f)})):[];if(O.some(f=>f.schema?.target==="role")&&O.some(f=>f.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let k=B.filter(f=>[...new Set(f.schema.playedBy?.map($=>$.thing))].length!==1);if(k.length>1)throw new Error(`Field: ${k[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(k[0].schema.playedBy)}. Schema: ${JSON.stringify(k[0].schema)}`);let M=u.nodePath;if([...O,...B].forEach(f=>{let $=c[f.path];if($===void 0)return;let m=f.schema;if(!m)throw new Error(`Field ${f.path} not found in schema`);let q=f.fieldType==="roleField"?m?.playedBy[0]:m,g=m&&"relation"in m&&q?.relation===c.$relation?"$self":q?.relation?q?.relation:"$self",L=g==="$self"?i:d.relations[g];if(ft(L.roles,(v,Y)=>v===f.path)?.playedBy?.length===0)throw new Error(`unused role: ${M}.${f.path}`);if(!m)throw new Error(`Field ${f.path} not found in schema`);let Q=f.fieldType==="linkField"?m?.oppositeLinkFieldsPlayedBy:m?.playedBy;if(!Q)throw new Error(`No opposite fields found for ${JSON.stringify(m)}`);if([...new Set(Q?.map(v=>v.thing))].length>1)throw new Error(`Field: ${f.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(Q)}. Schema: ${JSON.stringify(m)}`);if(m.cardinality==="ONE"&&Array.isArray($))throw new Error("Can't have an array in a cardinality === ONE link field");if(m.cardinality==="MANY"&&$!==null&&!Array.isArray($)&&!$.$arrayOp)throw new Error(`${f.fieldType==="linkField"?m.path:m.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if($?.$entity||$?.$relation)return;let[I]=Q,N="plays"in m?"linkField":"roleField",x={[`$${I.thingType}`]:I.thing,[Symbol.for("relation")]:g,[Symbol.for("edgeType")]:N,[Symbol.for("parent")]:{path:M,...c.$id?{$id:c.$id}:{},...c.$tempId?{$tempId:c.$tempId}:{},...c.filter?{filter:c.filter}:{},links:Q},[Symbol.for("role")]:I.plays,[Symbol.for("oppositeRole")]:"plays"in m?m.plays:void 0,[Symbol.for("relFieldSchema")]:m};if(radash.isObject($)&&(c[f.path]={...x,...$}),Array.isArray($))if($.every(v=>radash.isObject(v)))c[f.path]=$.map(v=>({...x,...v}));else if($.every(v=>typeof v=="string"))c[f.path]=$.map(v=>({...x,$op:c.$op==="create"?"link":"replace",$id:v}));else throw new Error(`Invalid array value for ${f.path}`);if(typeof $=="string"&&(c[f.path]={...x,$op:c.$op==="create"?"link":"replace",$id:$}),$===null){let v={...x,$op:"unlink"};c[f.path]=m.cardinality==="MANY"?[v]:v;}}),!R&&!c.$entity&&!c.$relation)throw new Error("Root things must specify $entity or $relation")}})))(w),E=(s=>immer.produce(s,h=>objectTraversal.traverse(h,({parent:r,key:u,value:n,meta:c})=>{if(radash.isObject(n)){if(Object.keys(n).length===0)throw new Error("Empty object!");if(u==="$filter"||c.nodePath?.includes(".$filter."))return;let i=n,t=c.nodePath?.split(".");if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$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.`);let R=t?.filter(P=>Number.isNaN(parseInt(P,10))).join("."),F=R?Array.isArray(r)?t?.slice(0,-1).join("."):c.nodePath:c.nodePath||"",T=D(d,i),{dataFields:O,roleFields:B,linkFields:k}=J(T,i),M=immer.current(i)[Symbol.for("parent")],f=R&&M.path,m=(f?objectTraversal.getNodeByPath(h,f):h)?.$op;if(R&&!m)throw new Error("Error: Parent $op not detected");let q=i[Symbol.for("relFieldSchema")];i.$op==="replace"&&m==="create"&&(i.$op="link");let S=Object.keys(i).some(P=>O?.includes(P)),g=Object.keys(i).some(P=>[...B,...k].includes(P)),L=()=>{if(i.$op)return i.$op;if(R&&!i.$id&&!i.$tempId&&m!=="create"&&q.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${c.nodePath}`);if(i.$tempId)return "create";if((i.$id||i.$filter)&&S)return "update";if((i.$id||i.$filter)&&R&&!S&&!g)return "link";if(!i.$filter&&!i.$id&&!i.$tempId)return "create";if((i.$id||i.$filter)&&!S&&g)return "match";throw new Error("Wrong op")};if(i.$op||(i.$op=L()),r||(i.$parentKey=""),typeof r=="object"&&(Array.isArray(r)&&(i[Symbol.for("index")]=u),i[Symbol.for("path")]=F,i[Symbol.for("isRoot")]=!R,i[Symbol.for("depth")]=R?.split(".").length),!i.$entity&&!i.$relation)throw new Error(`Node ${JSON.stringify(i)} without $entity/$relation`)}})))(y),e=(s=>immer.produce(s,h=>objectTraversal.traverse(h,({value:r})=>{if(radash.isObject(r)){let u=r,n=D(d,u),{unidentifiedFields:c}=J(n,u),{idFields:i}=n;if(!i)throw new Error("No idFields found");let[t]=i;if(u.$op==="create"&&!u[t]){let R=n.dataFields?.find(T=>T.path===t),F=Z({currentThing:u,fieldSchema:R,mandatoryDependencies:!0});if(typeof F!="string")throw new Error(`Default id field ${t} is not a string`);u[t]=F,u.$id=F;}if(c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(u)}`)}})))(E);l.filledBqlRequest=e;};var le=async l=>{let{filledBqlRequest:o,schema:d}=l,a=e=>{let s=[],h=[],r=i=>{if(i.$id)return i.$id;let t=D(d,i),{idFields:R}=t;if(!R)throw new Error(`no idFields: ${JSON.stringify(i)}`);let[F]=R;if(!F)throw new Error(`no idField: ${JSON.stringify(i)}`);let T=t.dataFields?.find(k=>k.path===F),O=Z({currentThing:i,fieldSchema:T,mandatoryDependencies:!0}),B=i[F]||i.$id||O;if(!B)throw new Error(`no idValue: ${JSON.stringify(i)}`);return B},u=i=>{if(i.$op==="create"){let t=r(i);if(s.find(R=>R.$id===t))throw new Error(`Duplicate id ${t} for node ${JSON.stringify(i)}`);if(h.find(R=>R.$bzId===i.$bzId))throw new Error(`Duplicate $bzid ${i.$bzId} for node ${JSON.stringify(i)}`);s.push({...i,$id:t});return}i.$tempId&&i.$op==="match"||s.push(i);},n=i=>{if(i.$op==="create"){let t=r(i);if(s.find(R=>R.$id===t),h.find(R=>R.$bzId===i.$bzId))throw new Error(`Duplicate %bzId ${i.$bzIdd} for edge ${JSON.stringify(i)}`);h.push({...i,$id:t});return}h.push(i);};return objectTraversal.traverse(e,({value:i})=>{if(!radash.isObject(i))return;let t=i;if(t.$entity||t.$relation){if(!t.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(t)}`);if(!t.$bzId)throw new Error("[internal error] BzId not found");let R=D(d,t),{dataFields:F,roleFields:T,linkFields:O,usedFields:B}=J(R,t),k=()=>{if(t.$op==="create"||t.$op==="delete")return t.$op;if(t.$op==="update"){let f=B.filter(q=>F?.includes(q)),$=B.filter(q=>T?.includes(q)),m=B.filter(q=>O?.includes(q));if(f.length>0)return "update";if($.length>0||m.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(t)}`)}return "match"},M={...t.$entity&&{$entity:t.$entity},...t.$relation&&{$relation:t.$relation},...t.$id&&{$id:t.$id},...t.$tempId&&{$tempId:t.$tempId},...t.$filter&&{$filter:t.$filter},...radash.shake(radash.pick(t,F||[""])),$op:k(),$bzId:t.$bzId,[Symbol.for("dbId")]:R.defaultDBConnector.id,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("isRoot")]:t[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:t[Symbol.for("isLocalId")]||!1};if(u(M),t[Symbol.for("relation")]&&t[Symbol.for("edgeType")]==="linkField"){if((t.$op==="link"||t.$op==="unlink")&&(t.$id||t.$filter)){if(t.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");s.push({...t,$op:"match"});}let f=t[Symbol.for("relation")]===t.$relation,$=f?t.$bzId:uuid.v4(),q=t[Symbol.for("parent")].path,g=(q?objectTraversal.getNodeByPath(e,q):e).$bzId;if(!g)throw new Error("No parent id found");if(t[Symbol.for("relation")]==="$self")return;let L=()=>{if(t.$op==="delete")return f?"match":"delete";if(t.$op==="unlink")return f?"unlink":"delete";if(t.$op==="link"||t.$op==="create")return f?"link":"create";if(t.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},P={$relation:t[Symbol.for("relation")],$bzId:$,...t.$tempId?{$tempId:t.$tempId}:{},$op:L(),...f?{}:{[t[Symbol.for("role")]]:t.$bzId},[t[Symbol.for("oppositeRole")]]:g,[Symbol.for("dbId")]:d.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]};n(P),(t.$op==="unlink"||L()==="unlink")&&f&&n({$relation:t[Symbol.for("relation")],$bzId:$,$op:"match",[t[Symbol.for("oppositeRole")]]:g,[Symbol.for("dbId")]:d.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]});}if(t.$relation){let f=it(t,(q,S)=>T.includes(q)),$=radash.mapEntries(f,(q,S)=>radash.isArray(S)?[q,S]:radash.isObject(S)?[q,S.$bzId]:[q,S]),m=it(i,(q,S)=>q.startsWith("$")||q.startsWith("Symbol"));if(Object.keys(f).filter(q=>!q.startsWith("$")).length>0){if(t.$op==="create"||t.$op==="delete"){let q=()=>{if(t.$op==="create")return "link";if(t.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=radash.mapEntries($,(L,P)=>Array.isArray(P)?[L,P.map(Q=>Q.$bzId||Q)]:[L,P.$bzId||P]),g={...m,$relation:t.$relation,$op:q(),...S,$bzId:t.$bzId,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("dbId")]:R.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};n(g);return}if(t.$op==="match"||t.$op==="update"&&Object.keys(f).length>0){let q=0;Object.entries(f).forEach(([S,g])=>{let L=radash.isArray(g)?g:[g],P=Q=>Q==="create"||Q==="replace"?"link":Q;L.forEach(Q=>{if(!Q)return;let I=P(Q.$op);if(I==="replace")throw new Error("Not supported yet: replace on roleFields");if(I==="unlink"&&q>0)throw q+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let N={...m,$relation:t.$relation,$op:I==="delete"?"unlink":I,[S]:Q.$bzId,$bzId:t.$bzId,[Symbol.for("dbId")]:R.defaultDBConnector.id,[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};n(N);});});}}}}}),[s,h]};if(!o)throw new Error("Undefined filledBqlRequest");let [w,p]=a(o),y=w.reduce((e,s)=>{if(!s.$bzId)return [...e,s];let h=e.findIndex(r=>r.$bzId===s.$bzId);if(h===-1)return [...e,s];if(e[h].$op==="create"&&s.$op==="match")return e;if(e[h].$op==="match"&&(s.$op==="create"||s.$op==="match"))return [...e.slice(0,h),s,...e.slice(h+1)];throw new Error(`Unsupported operation combination for $tempId "${s.$tempId}". Existing: ${e[h].$op}. Current: ${s.$op}`)},[]),b=p.reduce((e,s)=>{let h=e.find(r=>(r.$id&&r.$id===s.$id||r.$bzId&&r.$bzId===s.$bzId)&&r.$relation===s.$relation&&r.$op===s.$op);if(h){let r={...h};return Object.keys(s).forEach(n=>{if(typeof n=="symbol"||n.startsWith("$"))return;let c=h[n],i=s[n];Array.isArray(c)&&Array.isArray(i)?r[n]=Array.from(new Set([...c,...i])):!Array.isArray(c)&&Array.isArray(i)?c!==void 0?r[n]=Array.from(new Set([c,...i])):r[n]=i:Array.isArray(c)&&!Array.isArray(i)?i!==void 0&&(r[n]=Array.from(new Set([...c,i]))):c!==null&&i!==null&&c!==void 0&&i!==void 0?r[n]=Array.from(new Set([c,i])):c==null&&(r[n]=i);}),[...e.filter(n=>!((n.$id&&n.$id===s.$id||n.$bzId&&n.$bzId===s.$bzId)&&n.$relation===s.$relation&&n.$op===s.$op)),r]}return [...e,s]},[]);[...new Set(b.map(e=>e.$relation))];l.bqlRequest={mutation:{things:y,edges:b}};};var ut=async(l,o)=>{let d=o.dbConnectors[0].id,a=l.typeDB.get(d)?.session,w=l.typeDB.get(d)?.client;if(!a||!a.isOpen()){if(!w)throw new Error("Client not found");a=await w.session(o.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),l.typeDB.set(d,{client:w,session:a});}return {client:w,session:a}};var de=async(l,o)=>{let{dbHandles:d,tqlRequest:a,bqlRequest:w,config:p}=l;if(!a)throw new Error("TQL request not built");if(!(a.deletions&&a.deletionMatches||a.insertions))throw new Error("TQL request error, no things");if(!w?.mutation)throw new Error("BQL mutation not parsed");let{session:y}=await ut(d,p),b=await y.transaction(typedbDriver.TransactionType.WRITE);if(!b)throw new Error("Can't create transaction");let E=a.deletionMatches&&a.deletions&&`match ${a.deletionMatches} delete ${a.deletions}`,A=a.insertions&&`${a.insertionMatches?`match ${a.insertionMatches}`:""} insert ${a.insertions}`;E&&await b.query.delete(E);let e=A&&b.query.insert(A);try{let s=e?await e.collect():void 0;await b.commit(),await b.close(),o.rawTqlRes={insertions:s};}catch(s){throw await b.close(),new Error(`Transaction failed: ${s.message}`)}};var bt=Symbol.for("schema"),K=Symbol.for("queryPath");var H="___",ce=async l=>{let{enrichedBqlQuery:o}=l;if(!o)throw new Error("BQL query not enriched");let d="",a=(e,s)=>{let h="",r="";for(let u in e){let n=e[u];if(Array.isArray(n))for(let c=0;c<n.length;c++)r+=`{$${s} has ${u} "${n[c]}";}`,c<n.length-1?r+="or":r+=";";else h+=`, has ${u} "${n}"`;}h+=`;
|
|
36
|
-
`,
|
|
37
|
-
`;n
|
|
38
|
-
`,
|
|
39
|
-
`,
|
|
40
|
-
`,
|
|
41
|
-
`,
|
|
42
|
-
`,
|
|
43
|
-
;`;let
|
|
44
|
-
`;}},y=(e,s,
|
|
45
|
-
`,
|
|
46
|
-
`,
|
|
47
|
-
`:
|
|
48
|
-
`,
|
|
49
|
-
`,
|
|
50
|
-
`,
|
|
51
|
-
;`;let
|
|
52
|
-
`;}},
|
|
53
|
-
$${
|
|
54
|
-
`,
|
|
55
|
-
`,
|
|
56
|
-
;`,
|
|
57
|
-
$${
|
|
58
|
-
`,
|
|
59
|
-
`,
|
|
60
|
-
;`,n){let i=n.filter(F=>F.$fieldType==="data");i&&i.length>0&&w(i,h);let t=n.filter(F=>F.$fieldType==="link");t&&t.length>0&&y(t,h,h);let R=n.filter(F=>F.$fieldType==="role");R&&R.length>0&&p(R,h,h);}}})(o),l.tqlRequest=b?E:d;};var It=l=>{let o=l.dataFields?.map(p=>p.path)||[],d=l.linkFields?.map(p=>p.path)||[],a=Object.keys(l.roles||{})||[];return [...o,...d,...a]},Ct=(l,o)=>Object.keys(l||{}).some(a=>{if(!Array.isArray(l[a])){let w=o.idFields?.includes(a),p=o.dataFields?.some(y=>(y.dbPath===a||y.path===a)&&y?.validations?.unique);return w||p}return !1}),Nt=(l,o)=>{let d=o.dataFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],a=o.linkFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],w=Object.keys(o.roles||{}).map(y=>({path:y,dbPath:y}))||[],p=[...d,...a,...w];return Object.entries(l||{}).reduce((y,[b,E])=>{let A=p.find(e=>e.path===b);return y[A?.dbPath||b]=E,y},{})},ue=async l=>{let{rawBqlRequest:o,schema:d}=l;if(Array.isArray(o)){for(let e of o)if(!("$entity"in e)&&!("$relation"in e)&&(!("$thing"in e)||!("$thingType"in e)))throw new Error("No entity specified in query")}else if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let a=(e,s)=>typeof s=="string"?e.idFields?.includes(s):e.idFields?.includes(s.$path),w=(e,s,h,r,u)=>({$path:s,$dbPath:r,$thingType:"attribute",$as:e.$as||s,$var:s,$fieldType:"data",$excludedFields:e.$excludedFields,$justId:h,$id:e.$id,$filter:e.$filter,$isVirtual:u,$filterProcessed:!0}),p=(e,s,h,r,u)=>{let{target:n,oppositeLinkFieldsPlayedBy:c}=h;return c.map(i=>{let t=n==="role"?i.thingType:"relation",R=n==="role"?i.thing:h.relation,F={[`$${t}`]:R},T=D(d,F),O=e?.$fields?.filter(k=>a(T,k)).length===0,B=[];return typeof e!="string"?e.$fields?O?B=[...e.$fields,...T.idFields]:B=e.$fields:B=It(T):B=["id"],e.$excludedFields&&(B=B.filter(k=>a(T,k)?!0:!e.$excludedFields.includes(k.$path))),{$thingType:t,$plays:h.plays,$playedBy:i,$path:i.path,$dbPath:u,$as:e.$as||s,$var:s,$thing:R,$fields:B,$excludedFields:e.$excludedFields,$fieldType:"link",$target:n,$intermediary:i.relation,$justId:r,$id:e.$id,$filter:Nt(e.$filter,T),$idNotIncluded:O,$filterByUnique:Ct(e.$filter,T),$filterProcessed:!0}})},y=(e,s,h,r,u)=>h.playedBy.map(n=>{let{thing:c,thingType:i,relation:t}=n,R={[`$${i}`]:c},F=D(d,R),T=e?.$fields?.filter(B=>F?.idFields?.includes(B)||F?.idFields?.includes(B.$path)).length===0,O=[];return typeof e!="string"?e.$fields?T?O=[...e.$fields,...F.idFields]:O=e.$fields:O=It(F):O=["id"],e.$excludedFields&&(O=O.filter(B=>a(F,B)?!0:!e.$excludedFields.includes(B.$path))),{$thingType:i,$path:s,$dbPath:u,$as:e.$as||s,$var:s,$thing:c,$fields:O,$excludedFields:e.$excludedFields,$fieldType:"role",$intermediary:t,$justId:r,$id:e.$id,$filter:Nt(e.$filter,F),$idNotIncluded:T,$filterByUnique:Ct(e.$filter,F),$playedBy:n,$filterProcessed:!0}}),b=(e,s)=>{let h=typeof e=="string"?e:e.$path,r=typeof e=="string",u=s.dataFields?.find(i=>i.path===h),n=s.linkFields?.find(i=>i.path===h),c=s.roles?.[h];return u?w(e,h,r,u.dbPath,u.isVirtual):n?p(e,h,n,r,n.dbPath):c?y(e,h,c,r,c.dbPath):null},A=(e=>immer.produce(e,s=>objectTraversal.traverse(s,h=>{let{value:r,meta:u}=h,n=r;if(radash.isObject(n)){if(n.$id){let c=n.$entity||n.$relation?n:{[`$${n.$thingType}`]:n.$thing},i=D(d,c);if(n.$path=i.name,Array.isArray(n.$id)||(n.$filterByUnique=!0),i?.idFields?.length===1){let[t]=i.idFields;n.$filter={...n.$filter,[t]:n.$id},delete n.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in n||"$relation"in n){let c=D(d,n);n.$path=c.name,n.$as=c.name;}if(n.$entity?(n.$thing=n.$entity,n.$thingType="entity",delete n.$entity):n.$relation&&(n.$thing=n.$relation,n.$thingType="relation",delete n.$relation),radash.isObject(n)&&"$thing"in n){let c=n.$entity||n.$relation?n:{[`$${n.$thingType}`]:n.$thing};n[K]=u.nodePath;let i=D(d,c);if(n.$filter&&(n.$filterByUnique=Ct(n.$filter,i),n.$filterProcessed||(n.$filter=Nt(n.$filter,i))),n.$fields){n.$fields.filter(F=>i?.idFields?.includes(F)||i?.idFields?.includes(F.$path)).length>0||(n.$fields=[...n.$fields,...i.idFields],n.$idNotIncluded=!0);let R=n.$fields?.flatMap(F=>{let T=b(F,i);return Array.isArray(T)?T:[T]}).filter(Boolean);n.$fields=R;}else {let R=It(i)?.flatMap(F=>{let T=b(F,i);return Array.isArray(T)?T:[T]}).filter(Boolean);n.$fields=R;}n.$excludedFields&&(n.$fields=n.$fields.filter(t=>a(i,t)?!0:!n.$excludedFields.includes(t.$path)));}}})))(Array.isArray(o)?o:[o]);l.enrichedBqlQuery=A;};var ye=async(l,o)=>{let{dbHandles:d,enrichedBqlQuery:a,tqlRequest:w,config:p}=l;if(!a)throw new Error("BQL request not parsed");if(!w)throw new Error("TQL request not built");if(Array.isArray(w)){let b=await radash.parallel(w.length,w,async E=>{let{session:A}=await ut(d,p),e=await A.transaction(typedbDriver.TransactionType.READ);if(!e)throw new Error("Can't create transaction");let h=await e.query.fetch(E).collect();return await e.close(),h});o.rawTqlRes=b,o.isBatched=!0;}else {let{session:b}=await ut(d,p),E=await b.transaction(typedbDriver.TransactionType.READ);if(!E)throw new Error("Can't create transaction");let e=await E.query.fetch(w).collect();await E.close(),o.rawTqlRes=e;}};var he=l=>{let o=/as:([a-zA-Z0-9_\-·]+)/,d=/justId:([a-zA-Z0-9_\-·]+)/,a=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,w=/filterByUnique:([a-zA-Z0-9_\-·]+)/,p=l.match(o),y=l.match(d),b=l.match(a),E=l.match(w);return {as:p?p[1]:null,justId:y?y[1]:null,idNotIncluded:b?b[1]:null,filterByUnique:E?E[1]:null}},mi=l=>{try{let d=(w=>{let p=w.replace("$metadata:","");return p=p.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),p=p.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(y,b,E)=>/^{.*}$/.test(E)?`:${E}`:`:${b}"${E}"`),p=p.replace(/\[([^\]]+)\]/g,(y,b)=>`[${b.split(",").map(E=>E.trim().startsWith("{")&&E.trim().endsWith("}")?E.trim():`"${E.trim()}"`).join(",")}]`),p})(l);return JSON.parse(d)}catch(o){return console.error(o),{as:[],virtual:[]}}},$e=async(l,o)=>{let{enrichedBqlQuery:d,rawBqlRequest:a,schema:w,config:p}=l,{rawTqlRes:y,isBatched:b}=o;if(d){if(!y)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let E=(n,c)=>{let{$metaData:i}=n,{as:t}=mi(i),R=Object.entries(n).filter(([F])=>F!=="type"&&!F.includes("$")).map(([F,T])=>{let O=c.dataFields?.find(f=>f.path===F||f.dbPath===F),B=F==="id",k=Array.isArray(t)?t.find(f=>f[F])?.[F]:F,M;if(O?.cardinality==="ONE"){if(M=T[0]?T[0].value:p.query?.returnNulls?null:void 0,O.contentType==="DATE"&&(M=`${M}Z`),B)return [[k,M],["$id",M]].filter(([f,$])=>$!==void 0)}else if(O?.cardinality==="MANY"){if(!radash.isArray(T))throw new Error("Typedb fetch has changed its format");O.contentType==="DATE"?M=T.map(f=>`${f.value}Z`):M=T.map(f=>f.value);}return [[k,M]].filter(([f,$])=>$!==void 0)}).flat();return Object.fromEntries([...R])},A=n=>n.reduce((c,i)=>{let{$roleFields:t,$metaData:R,$cardinality:F}=i,{as:T,justId:O,idNotIncluded:B,filterByUnique:k}=he(R),M=t.map(f=>{let{dataFields:$,currentSchema:m,linkFields:q,roleFields:S,schemaValue:g}=s(f),L=E($,m);if(O==="T")return L.id;{let P=e(q),Q=A(S),I={...L};return B==="true"&&m?.idFields?.forEach(N=>delete I[N]),{...I,...P,...Q,...g}}});return M.length>0?c[T]=F==="MANY"&&k==="false"?M:M[0]:p.query?.returnNulls&&(c[T]=null),c},{}),e=n=>n.reduce((c,i)=>{let{$linkFields:t,$metaData:R,$cardinality:F}=i,{as:T,justId:O,idNotIncluded:B,filterByUnique:k}=he(R),M=t.map(f=>{let{dataFields:$,currentSchema:m,linkFields:q,roleFields:S,schemaValue:g}=s(f),L=E($,m);if(O==="T")return L.id;{let P=e(q),Q=A(S),I={...L};return B==="true"&&m.idFields?.forEach(N=>delete I[N]),{...I,...P,...Q,...g}}});return c[T]=M.length>0?F==="MANY"&&k==="false"?M:M[0]:p.query?.returnNulls?null:void 0,c},{}),s=n=>{let c=Object.keys(n),i=c.find(f=>f.endsWith(".$dataFields"));if(!i)throw new Error("No datafields");let t=n[i],R=i.split(".")[i.split(".").length-2];if(t.$metaData=R,t.length===0)throw new Error("No datafields");let F=t.type,T={$thing:F.label,$thingType:F.root,[K]:n.queryPath.value},O={[`$${T.$thingType}`]:T.$thing},B=D(w,O),k=c.filter(f=>!f.endsWith(".$dataFields")&&B.linkFields?.some($=>$.path===f.split(".").pop())).map(f=>({$linkFields:n[f],$key:f.split(".").pop(),$metaData:f.split(".")[f.split(".").length-2],$cardinality:B?.linkFields?.find($=>$.path===f.split(".").pop())?.cardinality})),M=c.filter(f=>!f.endsWith(".$dataFields")&&B.roles?.[f.split(".").pop()]).map(f=>({$roleFields:n[f],$key:f.split(".").pop(),$metaData:f.split(".")[f.split(".").length-2],$cardinality:B.roles[f.split(".").pop()].cardinality}));return {dataFields:t,schemaValue:T,currentSchema:B,linkFields:k,roleFields:M}},h=n=>n.map(c=>{let{dataFields:i,currentSchema:t,linkFields:R,roleFields:F,schemaValue:T}=s(c),O=E(i,t),B=e(R),k=A(F),M=a?.$fields?.every($=>!t?.idFields?.includes($)&&!t?.idFields?.includes($.$path));return {...B,...k,...T,...!p.query?.noMetadata&&a.$id?{$id:Array.isArray(a.$id)?O.id:a.$id}:{},...M?Object.fromEntries(Object.entries(O).filter(([$])=>!t?.idFields?.includes($))):O}}),u=(n=>{let c=i=>{let t=h(i);return a.$id&&!Array.isArray(a.$id)||d[0].$filterByUnique?t[0]??null:t.length===0?null:t};return b?n.map(c):c(n)})(y);o.bqlRes=u;};var gi=Symbol.for("grandChildOfCreate"),rt=l=>({...l[Symbol.for("relation")]&&{[Symbol.for("relation")]:l[Symbol.for("relation")]},...l[Symbol.for("parent")]&&{[Symbol.for("parent")]:l[Symbol.for("parent")]},...l[Symbol.for("edgeType")]&&{[Symbol.for("edgeType")]:l[Symbol.for("edgeType")]},...l[Symbol.for("role")]&&{[Symbol.for("role")]:l[Symbol.for("role")]},...l[Symbol.for("oppositeRole")]&&{[Symbol.for("oppositeRole")]:l[Symbol.for("oppositeRole")]},...l[Symbol.for("relFieldSchema")]&&{[Symbol.for("relFieldSchema")]:l[Symbol.for("relFieldSchema")]},...l[Symbol.for("path")]&&{[Symbol.for("path")]:l[Symbol.for("path")]},...l[Symbol.for("isRoot")]&&{[Symbol.for("isRoot")]:l[Symbol.for("isRoot")]},...l[Symbol.for("depth")]&&{[Symbol.for("depth")]:l[Symbol.for("depth")]},...l[Symbol.for("schema")]&&{[Symbol.for("schema")]:l[Symbol.for("schema")]},...l[Symbol.for("dbId")]&&{[Symbol.for("dbId")]:l[Symbol.for("dbId")]},...l[Symbol.for("index")]&&{[Symbol.for("index")]:l[Symbol.for("index")]}}),me=async l=>{let{filledBqlRequest:o,config:d,schema:a}=l,w=(B,k)=>Object.keys(B).filter(M=>M.startsWith("$")?!1:k?!D(a,B).dataFields?.find($=>$.path===M):!0);if(!o)throw new Error("[BQLE-M-PQ-1] No filledBqlRequest found");if(d.mutation?.preQuery===!1)return;let p=[];if(objectTraversal.traverse(o,({parent:B,key:k,value:M})=>{B&&k&&!k.includes("$")&&radash.isObject(B)?(Array.isArray(B[k])?B[k]:[B[k]]).forEach($=>{if(radash.isObject($)){if(B.$op!=="create")p.includes($.$op)||p.push($.$op);else if($.$op==="delete"||$.$op==="unlink")throw new Error(`Cannot ${$.$op} under a create`)}}):!B&&radash.isObject(M)&&(p.includes(M.$op)||p.push(M.$op));}),!p.includes("delete")&&!p.includes("unlink")&&!p.includes("replace")&&!p.includes("update")&&!p.includes("link"))return;let b=(B=>{let k=(M,f)=>{let $=[],m={},q=["$op","$bzId","$parentKey"],S=["$relation","$entity","$id",...q];for(let g in M)if(!q.includes(g)&&!(S.includes(g)&&!f))if(!g.includes("$")&&(radash.isObject(M[g])||Array.isArray(M[g]))){let L=M[g];Array.isArray(L)&&L.length>0?L.forEach(P=>{$.push({$path:g,...k(P)});}):$.push({$path:g,...k(L)});}else m[g]=M[g];return {...m,$fields:$}};return B.map(M=>k(M,!0))})(Array.isArray(o)?o:[o]),E=await Ft(b,l.config,l.schema,l.dbHandles),A=(B,k)=>{let M=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:f}=B,$=f?.beforePath||"root",m=Array.isArray(f.ids)?`[${f.ids}]`:f.ids;return {beforePath:`${$}.${m}___${f.key}`,ids:M,key:k}}else return {beforePath:"root",ids:M,key:k}},e=(B,k)=>{let M=B?.beforePath||"root",f=k||(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${M}.${f}___${B?.key}`},s=B=>{if(B.includes("[")&&B.includes("]")){let[k,M,f]=B.split(/[[\]]/);return M.split(",").map(m=>`${k}${m}${f}`)}else return [B]},h={};(B=>immer.produce(B,k=>objectTraversal.traverse(k,M=>{let{key:f,parent:$}=M;if($&&f&&$.$id&&!f.includes("$")){let m=A($,f),q=e(m);if(Array.isArray($[f])){let S=[];$[f].forEach(g=>{radash.isObject(g)?(g.$objectPath=m,S.push(g.$id.toString())):g&&S.push(g.toString());}),h[q]={$objectPath:m,$ids:S};}else {let S=$[f];radash.isObject(S)?(h[q]={$objectPath:m,$ids:[S.$id.toString()]},S.$objectPath=m):S&&(h[q]={$objectPath:m,$ids:[S.toString()]});}}})))(E||{});let u=B=>immer.produce(B,k=>objectTraversal.traverse(k,M=>{let{key:f,value:$,parent:m}=M;m&&f&&!f.includes("$")&&(Array.isArray($)||radash.isObject($))&&!Array.isArray(m)&&(Array.isArray(m[f])?m[f].forEach(q=>{typeof q!="string"&&(q.$objectPath=A(m,f),q.$parentIsCreate=m.$op==="create",q[gi]=m.$parentIsCreate||m[Symbol.for("grandChildOfCreate")]);}):radash.isObject(m[f])&&(m[f].$parentIsCreate=m.$op==="create",m[f][Symbol.for("grandChildOfCreate")]=m.$parentIsCreate||m[Symbol.for("grandChildOfCreate")],m[f].$objectPath=A(m,f)));})),n=u(o),i=(B=>{let k=(m,q)=>{let S=[];m.filter(Q=>Q).forEach(Q=>{let I=Object.keys(Q).filter(N=>!N.startsWith("$")).length;if(Array.isArray(Q.$id)&&I>0){let N=Q.$id.map(x=>({...Q,$id:x}));S=[...S,...N];}else S.push({...Q});});let g=[],L=[],P=S.filter(Q=>{let N=["delete","update","unlink"].includes(Q.$op||""),x=w(Q,!0).length;if((!Q.$id||Array.isArray(Q.$id)&&x>0||Q.$filter)&&N)return !0;L.push({...Q});});return P.length>0?P.forEach(Q=>{let N=(z=>{let at=(()=>{let V={};for(let j in z){let X=D(a,z);!j.startsWith("$")&&X.dataFields?.find(ot=>ot.path===j)&&(V[j]=z[j]);}return V})(),lt=Object.keys(z),G=lt.filter(V=>!V.startsWith("$")),Et=[],yt=(V,j)=>{if(V===G.length){let ot={...j};lt.forEach(_=>{_.startsWith("$")&&(ot[_]=z[_]);}),Et.push(ot);return}let X={...j,[G[V]]:z[G[V]],...rt(j),...at};yt(V+1,X),yt(V+1,j);};return yt(0,{...rt(z)}),Et})(Q).filter(z=>!(z.$op==="update"&&Object.keys(z).filter(tt=>!tt.startsWith("$")).length===0)),x=[],v=e(Q.$objectPath),W=h[v]?h[v].$ids:[],C=N.map((z,tt)=>{let at=D(a,z),G=Object.keys(z).filter(j=>!j.includes("$")&&!at.dataFields?.some(X=>X.path===j)).map(j=>(Array.isArray(z[j])?z[j].length>1?z[j].filter(_=>!_.$id||Array.isArray(_.$id)||_.$filter):z[j]:[z[j]]).map(_=>{let Lt=e(_.$objectPath);return {idsToKey:(Qt=>{let xt=[],ct=Qt.split("."),ve=ct.slice(0,ct.length-1).join("."),ze=ct.slice(ct.length-1,ct.length)[0].split("___")[1];for(let Mt in h)if(Mt.startsWith(ve)&&Mt.endsWith(ze)){let St=Mt.split("."),Ve=St.slice(St.length-1,St.length)[0].split("___")[0];xt.push(Ve);}return xt})(Lt),key:j,multiple:_}})).filter(j=>j!==void 0),V=(j=>{let X=j.map(_=>_.map(et=>et.idsToKey));return (_=>_.length>0?_.reduce((et,dt)=>et.concat(dt),[]).reduce((et,dt)=>et?dt.filter(Qt=>et.includes(Qt)):dt):[])(X)})(G).filter(j=>!x.includes(j));if(x=[...x,...V],W=W.filter(j=>!V.includes(j)),tt===N.length-1&&W.length>0)return {...z,$id:W,$bzId:`T_${uuid.v4()}`,...rt(z)};if(V.length>0)return {...z,$id:V,$bzId:`T_${uuid.v4()}`,...rt(z)}}).filter(z=>z!==void 0),xe=(()=>{if(C.length===0&&!q?.$id)return P;if(C.length===0&&q?.$id){let z=Array.isArray(q.$id)?q.$id:[q.$id],tt=[];return z.forEach(at=>{let lt=e({...Q.$objectPath,ids:at}),G=h[lt];G&&tt.push({...Q,$id:G.$ids,...rt(Q),$bzId:`T_${uuid.v4()}`});}),tt}else return C})();g=[...L,...xe].map(M);}):g=S.map(M),g},M=m=>{let q={...m,$bzId:`T_${uuid.v4()}`,...rt(m)},S=D(a,m);return Object.keys(m).filter(g=>!g.includes("$")&&!S.dataFields?.some(L=>L.path===g)).forEach(g=>{let L=Array.isArray(m[g])?m[g]:[m[g]],P=k(L,m);q[g]=P.length>0?P:void 0;}),q},f=[];return B.forEach(m=>{f=[...f,...k([m])];}),f.map(m=>M(m))})(Array.isArray(n)?n:[n]),t=B=>B.map(k=>{let M=w(k,!0),f={...k};return M.forEach($=>{let m=Array.isArray(k[$])?k[$]:[k[$]],q=[],S=[],g=[],L={},P=Rt(a,k,$);m.filter(C=>C).forEach(C=>{C.$op==="replace"&&C.$id?(L=C,Array.isArray(C.$id)?S=[...S,...C.$id]:S.push(C.$id)):C.$op==="create"&&P==="ONE"&&C.id?(L=C,Array.isArray(C.id)?g=[...S,...C.id]:g.push(C.id)):q.push(C);});let Q=e(L.$objectPath),N=s(Q).map(C=>h[C]),x=[];N.filter(C=>C!=null).forEach(C=>{x=[...x,...C.$ids];});let v=x.filter(C=>!S.includes(C)),Y=S.filter(C=>!x.includes(C)),W=rt(L);v.length>0&&q.push({...L,$op:"unlink",$id:v,$bzId:`T_${uuid.v4()}`,id:void 0,...W}),Y.length>0&&Y.forEach(C=>{q.push({...L,$op:"link",$id:C,$bzId:`T_${uuid.v4()}`,...W});}),g.length>0&&g.forEach(C=>{q.push({...L,$op:"create",id:C,$bzId:`T_${uuid.v4()}`,...W});}),f[$]=t(q);}),f}),R=u(t(u(i)));(B=>immer.produce(B,k=>objectTraversal.traverse(k,M=>{let{key:f,value:$,parent:m}=M;f&&m&&!f?.includes("$")&&(Array.isArray($)||radash.isObject($))&&!Array.isArray(m)&&(Array.isArray($)?$:[$]).forEach(S=>{let g=h[e(S.$objectPath)],L=(I,N)=>I.every(x=>N.includes(x)),P=S.$id?Array.isArray(S.$id)?L(S.$id,g?g.$ids:[]):g?.$ids.includes(S.$id):g,Q=Rt(a,m,S.$objectPath.key);if(S.$op==="link"&&P&&Q==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${e(S.$objectPath)}" because it is already occupied.`);if(S.$op)switch(S.$op){case"delete":if(!P&&!d.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${S.$id}" because it is not linked to $id:"${m.$id}"`);break;case"update":if(!P&&!d.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${S.$id}" because it is not linked to $id:"${m.$id}"`);break;case"unlink":if(!P&&!d.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${S.$id}" because it is not linked to $id:"${m.$id}"`);break;case"link":if(P)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${S.$id}" because it is already linked to $id:"${m.$id}"`);break;}});})))(R);let O=(B=>immer.produce(B,k=>objectTraversal.traverse(k,M=>{let{parent:f,key:$,value:m,meta:q}=M;radash.isObject(m)&&(m[Symbol.for("path")]=q.nodePath,delete m.$objectPath,delete m.$parentIsCreate),$&&f&&!$?.includes("$")&&(Array.isArray(m)||radash.isObject(m))&&!Array.isArray(f)&&(Array.isArray(m)?m:[m]).forEach(g=>{radash.isObject(g)&&(g[Symbol.for("parent")]={...m[Symbol.for("parent")],path:f[Symbol.for("path")]});});})))(R);l.filledBqlRequest=O;};var Fe=async l=>{let{filledBqlRequest:o,schema:d}=l;if(!o)throw new Error("Filled BQL request is missing");let w=(b=>immer.produce(b,E=>objectTraversal.traverse(E,({value:A})=>{if(radash.isObject(A)){let e=A,s=D(d,e),{unidentifiedFields:h}=J(s,e),{idFields:r,computedFields:u,virtualFields:n}=s;if(!r)throw new Error("No idFields found");let[c]=r,i=radash.listify(e,(F,T)=>T!==void 0?F:void 0),t=i.filter(F=>n?.includes(F));if(t.length>0)throw new Error(`Virtual fields can't be sent to DB: "${t.join(",")}"`);if(u.filter(F=>!i.includes(F)).forEach(F=>{let T=s.dataFields?.find(f=>f.path===F),B=s.linkFields?.find(f=>f.path===F)?.oppositeLinkFieldsPlayedBy[0],k="roles"in s?ft(s.roles,(f,$)=>f===F):void 0,M=T||B||k;if(!M)throw new Error(`no field Def for ${F}`);if(F!==c&&e.$op==="create"&&!e[F]){let f=Z({currentThing:e,fieldSchema:M,mandatoryDependencies:!0});e[F]=f;}}),h.length>0)throw new Error(`Unknown fields: [${h.join(",")}] in ${JSON.stringify(e)}`)}})))(o),y=(b=>immer.produce(b,E=>objectTraversal.traverse(E,({value:A})=>{radash.isObject(A);})))(w);l.filledBqlRequest=y;};var Qe=async l=>{let{filledBqlRequest:o}=l;if(!o)throw new Error("Filled BQL request is missing");let a=(y=>immer.produce(y,b=>objectTraversal.traverse(b,({value:E})=>{radash.isObject(E)&&Jt();})))(o),p=(y=>immer.produce(y,b=>objectTraversal.traverse(b,({value:E})=>{radash.isObject(E);})))(a);l.filledBqlRequest=p;};var ke=async l=>{let{filledBqlRequest:o}=l;if(!o)throw new Error("Filled BQL request is missing");let d=w=>immer.produce(w,p=>objectTraversal.traverse(p,({value:y})=>{if(radash.isObject(y)&&("$entity"in y||"$relation"in y)){let b=y,{requiredFields:E,enumFields:A,fnValidatedFields:e}=b[bt];"$op"in b&&b.$op==="create"&&E.forEach(s=>{if(!(s in b))throw new Error(`[Validations] Required field "${s}" is missing.`)}),("$op"in b&&b.$op==="update"||b.$op==="create")&&A.forEach(s=>{if(s in b){let h=b[bt]?.dataFields?.find(r=>r.path===s)?.validations?.enum;if(!h)throw new Error(`[Validations] Enum field "${s}" is missing enum options.`);if(radash.isArray(b[s]))b[s].some(r=>{if(!h.includes(r))throw new Error(`[Validations] Option "${r}" is not a valid option for field "${s}".`)});else if(h&&!h.includes(b[s]))throw new Error(`[Validations] Option "${b[s]}" is not a valid option for field "${s}".`)}}),("$op"in b&&b.$op==="update"||b.$op==="create")&&e.forEach(s=>{if(s in b)try{let h=b[bt]?.dataFields?.find(r=>r.path===s)?.validations?.fn;if(!h)throw new Error("Missing validation function.");if(!h(b[s]))throw new Error("Failed validation function.")}catch(h){throw new Error(`[Validations:attribute:${s}] ${h.message}`)}});}})),a=w=>immer.produce(w,p=>objectTraversal.traverse(p,({value:y})=>{if(radash.isObject(y)&&("$entity"in y||"$relation"in y)){let b="$entity"in y?y.$entity:y.$relation,E=y,A=y[Symbol.for("schema")].hooks;if(A){let{pre:e}=A;if(e){let s=`on${Ht(E.$op)}`;e.filter(r=>r.triggers[s]).forEach(r=>{let u=s in r.triggers?r.triggers[s]:void 0;u!==void 0&&u()&&r.actions.forEach(n=>{if(n.type==="validate"){if(n.severity!=="error")return;try{let c=n.fn(E);if(c===!1)throw new Error(`${n.message}.`);if(c!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(c){throw new Error(`[Validations:thing:${b}] ${c.message}`)}}});});}}}}));d(o),a(o);};var Re=async(l,o)=>{let{schema:d,enrichedBqlQuery:a}=l,{bqlRes:w}=o;if(!w)return;let y=(b=>immer.produce(b,E=>objectTraversal.traverse(E,({value:A})=>{if(radash.isObject(A)){let e=A;if(!e.$thing)throw new Error("[Internal] Thing is missing");if(e.$thing){let s=D(d,e),{virtualFields:h}=s,r=e[K];if(!r)throw new Error("[Internal] QueryPath is missing");let u=objectTraversal.getNodeByPath(a,r),n=u.$fields.map(i=>i.$path),c=u.$excludedFields;h.forEach(i=>{if(c?.includes(i)||n.length>0&&!n.includes(i))return;let t=s.dataFields?.find(F=>F.path===i),R=Z({currentThing:e,fieldSchema:t,mandatoryDependencies:!0});e[i]=R;}),c&&c.forEach(i=>{if(typeof i!="string")throw new Error("[Internal] ExcludedField is not a string");delete e[i];});}}})))(w);o.bqlRes=y;};var Oe=async(l,o)=>{let{config:d}=l,{bqlRes:a}=o;if(!a)return;let p=(E=>immer.produce(E,A=>objectTraversal.traverse(A,({value:e})=>{radash.isObject(e);})))(a),b=(E=>immer.produce(E,A=>objectTraversal.traverse(A,({value:e})=>{if(radash.isObject(e)){let s=e;Object.keys(s).forEach(h=>{s[h]===void 0&&delete s[h];}),Object.getOwnPropertySymbols(s).forEach(h=>{delete s[h];}),d.query?.noMetadata===!0&&Object.keys(s).forEach(h=>{h.startsWith("$")&&delete s[h];});}})))(p);o.bqlRes=b;};var Ie={query:[ue,ce,ye,$e,Re,Oe],mutation:[re,me,Fe,Qe,ke,le,ie,de,Ut,ee]},jt=async(l,o,d={},a=!0)=>{for(let w of l){let p=await w(o,d);if(p&&Array.isArray(p))for(let y of p)await jt(y.pipeline,y.req,y.res,!1);}return a&&o.config.query?.debugger===!0&&typeof d.bqlRes=="object"?{...d.bqlRes,$debugger:{tqlRequest:o.tqlRequest}}:d.bqlRes},Ft=(l,o,d,a)=>jt(Ie.query,{config:o,schema:d,rawBqlRequest:l,dbHandles:a},{}),Ce=(l,o,d,a)=>jt(Ie.mutation,{config:o,schema:d,rawBqlRequest:l,dbHandles:a},{});var Dt=class{schema;config;dbHandles;constructor({schema:o,config:d}){this.schema=o,this.config=d;}init=async()=>{let o={typeDB:new Map},d=Wt(this.schema);await Promise.all(this.config.dbConnectors.map(async a=>{if(a.provider==="typeDB"&&a.dbName){let[w,p]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(a.url);if(w){let y=`[BORM:${a.provider}:${a.dbName}:core] ${w.message??"Can't create TypeDB Client"}`;throw new Error(y)}try{let y=await p.session(a.dbName,typedbDriver.SessionType.DATA);o.typeDB.set(a.id,{client:p,session:y});}catch(y){let b=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(b)}}if(a.provider==="typeDBCluster"&&a.dbName){let[w,p]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(a.addresses,a.credentials);if(w){let y=`[BORM:${a.provider}:${a.dbName}:core] ${w.message??"Can't create TypeDB Cluster Client"}`;throw new Error(y)}try{let y=await p.session(a.dbName,typedbDriver.SessionType.DATA);o.typeDB.set(a.id,{client:p,session:y});}catch(y){let b=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(b)}}})),this.schema=d,this.dbHandles=o;};#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(),zt(this.config,this.schema,this.dbHandles));query=async(o,d)=>{await this.#t();let a={...this.config,query:{...Tt.query,...this.config.query,...d}};return Ft(o,a,this.schema,this.dbHandles)};mutate=async(o,d)=>{await this.#t();let a={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...d}};return Ce(o,a,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:o,session:d})=>{console.log("Closing session"),await d.close(),console.log("Closing client"),await o.close();});}},Gr=Dt;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
34
|
+
${c}`})(),f=d.dbConnectors[0].id,y=l.typeDB.get(f)?.session,B=l.typeDB.get(f)?.client;if(!y){console.log("Session Status: ","NO SESSION");return}await y.close();let[{dbName:M}]=d.dbConnectors;await(await B.databases.get(M)).delete(),await B.databases.create(M);let e=await B.session(d.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),s=await e.transaction(typedbDriver.TransactionType.WRITE);await s.query.define(F),await s.commit(),await s.close();let u=await e.transaction(typedbDriver.TransactionType.READ);(await(await u.query.match("match $a sub thing;")).collect()).forEach(async c=>{c.get("a");}),await u.close();};var ve=(d,r,l)=>l?r:`${d}\xB7${r}`;var pe=(d,r)=>Object.values(Object.fromEntries(Object.entries(d).filter(([l,a])=>r(l,a))))[0],ce=(d,r)=>Object.fromEntries(Object.entries(d).filter(([l,a])=>r(l,a))),ze=d=>{let r=[],l=immer.produce(d,F=>objectTraversal.traverse(F,({key:f,value:y,meta:B})=>{if(B.depth===2&&(f&&(y.dataFields=y.dataFields?.map(M=>({...M,cardinality:M.cardinality||"ONE",dbPath:ve(f,M.path,M.shared)}))),y.extends)){let M=F.entities[y.extends]||F.relations[y.extends];if(y.allExtends=[y.extends,...M.allExtends||[]],y.idFields=M.idFields?(y.idFields||[]).concat(M.idFields):y.idFields,y.dataFields=M.dataFields?(y.dataFields||[]).concat(M.dataFields.map(R=>{let e=y.extends,s=d.entities[e]||d.relations[e];for(;!s.dataFields?.find(u=>u.path===R.path);)e=s.extends,s=d.entities[e]||d.relations[e];return {...R,dbPath:ve(e,R.path,R.shared)}})):y.dataFields,y.linkFields=M.linkFields?(y.linkFields||[]).concat(M.linkFields):y.linkFields,"roles"in M){let R=y,e=M;R.roles=R.roles||{},R.roles={...R.roles,...e.roles},Object.keys(R.roles).length===0&&(R.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(d,({key:F,value:f,meta:y})=>{if(F==="linkFields"){let M=(()=>{if(!y.nodePath)throw new Error("No path");let[e,s]=y.nodePath.split(".");return {thing:s,thingType:e==="entities"?"entity":e==="relations"?"relation":""}})(),R=Array.isArray(f)?f.map(e=>({...e,...M})):[{...f,...M}];r.push(...R);}}),immer.produce(l,F=>objectTraversal.traverse(F,({value:f,key:y,meta:B})=>{if(B.depth===2&&f.idFields&&!f.id){f.name=y;let M=()=>{if(B.nodePath?.split(".")[0]==="entities")return "entity";if(B.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};f.thingType=M(),f.computedFields=[],f.virtualFields=[],f.requiredFields=[],f.enumFields=[],f.fnValidatedFields=[],"roles"in f&&Object.entries(f.roles).forEach(([e,s])=>{s.playedBy=r.filter(u=>u.relation===y&&u.plays===e)||[],s.name=e;}),"linkFields"in f&&f.linkFields&&f.linkFields?.forEach(e=>{if(e.target==="relation"){e.oppositeLinkFieldsPlayedBy=[{plays:e.path,thing:e.relation,thingType:"relation"}];return}let s=r.filter(n=>n.relation===e.relation&&n.plays!==e.plays)||[];e.oppositeLinkFieldsPlayedBy=s;let{filter:u}=e;e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>n.target==="role"),u&&Array.isArray(u)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>u.some(p=>n.thing===p.$role)),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>u.some(p=>n.thing===p.$thing))),u&&!Array.isArray(u)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>n.$role===u.$role),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>n.thing===u.$thing));});}if(typeof f=="object"&&"playedBy"in f){if([...new Set(f.playedBy?.map(M=>M.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${y} path:${B.nodePath}`);if(f.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${y}, path:${B.nodePath}`)}if(B.depth===4){let[M,R]=B.nodePath?.split(".")||[],e=F[M][R];f.validations&&(f.validations.required&&e.requiredFields.push(f.path),f.validations.enum&&e.enumFields.push(f.path),f.validations.fn&&e.fnValidatedFields.push(f.path)),f.default?f.isVirtual?e.virtualFields.push(f.path):e.computedFields.push(f.path):f.isVirtual&&e.virtualFields.push(f.path);}}))},Se=(d,r,l)=>{let a=N(d,r),F=a.linkFields?.find(B=>B.path===l);if(F)return F.cardinality;let f=a.dataFields?.find(B=>B.path===l);if(f)return f.cardinality;let y=a.roles[l];if(y)return y.cardinality},N=(d,r)=>{if(r.$thing){if(!r.$thingType)throw new Error("Missing $thingType in node$: {JSON.stringify(node, null, 2)");if(r.$thingType==="entity"){if(!(r.$thing in d.entities))throw new Error(`Missing entity '${r.$thing}' in the schema`);return d.entities[r.$thing]}if(r.$thingType==="relation"){if(!(r.$thing in d.relations))throw new Error(`Missing relation '${r.$thing}' in the schema`);return d.relations[r.$thing]}throw new Error(`Wrong schema or query for ${JSON.stringify(r,null,2)}`)}if(r.$entity){if(!(r.$entity in d.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return d.entities[r.$entity]}if(r.$relation){if(!(r.$relation in d.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return d.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r,null,2)}`)},G=(d,r)=>{let l=d.dataFields?.map(p=>p.path)||[],a=d.linkFields?.map(p=>p.path)||[],F="roles"in d?radash.listify(d.roles,p=>p):[],f=[...l||[],...a||[],...F||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...f];if(!r)return {fields:f,dataFields:l,roleFields:F,linkFields:a};let M=r.$fields?r.$fields.map(p=>{if(typeof p=="string")return p;if("$path"in p&&typeof p.$path=="string")return p.$path;throw new Error(" Wrongly structured query")}):radash.listify(r,p=>p),R=r.$filter?radash.listify(r.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&l?.includes(p)):[],e=r.$filter?radash.listify(r.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&[...F||[],...a||[]].includes(p)):[],s=[...M,...R].filter(p=>!B.includes(p)).filter(p=>p),u=r.$filter?ce(r.$filter,(p,i)=>R.includes(p)):{},n=r.$filter?ce(r.$filter,(p,i)=>e.includes(p)):{};return {fields:f,dataFields:l,roleFields:F,linkFields:a,usedFields:M,usedLinkFields:a.filter(p=>M.includes(p)),usedRoleFields:F.filter(p=>M.includes(p)),unidentifiedFields:s,...R.length?{localFilters:u}:{},...e.length?{nestedFilters:n}:{}}};var _e=d=>{if(typeof d!="string")throw new Error("capitalizeFirstLetter: string is not a string");return d.charAt(0).toUpperCase()+d.slice(1).toLowerCase()},Ve=(d,r,l)=>{let F=(l.nodePath||"").split("."),f=radash.isArray(r)?F.slice(0,-2).join("."):F.slice(0,-1).join(".");return r?objectTraversal.getNodeByPath(d,f):{}};var We=async(d,r)=>{let{bqlRequest:l,config:a,tqlRequest:F}=d,{rawTqlRes:f}=r;if(l){if(!f)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:y}=l;if(!y){if(f.insertions?.length===0&&!F?.deletions){r.bqlRes={};return}let{mutation:B}=l;if(!B)throw new Error("TQL mutation not executed");let R=[...B.things,...B.edges].map(e=>{let s=f.insertions?.find(u=>u.get(`${e.$bzId}`))?.get(`${e.$bzId}`);if(e.$op==="create"||e.$op==="update"||e.$op==="link"){let u=s?.asThing().iid;return a.mutation?.noMetadata?radash.mapEntries(e,(n,p)=>[n.toString().startsWith("$")?Symbol.for(n):n,p]):{$dbId:u,...e,[e.path]:e.$id}}if(e.$op==="delete"||e.$op==="unlink")return e;if(e.$op!=="match")throw new Error(`Unsupported op ${e.$op}`)}).filter(e=>e);r.bqlRes=R;return}};var Vt=(d,r)=>immer.produce(d,l=>objectTraversal.traverse(l,({value:a})=>{if(Array.isArray(a)||typeof a!="object"||a===null)return;a.$tempId&&(a.$tempId=`_:${a.$tempId}`),a.$fields&&delete a.$fields,a.$filter&&delete a.$filter,a.$show&&delete a.$show,a.$bzId&&delete a.$bzId,r.query?.noMetadata&&(a.$entity||a.$relation)&&(delete a.$entity,delete a.$relation,delete a.$id),Object.getOwnPropertySymbols(a).forEach(f=>{delete a[f];}),a.$excludedFields&&(a.$excludedFields.forEach(f=>{delete a[f];}),delete a.$excludedFields);})),Wt=(d,r)=>{let l={};return r.forEach(a=>{l[a.$bzId]=a.$id;}),d.forEach(a=>{Object.keys(a).forEach(F=>{l[a[F]]&&F!=="$tempId"&&(a[F]=l[a[F]]);});}),d},Ht=(d,r)=>{let l=r.map(F=>F.$bzId),a=!1;return d.forEach(F=>{Object.keys(F).forEach(f=>{l.includes(F[f])&&(a=!0);});}),a},He=async(d,r)=>{let{bqlRequest:l,config:a}=d;if(!l)throw new Error("BQL request not parsed");let F=r.bqlRes[0]?r.bqlRes:[r.bqlRes],f=d.bqlRequest?.mutation?.things;if(Ht(F,f)){let M=Wt(F,f);r.bqlRes=M[1]?M:M[0];}let B=Vt(r.bqlRes,a);r.bqlRes=B;};var Ue=async d=>{let{bqlRequest:r,schema:l}=d;if(!r)throw new Error("BQL request not parsed");let{mutation:a}=r;if(!a)throw new Error("BQL request is not a mutation");let F=n=>{let p=n.$op,i=`$${n.$bzId}`,c=N(l,n),{idFields:t,defaultDBConnector:o}=c,P=o?.path||n.$entity||n.$relation,w=n.$id,k=t?.[0],q=radash.listify(n,(m,Q)=>{if(m.startsWith("$")||m===k||Q===void 0||Q===null)return "";let I=c.dataFields?.find(D=>D.path===m);if(!I?.path)return "";let j=I.dbPath;if(["TEXT","ID","EMAIL"].includes(I.contentType))return `has ${j} '${Q}'`;if(["NUMBER","BOOLEAN"].includes(I.contentType))return `has ${j} ${Q}`;if(I.contentType==="DATE"){if(Number.isNaN(Q.valueOf()))throw new Error("Invalid format, Nan Date");return Q instanceof Date?`has ${j} ${Q.toISOString().replace("Z","")}`:`has ${j} ${new Date(Q).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${I.contentType}`)}).filter(m=>m),b=`${i}-atts`,T=radash.listify(n,m=>{if(m.startsWith("$")||m===k)return "";let Q=c.dataFields?.find(j=>j.path===m);if(!Q?.path)return "";let O=Q.dbPath;return `{${b} isa ${O};}`}).filter(m=>m),L=n[Symbol.for("isLocalId")],h=radash.isArray(w)?`like '${w.join("|")}'`:`'${w}'`,S=!L&&w?[`has ${k} ${h}`]:[],$=[...S,...q].filter(m=>m).join(","),E=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${i} isa ${[P,...S].filter(m=>m).join(",")};`;if(p==="update"){if(!T.length)throw new Error("update without attributes");return `${i} isa ${[P,...S].filter(m=>m).join(",")}, has ${b};
|
|
35
|
+
${T.join(" or ")};`}return ""},g=()=>p==="update"||p==="link"||p==="match"?`${i} isa ${[P,...S].filter(m=>m).join(",")};`:"";if(n.$entity||n.$relation)return {op:p,deletionMatch:E(),insertionMatch:g(),insertion:p==="create"?`${i} isa ${[P,$].filter(m=>m).join(",")};`:p==="update"&&q.length?`${i} ${q.join(",")};`:"",deletion:p==="delete"?`${i} isa ${P};`:p==="update"&&T.length?`${i} has ${b};`:""};throw new Error("in attributes")},f=n=>{let p=n.$op,i=N(l,n),c=`$${n.$bzId}`,t=n.$id,o=i.defaultDBConnector?.path||n.$relation,P="roles"in i?radash.listify(i.roles,m=>m):[],w=n.$relation&&"roles"in i&&radash.mapEntries(i.roles,(m,Q)=>[m,Q.dbConnector?.path||m]),k=radash.listify(n,(m,Q)=>{if(!P.includes(m))return null;if(!("roles"in i))throw new Error("This should have roles! ");let I=w[m];return Array.isArray(Q)?Q.map(O=>({path:I,id:O})):{path:I,id:Q}}).filter(m=>m).flat(),q=k.map(m=>{if(!m?.path)throw new Error("Object without path");return `${m.path}: $${m.id}`}),b=k.length>0?`( ${q.join(" , ")} )`:"",T=n[Symbol.for("edgeType")];if(!T)throw new Error("[internal error] Symbol edgeType not defined");let L=b?`${c} ${b} ${T==="linkField"||p==="delete"||p==="unlink"?`isa ${o}`:""}`:"",h=`${c} ${T==="linkField"||p==="delete"?`isa ${o}`:""}`,S=()=>L?p==="link"?`${L};`:p==="create"?`${L}, has id '${t}';`:"":"",$=()=>L&&p==="match"?`${L};`:"",E=()=>L?p==="delete"?`${L};`:p==="match"?`${L};`:"":"",g=()=>L?p==="delete"?`${h};`:p==="unlink"?`${c} ${b};`:"":"";return {deletionMatch:E(),insertionMatch:$(),deletion:g(),insertion:S(),op:""}},y=(n,p)=>{let i=p==="edges"?f:F;if(Array.isArray(n))return n.map(k=>{let{preDeletionBatch:q,insertionMatch:b,deletionMatch:T,insertion:L,deletion:h}=i(k);return radash.shake({preDeletionBatch:q,insertionMatch:b,deletionMatch:T,insertion:L,deletion:h},S=>!S)}).filter(k=>k);let{preDeletionBatch:c,insertionMatch:t,deletionMatch:o,insertion:P,deletion:w}=i(n);return radash.shake({preDeletionBatch:c,insertionMatch:t,deletionMatch:o,insertion:P,deletion:w},k=>!k)},B=y(a.things),M=Array.isArray(B)?B:[B],R=y(a.edges,"edges"),e=Array.isArray(R)?R:[R],s=[...M,...e],u=radash.shake({insertionMatches:s.map(n=>n.insertionMatch).join(" ").trim(),deletionMatches:s.map(n=>n.deletionMatch).join(" ").trim(),insertions:s.map(n=>n.insertion).join(" ").trim(),deletions:s.map(n=>n.deletion).join(" ").trim()},n=>!n);d.tqlRequest=u;};var Jt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Zt=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Ke=d=>{let l=d.toString().replace(Jt,"").trim().split("=>")[0].split("{")[0].replace(Zt,"").trim(),a=l.substring(l.indexOf("(")+1,l.lastIndexOf(")")).trim();return a?(a.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(f=>f.includes("{")&&f.includes("}")?(f.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):f.trim()).filter(Boolean):[]};var X=({currentThing:d,fieldSchema:r,mandatoryDependencies:l=!1})=>{if(!r||!r.default||!("fn"in r.default||"value"in r.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(r,null,3)}`);if(r.default.type==="value")return r.default.value;if(l){let{fn:F}=r.default,y=Ke(F).filter(B=>!(B in d));if(y.length)throw new Error(`Virtual field: Missing arguments ${y.join(", ")}`)}return "default"in r?r.default?.fn(d):void 0},Je=()=>{};var ti=d=>{if(!d.startsWith("_:"))throw new Error("ID must start with '_:'.");let r=d.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(r))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(d.length>36)throw new Error("$tempId must not be longer than 36 characters.");return r},Ye=async d=>{let{rawBqlRequest:r,schema:l}=d,F=(s=>immer.produce(s,u=>objectTraversal.traverse(u,({value:n,key:p,parent:i})=>{if(radash.isObject(n)&&(n=radash.shake(n,c=>c===void 0)),p==="$tempId"&&(i[p]=ti(n)),i&&radash.isArray(n)){if(!n.some(t=>typeof t=="object"&&"$id"in t))return;let c=n.flatMap(t=>typeof t=="string"?t:typeof t=="object"&&"$id"in t&&radash.isArray(t.$id)?t.$id.map(o=>({...t,$id:o})):t);i[p]=c;}})))(r),y=(s=>immer.produce(s,u=>objectTraversal.traverse(u,({value:n,meta:p,key:i})=>{if(radash.isObject(n)){if(n.$arrayOp)throw new Error("Array op not supported yet");if(i==="$filter"||p.nodePath?.includes(".$filter."))return;let c=n;if(c.$op==="create"&&c.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let t=N(l,c),P=Object.keys(c).filter($=>t.virtualFields?.includes($));if(P.length>0){let $=P.filter(E=>c[E]);if($.length>0)throw new Error(`Can't set virtual fields: ["${$.join('","')}"]`)}let k=p.nodePath?.split(".")?.filter($=>Number.isNaN(parseInt($,10))).join(".");if(!t)throw new Error(`Schema not found for ${c.$entity||c.$relation}`);c.$bzId=c.$tempId??`T_${uuid.v4()}`,c[Symbol.for("schema")]=t,c[Symbol.for("dbId")]=t.defaultDBConnector.id;let{usedLinkFields:q,usedRoleFields:b}=G(t,c),T=q.map($=>({fieldType:"linkField",path:$,schema:t.linkFields.find(E=>E.path===$)})),L=t.thingType==="relation"?b.map($=>({fieldType:"roleField",path:$,schema:pe(t.roles,E=>E===$)})):[];if(T.some($=>$.schema?.target==="role")&&T.some($=>$.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let h=L.filter($=>[...new Set($.schema.playedBy?.map(E=>E.thing))].length!==1);if(h.length>1)throw new Error(`Field: ${h[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(h[0].schema.playedBy)}. Schema: ${JSON.stringify(h[0].schema)}`);let S=p.nodePath;if([...T,...L].forEach($=>{let E=c[$.path];if(E===void 0)return;let g=$.schema;if(!g)throw new Error(`Field ${$.path} not found in schema`);let m=$.fieldType==="roleField"?g?.playedBy[0]:g,I=g&&"relation"in g&&m?.relation===c.$relation?"$self":m?.relation?m?.relation:"$self",O=I==="$self"?t:l.relations[I];if(pe(O.roles,(v,A)=>v===$.path)?.playedBy?.length===0)throw new Error(`unused role: ${S}.${$.path}`);if(!g)throw new Error(`Field ${$.path} not found in schema`);let D=$.fieldType==="linkField"?g?.oppositeLinkFieldsPlayedBy:g?.playedBy;if(!D)throw new Error(`No opposite fields found for ${JSON.stringify(g)}`);if([...new Set(D?.map(v=>v.thing))].length>1)throw new Error(`Field: ${$.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(D)}. Schema: ${JSON.stringify(g)}`);if(g.cardinality==="ONE"&&Array.isArray(E))throw new Error("Can't have an array in a cardinality === ONE link field");if(g.cardinality==="MANY"&&E!==null&&!Array.isArray(E)&&!E.$arrayOp)throw new Error(`${$.fieldType==="linkField"?g.path:g.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(E?.$entity||E?.$relation)return;let[z]=D,J="plays"in g?"linkField":"roleField",K={[`$${z.thingType}`]:z.thing,[Symbol.for("relation")]:I,[Symbol.for("edgeType")]:J,[Symbol.for("parent")]:{path:S,...c.$id?{$id:c.$id}:{},...c.$tempId?{$tempId:c.$tempId}:{},...c.filter?{filter:c.filter}:{},links:D},[Symbol.for("role")]:z.plays,[Symbol.for("oppositeRole")]:"plays"in g?g.plays:void 0,[Symbol.for("relFieldSchema")]:g};if(radash.isObject(E)&&(c[$.path]={...K,...E}),Array.isArray(E))if(E.every(v=>radash.isObject(v)))c[$.path]=E.map(v=>({...K,...v}));else if(E.every(v=>typeof v=="string"))c[$.path]=E.map(v=>({...K,$op:c.$op==="create"?"link":"replace",$id:v}));else throw new Error(`Invalid array value for ${$.path}`);if(typeof E=="string"&&(c[$.path]={...K,$op:c.$op==="create"?"link":"replace",$id:E}),E===null){let v={...K,$op:"unlink"};c[$.path]=g.cardinality==="MANY"?[v]:v;}}),!k&&!c.$entity&&!c.$relation)throw new Error("Root things must specify $entity or $relation")}})))(F),M=(s=>immer.produce(s,u=>objectTraversal.traverse(u,({parent:n,key:p,value:i,meta:c})=>{if(radash.isObject(i)){if(Object.keys(i).length===0)throw new Error("Empty object!");if(p==="$filter"||c.nodePath?.includes(".$filter."))return;let t=i,o=c.nodePath?.split(".");if(t.$tempId&&!(t.$op===void 0||t.$op==="link"||t.$op==="create"||t.$op==="update"))throw new Error(`Invalid op ${t.$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.`);let P=o?.filter(I=>Number.isNaN(parseInt(I,10))).join("."),w=P?Array.isArray(n)?o?.slice(0,-1).join("."):c.nodePath:c.nodePath||"",k=N(l,t),{dataFields:q,roleFields:b,linkFields:T}=G(k,t),L=immer.current(t)[Symbol.for("parent")],h=P&&L.path,$=(h?objectTraversal.getNodeByPath(u,h):u)?.$op;if(P&&!$)throw new Error("Error: Parent $op not detected");let E=t[Symbol.for("relFieldSchema")];t.$op==="replace"&&$==="create"&&(t.$op="link");let g=Object.keys(t).some(I=>q?.includes(I)),m=Object.keys(t).some(I=>[...b,...T].includes(I)),Q=()=>{if(t.$op)return t.$op;if(P&&!t.$id&&!t.$tempId&&$!=="create"&&E.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${c.nodePath}`);if(t.$tempId)return "create";if((t.$id||t.$filter)&&g)return "update";if((t.$id||t.$filter)&&P&&!g&&!m)return "link";if(!t.$filter&&!t.$id&&!t.$tempId)return "create";if((t.$id||t.$filter)&&!g&&m)return "match";throw new Error("Wrong op")};if(t.$op||(t.$op=Q()),n||(t.$parentKey=""),typeof n=="object"&&(Array.isArray(n)&&(t[Symbol.for("index")]=p),t[Symbol.for("path")]=w,t[Symbol.for("isRoot")]=!P,t[Symbol.for("depth")]=P?.split(".").length),!t.$entity&&!t.$relation)throw new Error(`Node ${JSON.stringify(t)} without $entity/$relation`)}})))(y),e=(s=>immer.produce(s,u=>objectTraversal.traverse(u,({value:n})=>{if(radash.isObject(n)){let p=n,i=N(l,p),{unidentifiedFields:c}=G(i,p),{idFields:t}=i;if(!t)throw new Error("No idFields found");let[o]=t;if(p.$op==="create"&&!p[o]){let P=i.dataFields?.find(k=>k.path===o),w=X({currentThing:p,fieldSchema:P,mandatoryDependencies:!0});if(typeof w!="string")throw new Error(`Default id field ${o} is not a string`);p[o]=w,p.$id=w;}if(c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(p)}`)}})))(M);d.filledBqlRequest=e;};var tt=async d=>{let{filledBqlRequest:r,schema:l}=d,a=e=>{let s=[],u=[],n=t=>{if(t.$id)return t.$id;let o=N(l,t),{idFields:P}=o;if(!P)throw new Error(`no idFields: ${JSON.stringify(t)}`);let[w]=P;if(!w)throw new Error(`no idField: ${JSON.stringify(t)}`);let k=o.dataFields?.find(T=>T.path===w),q=X({currentThing:t,fieldSchema:k,mandatoryDependencies:!0}),b=t[w]||t.$id||q;if(!b)throw new Error(`no idValue: ${JSON.stringify(t)}`);return b},p=t=>{if(t.$op==="create"){let o=n(t);if(s.find(P=>P.$id===o))throw new Error(`Duplicate id ${o} for node ${JSON.stringify(t)}`);if(u.find(P=>P.$bzId===t.$bzId))throw new Error(`Duplicate $bzid ${t.$bzId} for node ${JSON.stringify(t)}`);s.push({...t,$id:o});return}t.$tempId&&t.$op==="match"||s.push(t);},i=t=>{if(t.$op==="create"){let o=n(t);if(s.find(P=>P.$id===o),u.find(P=>P.$bzId===t.$bzId))throw new Error(`Duplicate %bzId ${t.$bzIdd} for edge ${JSON.stringify(t)}`);u.push({...t,$id:o});return}u.push(t);};return objectTraversal.traverse(e,({value:t})=>{if(!radash.isObject(t))return;let o=t;if(o.$entity||o.$relation){if(!o.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(o)}`);if(!o.$bzId)throw new Error("[internal error] BzId not found");let P=N(l,o),{dataFields:w,roleFields:k,linkFields:q,usedFields:b}=G(P,o),T=()=>{if(o.$op==="create"||o.$op==="delete")return o.$op;if(o.$op==="update"){let h=b.filter(E=>w?.includes(E)),S=b.filter(E=>k?.includes(E)),$=b.filter(E=>q?.includes(E));if(h.length>0)return "update";if(S.length>0||$.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(o)}`)}return "match"},L={...o.$entity&&{$entity:o.$entity},...o.$relation&&{$relation:o.$relation},...o.$id&&{$id:o.$id},...o.$tempId&&{$tempId:o.$tempId},...o.$filter&&{$filter:o.$filter},...radash.shake(radash.pick(o,w||[""])),$op:T(),$bzId:o.$bzId,[Symbol.for("dbId")]:P.defaultDBConnector.id,[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("parent")]:o[Symbol.for("parent")],[Symbol.for("isRoot")]:o[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:o[Symbol.for("isLocalId")]||!1};if(p(L),o[Symbol.for("relation")]&&o[Symbol.for("edgeType")]==="linkField"){if((o.$op==="link"||o.$op==="unlink")&&(o.$id||o.$filter)){if(o.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");s.push({...o,$op:"match"});}let h=o[Symbol.for("relation")]===o.$relation,S=h?o.$bzId:`LT_${uuid.v4()}`,E=o[Symbol.for("parent")].path,m=(E?objectTraversal.getNodeByPath(e,E):e).$bzId;if(!m)throw new Error("No parent id found");if(o[Symbol.for("relation")]==="$self")return;let Q=()=>{if(o.$op==="delete")return h?"match":"delete";if(o.$op==="unlink")return h?"unlink":"delete";if(o.$op==="link"||o.$op==="create")return h?"link":"create";if(o.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},I={$relation:o[Symbol.for("relation")],$bzId:S,...o.$tempId?{$tempId:o.$tempId}:{},$op:Q(),...h?{}:{[o[Symbol.for("role")]]:o.$bzId},[o[Symbol.for("oppositeRole")]]:m,[Symbol.for("dbId")]:l.relations[o[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("parent")]:o[Symbol.for("parent")]};i(I),(o.$op==="unlink"||Q()==="unlink")&&h&&i({$relation:o[Symbol.for("relation")],$bzId:S,$op:"match",[o[Symbol.for("oppositeRole")]]:m,[Symbol.for("dbId")]:l.relations[o[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("parent")]:o[Symbol.for("parent")]});}if(o.$relation){let h=ce(o,(E,g)=>k.includes(E)),S=radash.mapEntries(h,(E,g)=>radash.isArray(g)?[E,g]:radash.isObject(g)?[E,g.$bzId]:[E,g]),$=ce(t,(E,g)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(h).filter(E=>!E.startsWith("$")).length>0){if(o.$op==="create"||o.$op==="delete"){let E=()=>{if(o.$op==="create")return "link";if(o.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},g=radash.mapEntries(S,(Q,I)=>Array.isArray(I)?[Q,I.map(O=>O.$bzId||O)]:[Q,I.$bzId||I]),m={...$,$relation:o.$relation,$op:E(),...g,$bzId:o.$bzId,[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("dbId")]:P.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};i(m);return}if(o.$op==="match"||o.$op==="update"&&Object.keys(h).length>0){let E=0;Object.entries(h).forEach(([g,m])=>{let Q=radash.isArray(m)?m:[m],I=O=>O==="create"||O==="replace"?"link":O;Q.forEach(O=>{if(!O)return;let j=I(O.$op);if(j==="replace")throw new Error("Not supported yet: replace on roleFields");if(j==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let D={...$,$relation:o.$relation,$op:j==="delete"?"unlink":j,[g]:O.$bzId,$bzId:o.$bzId,[Symbol.for("dbId")]:P.defaultDBConnector.id,[Symbol.for("parent")]:o[Symbol.for("parent")],[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};i(D);});});}}}}}),[s,u]};if(!r)throw new Error("Undefined filledBqlRequest");let [F,f]=a(r),y=F.reduce((e,s)=>{if(!s.$bzId)return [...e,s];let u=e.findIndex(n=>n.$bzId===s.$bzId);if(u===-1)return [...e,s];if(e[u].$op==="create"&&s.$op==="match")return e;if(e[u].$op==="match"&&(s.$op==="create"||s.$op==="match"))return [...e.slice(0,u),s,...e.slice(u+1)];throw new Error(`Unsupported operation combination for $tempId "${s.$tempId}". Existing: ${e[u].$op}. Current: ${s.$op}`)},[]),B=f.reduce((e,s)=>{let u=e.find(n=>(n.$id&&n.$id===s.$id||n.$bzId&&n.$bzId===s.$bzId)&&n.$relation===s.$relation&&n.$op===s.$op);if(u){let n={...u};return Object.keys(s).forEach(i=>{if(typeof i=="symbol"||i.startsWith("$"))return;let c=u[i],t=s[i];Array.isArray(c)&&Array.isArray(t)?n[i]=Array.from(new Set([...c,...t])):!Array.isArray(c)&&Array.isArray(t)?c!==void 0?n[i]=Array.from(new Set([c,...t])):n[i]=t:Array.isArray(c)&&!Array.isArray(t)?t!==void 0&&(n[i]=Array.from(new Set([...c,t]))):c!==null&&t!==null&&c!==void 0&&t!==void 0?n[i]=Array.from(new Set([c,t])):c==null&&(n[i]=t);}),[...e.filter(i=>!((i.$id&&i.$id===s.$id||i.$bzId&&i.$bzId===s.$bzId)&&i.$relation===s.$relation&&i.$op===s.$op)),n]}return [...e,s]},[]);[...new Set(B.map(e=>e.$relation))];d.bqlRequest={mutation:{things:y,edges:B}};};var fe=async(d,r)=>{let l=r.dbConnectors[0].id,a=d.typeDB.get(l)?.session,F=d.typeDB.get(l)?.client;if(!a||!a.isOpen()){if(!F)throw new Error("Client not found");a=await F.session(r.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),d.typeDB.set(l,{client:F,session:a});}return {client:F,session:a}};var it=async(d,r)=>{let{dbHandles:l,tqlRequest:a,bqlRequest:F,config:f}=d;if(!a)throw new Error("TQL request not built");if(!(a.deletions&&a.deletionMatches||a.insertions))throw new Error("TQL request error, no things");if(!F?.mutation)throw new Error("BQL mutation not parsed");let{session:y}=await fe(l,f),B=await y.transaction(typedbDriver.TransactionType.WRITE);if(!B)throw new Error("Can't create transaction");let M=a.deletionMatches&&a.deletions&&`match ${a.deletionMatches} delete ${a.deletions}`,R=a.insertions&&`${a.insertionMatches?`match ${a.insertionMatches}`:""} insert ${a.insertions}`;M&&await B.query.delete(M);let e=R&&B.query.insert(R);try{let s=e?await e.collect():void 0;await B.commit(),await B.close(),r.rawTqlRes={insertions:s};}catch(s){throw await B.close(),new Error(`Transaction failed: ${s.message}`)}};var be=Symbol.for("schema"),U=Symbol.for("queryPath");var W="___",nt=async d=>{let{enrichedBqlQuery:r}=d;if(!r)throw new Error("BQL query not enriched");let l="",a=(e,s)=>{let u="",n="";for(let p in e){let i=e[p];if(Array.isArray(i))for(let c=0;c<i.length;c++)n+=`{$${s} has ${p} "${i[c]}";}`,c<i.length-1?n+="or":n+=";";else u+=`, has ${p} "${i}"`;}u+=`;
|
|
36
|
+
`,l+=u,l+=n;},F=(e,s)=>{let u=[],n=[],p="";for(let t=0;t<e.length;t++)e[t].$isVirtual||u.push(` ${e[t].$dbPath}`),n.push(`{${e[t].$dbPath}:${e[t].$as}}`);let i=`${u.join(",")};
|
|
37
|
+
`;p=n.join(",");let c=`$metadata:{as:[${p}]}`;l+=`$${s} as "${s}.${c}.$dataFields": `,l+=i;},f=(e,s,u)=>{for(let n of e){let{$fields:p,$as:i,$justId:c,$idNotIncluded:t,$filterByUnique:o}=n,P=n[U],w=`$metadata:{as:${i},justId:${c?"T":"F"},idNotIncluded:${t},filterByUnique:${o}}`;if(l+=`"${u}.${w}.${n.$var}":{
|
|
38
|
+
`,l+=` match
|
|
39
|
+
`,n.$filter&&(l+=` $${s}${W}${n.$var} isa ${n.$thing}`,a(n.$filter,`${s}${W}${n.$var}`)),l+=` $${s} (${n.$var}: $${s}${W}${n.$var}) isa ${n.$intermediary};
|
|
40
|
+
`,p){let k=`M_${uuid.v4()}`;l+=`?queryPath${k} = "${P}";
|
|
41
|
+
`,l+=` fetch
|
|
42
|
+
`,l+=`?queryPath${k} as "queryPath"
|
|
43
|
+
;`;let q=p?.filter(L=>L.$fieldType==="data");q&&q.length>0&&F(q,`${s}${W}${n.$var}`,`${s}.${n.$var}`);let b=p?.filter(L=>L.$fieldType==="link");b&&b.length>0&&y(b,`${s}${W}${n.$var}`,`${s}.${n.$var}`);let T=p?.filter(L=>L.$fieldType==="role");T&&T.length>0&&f(T,`${s}${W}${n.$var}`,`${s}.${n.$var}`);}l+=`};
|
|
44
|
+
`;}},y=(e,s,u)=>{for(let n of e){let{$fields:p,$as:i,$justId:c,$idNotIncluded:t,$filterByUnique:o,$playedBy:P}=n,w=n[U],k=`$metadata:{as:${i},justId:${c?"T":"F"},idNotIncluded:${t},filterByUnique:${o}}`;if(l+=`"${u}.${k}.${n.$var}":{
|
|
45
|
+
`,l+=` match
|
|
46
|
+
`,n.$filter&&(l+=` $${s}${W}${n.$var} isa ${n.$thing}`,a(n.$filter,`${s}${W}${n.$var}`)),n.$target==="role"?l+=` $${s}_intermediary (${n.$plays}: $${s}, ${P.plays}: $${s}${W}${n.$var}) isa ${n.$intermediary};
|
|
47
|
+
`:l+=` $${s}${W}${n.$var} (${n.$plays}: $${s}) isa ${n.$thing};
|
|
48
|
+
`,p){let q=`M_${uuid.v4()}`;l+=`?queryPath${q} = "${w}";
|
|
49
|
+
`,l+=` fetch
|
|
50
|
+
`,l+=`?queryPath${q} as "queryPath"
|
|
51
|
+
;`;let b=p?.filter(h=>h.$fieldType==="data");b&&b.length>0&&F(b,`${s}${W}${n.$var}`);let T=p?.filter(h=>h.$fieldType==="link");T&&T.length>0&&y(T,`${s}${W}${n.$var}`,`${s}.${n.$var}`);let L=p?.filter(h=>h.$fieldType==="role");L&&L.length>0&&f(L,`${s}${W}${n.$var}`,`${s}.${n.$var}`);}l+=`};
|
|
52
|
+
`;}},B=r.length>1,M=[];(e=>{if(B)for(let s of e){let{$path:u,$thing:n,$filter:p,$fields:i}=s,c=s[U];l+=`match
|
|
53
|
+
$${u} isa ${n} `,p?a(p,u):l+="; ";let t=`M_${uuid.v4()}`;if(l+=`?queryPath${t} = "${c}";
|
|
54
|
+
`,l+=`fetch
|
|
55
|
+
`,l+=`?queryPath${t} as "queryPath"
|
|
56
|
+
;`,i){let o=i.filter(k=>k.$fieldType==="data");o&&o.length>0&&F(o,u);let P=i.filter(k=>k.$fieldType==="link");P&&P.length>0&&y(P,u,u);let w=i.filter(k=>k.$fieldType==="role");w&&w.length>0&&f(w,u,u);}M.push(l),l="";}else for(let s of e){let{$path:u,$thing:n,$filter:p,$fields:i}=s,c=s[U];if(l+=`match
|
|
57
|
+
$${u} isa ${n} `,p?a(p,u):l+="; ",l+=`?queryPath = "${c}";
|
|
58
|
+
`,l+=`fetch
|
|
59
|
+
`,l+=`?queryPath as "queryPath"
|
|
60
|
+
;`,i){let t=i.filter(w=>w.$fieldType==="data");t&&t.length>0&&F(t,u);let o=i.filter(w=>w.$fieldType==="link");o&&o.length>0&&y(o,u,u);let P=i.filter(w=>w.$fieldType==="role");P&&P.length>0&&f(P,u,u);}}})(r),d.tqlRequest=B?M:l;};var Re=d=>{let r=d.dataFields?.map(f=>f.path)||[],l=d.linkFields?.map(f=>f.path)||[],a=Object.keys(d.roles||{})||[];return [...r,...l,...a]},qe=(d,r)=>Object.keys(d||{}).some(a=>{if(!Array.isArray(d[a])){let F=r.idFields?.includes(a),f=r.dataFields?.some(y=>(y.dbPath===a||y.path===a)&&y?.validations?.unique);return F||f}return !1}),Oe=(d,r)=>{let l=r.dataFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],a=r.linkFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],F=Object.keys(r.roles||{}).map(y=>({path:y,dbPath:y}))||[],f=[...l,...a,...F];return Object.entries(d||{}).reduce((y,[B,M])=>{let R=f.find(e=>e.path===B);return y[R?.dbPath||B]=M,y},{})},ot=async d=>{let{rawBqlRequest:r,schema:l}=d;if(Array.isArray(r)){for(let e of r)if(!("$entity"in e)&&!("$relation"in e)&&(!("$thing"in e)||!("$thingType"in e)))throw new Error("No entity specified in query")}else if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query");let a=(e,s)=>typeof s=="string"?e.idFields?.includes(s):e.idFields?.includes(s.$path),F=(e,s,u,n,p)=>({$path:s,$dbPath:n,$thingType:"attribute",$as:e.$as||s,$var:s,$fieldType:"data",$excludedFields:e.$excludedFields,$justId:u,$id:e.$id,$filter:e.$filter,$isVirtual:p,$filterProcessed:!0}),f=(e,s,u,n,p)=>{let{target:i,oppositeLinkFieldsPlayedBy:c}=u;return c.map(t=>{let o=i==="role"?t.thingType:"relation",P=i==="role"?t.thing:u.relation,w={[`$${o}`]:P},k=N(l,w),q=e?.$fields?.filter(T=>a(k,T)).length===0,b=[];return typeof e!="string"?e.$fields?q?b=[...e.$fields,...k.idFields]:b=e.$fields:b=Re(k):b=["id"],e.$excludedFields&&(b=b.filter(T=>a(k,T)?!0:!e.$excludedFields.includes(T.$path))),{$thingType:o,$plays:u.plays,$playedBy:t,$path:t.path,$dbPath:p,$as:e.$as||s,$var:s,$thing:P,$fields:b,$excludedFields:e.$excludedFields,$fieldType:"link",$target:i,$intermediary:t.relation,$justId:n,$id:e.$id,$filter:Oe(e.$filter,k),$idNotIncluded:q,$filterByUnique:qe(e.$filter,k),$filterProcessed:!0}})},y=(e,s,u,n,p)=>u.playedBy.map(i=>{let{thing:c,thingType:t,relation:o}=i,P={[`$${t}`]:c},w=N(l,P),k=e?.$fields?.filter(b=>w?.idFields?.includes(b)||w?.idFields?.includes(b.$path)).length===0,q=[];return typeof e!="string"?e.$fields?k?q=[...e.$fields,...w.idFields]:q=e.$fields:q=Re(w):q=["id"],e.$excludedFields&&(q=q.filter(b=>a(w,b)?!0:!e.$excludedFields.includes(b.$path))),{$thingType:t,$path:s,$dbPath:p,$as:e.$as||s,$var:s,$thing:c,$fields:q,$excludedFields:e.$excludedFields,$fieldType:"role",$intermediary:o,$justId:n,$id:e.$id,$filter:Oe(e.$filter,w),$idNotIncluded:k,$filterByUnique:qe(e.$filter,w),$playedBy:i,$filterProcessed:!0}}),B=(e,s)=>{let u=typeof e=="string"?e:e.$path,n=typeof e=="string",p=s.dataFields?.find(t=>t.path===u),i=s.linkFields?.find(t=>t.path===u),c=s.roles?.[u];if(p){let t=p.isVirtual&&p.default;return F(e,u,n,p.dbPath,t)}else {if(i)return f(e,u,i,n,i.dbPath);if(c)return y(e,u,c,n,c.dbPath)}return null},R=(e=>immer.produce(e,s=>objectTraversal.traverse(s,u=>{let{value:n,meta:p}=u,i=n;if(radash.isObject(i)){if(i.$id){let c=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},t=N(l,c);if(i.$path=t.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),t?.idFields?.length===1){let[o]=t.idFields;i.$filter={...i.$filter,[o]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i){let c=N(l,i);i.$path=c.name,i.$as=c.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),radash.isObject(i)&&"$thing"in i){let c=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[U]=p.nodePath;let t=N(l,c);if(i.$filter&&(i.$filterByUnique=qe(i.$filter,t),i.$filterProcessed||(i.$filter=Oe(i.$filter,t))),i.$fields){i.$fields.filter(w=>t?.idFields?.includes(w)||t?.idFields?.includes(w.$path)).length>0||(i.$fields=[...i.$fields,...t.idFields],i.$idNotIncluded=!0);let P=i.$fields?.flatMap(w=>{let k=B(w,t);return Array.isArray(k)?k:[k]}).filter(Boolean);i.$fields=P;}else {let P=Re(t)?.flatMap(w=>{let k=B(w,t);return Array.isArray(k)?k:[k]}).filter(Boolean);i.$fields=P;}i.$excludedFields&&(i.$fields=i.$fields.filter(o=>a(t,o)?!0:!i.$excludedFields.includes(o.$path)));}}})))(Array.isArray(r)?r:[r]);d.enrichedBqlQuery=R;};var at=async(d,r)=>{let{dbHandles:l,enrichedBqlQuery:a,tqlRequest:F,config:f}=d;if(!a)throw new Error("BQL request not parsed");if(!F)throw new Error("TQL request not built");let y=new typedbDriver.TypeDBOptions;if(y.infer=!0,Array.isArray(F)){let M=await radash.parallel(F.length,F,async R=>{let{session:e}=await fe(l,f),s=await e.transaction(typedbDriver.TransactionType.READ,y);if(!s)throw new Error("Can't create transaction");let n=await s.query.fetch(R).collect();return await s.close(),n});r.rawTqlRes=M,r.isBatched=!0;}else {let{session:M}=await fe(l,f),R=await M.transaction(typedbDriver.TransactionType.READ,y);if(!R)throw new Error("Can't create transaction");let s=await R.query.fetch(F).collect();await R.close(),r.rawTqlRes=s;}};var lt=d=>{let r=/as:([a-zA-Z0-9_\-·]+)/,l=/justId:([a-zA-Z0-9_\-·]+)/,a=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,F=/filterByUnique:([a-zA-Z0-9_\-·]+)/,f=d.match(r),y=d.match(l),B=d.match(a),M=d.match(F);return {as:f?f[1]:null,justId:y?y[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:M?M[1]:null}},yi=d=>{try{let l=(F=>{let f=F.replace("$metadata:","");return f=f.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),f=f.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(y,B,M)=>/^{.*}$/.test(M)?`:${M}`:`:${B}"${M}"`),f=f.replace(/\[([^\]]+)\]/g,(y,B)=>`[${B.split(",").map(M=>M.trim().startsWith("{")&&M.trim().endsWith("}")?M.trim():`"${M.trim()}"`).join(",")}]`),f})(d);return JSON.parse(l)}catch(r){return console.error(r),{as:[]}}},dt=async(d,r)=>{let{enrichedBqlQuery:l,rawBqlRequest:a,schema:F,config:f}=d,{rawTqlRes:y,isBatched:B}=r;if(l){if(!y)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let M=(i,c)=>{let{$metaData:t}=i,{as:o}=yi(t),P=Object.entries(i).filter(([w])=>w!=="type"&&!w.includes("$")).map(([w,k])=>{let q=c.dataFields?.find(h=>h.path===w||h.dbPath===w),b=w==="id",T=Array.isArray(o)?o.find(h=>h[w])?.[w]:w,L;if(q?.cardinality==="ONE"){if(L=k[0]?k[0].value:f.query?.returnNulls?null:void 0,q.contentType==="DATE"&&(L=L&&`${L}Z`),b)return [[T,L],["$id",L]].filter(([h,S])=>S!==void 0)}else if(q?.cardinality==="MANY"){if(!radash.isArray(k))throw new Error("Typedb fetch has changed its format");if(k.length===0)return f.query?.returnNulls?[[T,null]]:[];q.contentType==="DATE"?L=k.map(h=>`${h.value}Z`):L=k.map(h=>h.value);}return [[T,L]].filter(([h,S])=>S!==void 0)}).flat();return Object.fromEntries([...P])},R=i=>i.reduce((c,t)=>{let{$roleFields:o,$metaData:P,$cardinality:w}=t,{as:k,justId:q,idNotIncluded:b,filterByUnique:T}=lt(P),L=o.map(h=>{let{dataFields:S,currentSchema:$,linkFields:E,roleFields:g,schemaValue:m}=s(h),Q=M(S,$);if(q==="T")return Q.id;{let I=e(E),O=R(g),j={...Q};return b==="true"&&$?.idFields?.forEach(D=>delete j[D]),{...j,...I,...O,...m}}});return L.length>0?c[k]=w==="MANY"&&T==="false"?L:L[0]:f.query?.returnNulls&&(c[k]=null),c},{}),e=i=>i.reduce((c,t)=>{let{$linkFields:o,$metaData:P,$cardinality:w}=t,{as:k,justId:q,idNotIncluded:b,filterByUnique:T}=lt(P),L=o.map(h=>{let{dataFields:S,currentSchema:$,linkFields:E,roleFields:g,schemaValue:m}=s(h),Q=M(S,$);if(q==="T")return Q.id;{let I=e(E),O=R(g),j={...Q};return b==="true"&&$.idFields?.forEach(D=>delete j[D]),{...j,...I,...O,...m}}});return c[k]=L.length>0?w==="MANY"&&T==="false"?L:L[0]:f.query?.returnNulls?null:void 0,c},{}),s=i=>{let c=Object.keys(i),t=c.find(h=>h.endsWith(".$dataFields"));if(!t)throw new Error("No datafields");let o=i[t],P=t.split(".")[t.split(".").length-2];if(o.$metaData=P,o.length===0)throw new Error("No datafields");let w=o.type,k={$thing:w.label,$thingType:w.root,[U]:i.queryPath.value},q={[`$${k.$thingType}`]:k.$thing},b=N(F,q),T=c.filter(h=>!h.endsWith(".$dataFields")&&b.linkFields?.some(S=>S.path===h.split(".").pop())).map(h=>({$linkFields:i[h],$key:h.split(".").pop(),$metaData:h.split(".")[h.split(".").length-2],$cardinality:b?.linkFields?.find(S=>S.path===h.split(".").pop())?.cardinality})),L=c.filter(h=>!h.endsWith(".$dataFields")&&b.roles?.[h.split(".").pop()]).map(h=>({$roleFields:i[h],$key:h.split(".").pop(),$metaData:h.split(".")[h.split(".").length-2],$cardinality:b.roles[h.split(".").pop()].cardinality}));return {dataFields:o,schemaValue:k,currentSchema:b,linkFields:T,roleFields:L}},u=i=>i.map(c=>{let{dataFields:t,currentSchema:o,linkFields:P,roleFields:w,schemaValue:k}=s(c),q=M(t,o),b=e(P),T=R(w),L=a?.$fields?.every(S=>!o?.idFields?.includes(S)&&!o?.idFields?.includes(S.$path));return {...b,...T,...k,...!f.query?.noMetadata&&a.$id?{$id:Array.isArray(a.$id)?q.id:a.$id}:{},...L?Object.fromEntries(Object.entries(q).filter(([S])=>!o?.idFields?.includes(S))):q}}),p=(i=>{let c=t=>{let o=u(t);return a.$id&&!Array.isArray(a.$id)||l[0].$filterByUnique?o[0]??null:o.length===0?null:o};return B?i.map(c):c(i)})(y);r.bqlRes=p;};var hi=Symbol.for("grandChildOfCreate"),ne=d=>({...d[Symbol.for("relation")]&&{[Symbol.for("relation")]:d[Symbol.for("relation")]},...d[Symbol.for("parent")]&&{[Symbol.for("parent")]:d[Symbol.for("parent")]},...d[Symbol.for("edgeType")]&&{[Symbol.for("edgeType")]:d[Symbol.for("edgeType")]},...d[Symbol.for("role")]&&{[Symbol.for("role")]:d[Symbol.for("role")]},...d[Symbol.for("oppositeRole")]&&{[Symbol.for("oppositeRole")]:d[Symbol.for("oppositeRole")]},...d[Symbol.for("relFieldSchema")]&&{[Symbol.for("relFieldSchema")]:d[Symbol.for("relFieldSchema")]},...d[Symbol.for("path")]&&{[Symbol.for("path")]:d[Symbol.for("path")]},...d[Symbol.for("isRoot")]&&{[Symbol.for("isRoot")]:d[Symbol.for("isRoot")]},...d[Symbol.for("depth")]&&{[Symbol.for("depth")]:d[Symbol.for("depth")]},...d[Symbol.for("schema")]&&{[Symbol.for("schema")]:d[Symbol.for("schema")]},...d[Symbol.for("dbId")]&&{[Symbol.for("dbId")]:d[Symbol.for("dbId")]},...d[Symbol.for("index")]&&{[Symbol.for("index")]:d[Symbol.for("index")]}}),ct=async d=>{let{filledBqlRequest:r,config:l,schema:a}=d,F=(b,T)=>Object.keys(b).filter(L=>L.startsWith("$")?!1:T?!N(a,b).dataFields?.find(S=>S.path===L):!0);if(!r)throw new Error("[BQLE-M-PQ-1] No filledBqlRequest found");if(l.mutation?.preQuery===!1)return;let f=[];if(objectTraversal.traverse(r,({parent:b,key:T,value:L})=>{b&&T&&!T.includes("$")&&radash.isObject(b)?(Array.isArray(b[T])?b[T]:[b[T]]).forEach(S=>{if(radash.isObject(S)){if(b.$op!=="create")f.includes(S.$op)||f.push(S.$op);else if(S.$op==="delete"||S.$op==="unlink")throw new Error(`Cannot ${S.$op} under a create`)}}):!b&&radash.isObject(L)&&(f.includes(L.$op)||f.push(L.$op));}),!f.includes("delete")&&!f.includes("unlink")&&!f.includes("replace")&&!f.includes("update")&&!f.includes("link"))return;let B=(b=>{let T=(L,h)=>{let S=[],$={},E=["$op","$bzId","$parentKey"],g=["$relation","$entity","$id",...E];for(let m in L)if(!E.includes(m)&&!(g.includes(m)&&!h))if(!m.includes("$")&&(radash.isObject(L[m])||Array.isArray(L[m]))){let Q=L[m];Array.isArray(Q)&&Q.length>0?Q.forEach(I=>{S.push({$path:m,...T(I)});}):S.push({$path:m,...T(Q)});}else $[m]=L[m];return {...$,$fields:S}};return b.map(L=>T(L,!0))})(Array.isArray(r)?r:[r]),M=await Fe(B,d.config,d.schema,d.dbHandles),R=(b,T)=>{let L=b.$id||b.id||b.$bzId;if(b.$objectPath){let{$objectPath:h}=b,S=h?.beforePath||"root",$=Array.isArray(h.ids)?`[${h.ids}]`:h.ids;return {beforePath:`${S}.${$}___${h.key}`,ids:L,key:T}}else return {beforePath:"root",ids:L,key:T}},e=(b,T)=>{let L=b?.beforePath||"root",h=T||(Array.isArray(b?.ids)?`[${b?.ids}]`:b?.ids);return `${L}.${h}___${b?.key}`},s=b=>{if(b.includes("[")&&b.includes("]")){let[T,L,h]=b.split(/[[\]]/);return L.split(",").map($=>`${T}${$}${h}`)}else return [b]},u={};(b=>immer.produce(b,T=>objectTraversal.traverse(T,L=>{let{key:h,parent:S}=L;if(S&&h&&S.$id&&!h.includes("$")){let $=R(S,h),E=e($);if(Array.isArray(S[h])){let g=[];S[h].forEach(m=>{radash.isObject(m)?(m.$objectPath=$,g.push(m.$id.toString())):m&&g.push(m.toString());}),u[E]={$objectPath:$,$ids:g};}else {let g=S[h];radash.isObject(g)?(u[E]={$objectPath:$,$ids:[g.$id.toString()]},g.$objectPath=$):g&&(u[E]={$objectPath:$,$ids:[g.toString()]});}}})))(M||{});let p=b=>immer.produce(b,T=>objectTraversal.traverse(T,L=>{let{key:h,value:S,parent:$}=L;$&&h&&!h.includes("$")&&(Array.isArray(S)||radash.isObject(S))&&!Array.isArray($)&&(Array.isArray($[h])?$[h].forEach(E=>{typeof E!="string"&&(E.$objectPath=R($,h),E.$parentIsCreate=$.$op==="create",E[hi]=$.$parentIsCreate||$[Symbol.for("grandChildOfCreate")]);}):radash.isObject($[h])&&($[h].$parentIsCreate=$.$op==="create",$[h][Symbol.for("grandChildOfCreate")]=$.$parentIsCreate||$[Symbol.for("grandChildOfCreate")],$[h].$objectPath=R($,h)));})),i=p(r),t=(b=>{let T=($,E)=>{let g=[];$.filter(O=>O).forEach(O=>{let j=Object.keys(O).filter(D=>!D.startsWith("$")).length;if(Array.isArray(O.$id)&&j>0){let D=O.$id.map(z=>({...O,$id:z}));g=[...g,...D];}else g.push({...O});});let m=[],Q=[],I=g.filter(O=>{let D=["delete","update","unlink"].includes(O.$op||""),z=F(O,!0).length;if((!O.$id||Array.isArray(O.$id)&&z>0||O.$filter)&&D)return !0;Q.push({...O});});return I.length>0?I.forEach(O=>{let D=(x=>{let se=(()=>{let _={};for(let C in x){let Y=N(a,x);!C.startsWith("$")&&Y.dataFields?.find(re=>re.path===C)&&(_[C]=x[C]);}return _})(),ae=Object.keys(x),Z=ae.filter(_=>!_.startsWith("$")),we=[],ye=(_,C)=>{if(_===Z.length){let re={...C};ae.forEach(V=>{V.startsWith("$")&&(re[V]=x[V]);}),we.push(re);return}let Y={...C,[Z[_]]:x[Z[_]],...ne(C),...se};ye(_+1,Y),ye(_+1,C);};return ye(0,{...ne(x)}),we})(O).filter(x=>!(x.$op==="update"&&Object.keys(x).filter(ee=>!ee.startsWith("$")).length===0)),z=[],J=e(O.$objectPath),v=u[J]?u[J].$ids:[],A=D.map((x,ee)=>{let se=N(a,x),Z=Object.keys(x).filter(C=>!C.includes("$")&&!se.dataFields?.some(Y=>Y.path===C)).map(C=>(Array.isArray(x[C])?x[C].length>1?x[C].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):x[C]:[x[C]]).map(V=>{let Ee=e(V.$objectPath);return {idsToKey:(Le=>{let je=[],de=Le.split("."),Ot=de.slice(0,de.length-1).join("."),At=de.slice(de.length-1,de.length)[0].split("___")[1];for(let Me in u)if(Me.startsWith(Ot)&&Me.endsWith(At)){let Te=Me.split("."),Ct=Te.slice(Te.length-1,Te.length)[0].split("___")[0];je.push(Ct);}return je})(Ee),key:C,multiple:V}})).filter(C=>C!==void 0),_=(C=>{let Y=C.map(V=>V.map(te=>te.idsToKey));return (V=>V.length>0?V.reduce((te,le)=>te.concat(le),[]).reduce((te,le)=>te?le.filter(Le=>te.includes(Le)):le):[])(Y)})(Z).filter(C=>!z.includes(C));if(z=[...z,..._],v=v.filter(C=>!_.includes(C)),ee===D.length-1&&v.length>0)return {...x,$id:v,$bzId:`T_${uuid.v4()}`,...ne(x)};if(_.length>0)return {...x,$id:_,$bzId:`T_${uuid.v4()}`,...ne(x)}}).filter(x=>x!==void 0),qt=(()=>{if(A.length===0&&!E?.$id)return I;if(A.length===0&&E?.$id){let x=Array.isArray(E.$id)?E.$id:[E.$id],ee=[];return x.forEach(se=>{let ae=e({...O.$objectPath,ids:se}),Z=u[ae];Z&&ee.push({...O,$id:Z.$ids,...ne(O),$bzId:`T_${uuid.v4()}`});}),ee}else return A})();m=[...Q,...qt].map(L);}):m=g.map(L),m},L=$=>{let E={...$,$bzId:`T_${uuid.v4()}`,...ne($)},g=N(a,$);return Object.keys($).filter(m=>!m.includes("$")&&!g.dataFields?.some(Q=>Q.path===m)).forEach(m=>{let Q=Array.isArray($[m])?$[m]:[$[m]],I=T(Q,$);E[m]=I.length>0?I:void 0;}),E},h=[];return b.forEach($=>{h=[...h,...T([$])];}),h.map($=>L($))})(Array.isArray(i)?i:[i]),o=b=>b.map(T=>{let L=F(T,!0),h={...T};return L.forEach(S=>{let $=Array.isArray(T[S])?T[S]:[T[S]],E=[],g=[],m=[],Q={},I=Se(a,T,S);$.filter(A=>A).forEach(A=>{A.$op==="replace"&&A.$id?(Q=A,Array.isArray(A.$id)?g=[...g,...A.$id]:g.push(A.$id)):A.$op==="create"&&I==="ONE"&&A.id?(Q=A,Array.isArray(A.id)?m=[...g,...A.id]:m.push(A.id)):E.push(A);});let O=e(Q.$objectPath),D=s(O).map(A=>u[A]),z=[];D.filter(A=>A!=null).forEach(A=>{z=[...z,...A.$ids];});let J=z.filter(A=>!g.includes(A)),K=g.filter(A=>!z.includes(A)),v=ne(Q);J.length>0&&E.push({...Q,$op:"unlink",$id:J,$bzId:`T_${uuid.v4()}`,id:void 0,...v}),K.length>0&&K.forEach(A=>{E.push({...Q,$op:"link",$id:A,$bzId:`T_${uuid.v4()}`,...v});}),m.length>0&&m.forEach(A=>{E.push({...Q,$op:"create",id:A,$bzId:`T_${uuid.v4()}`,...v});}),h[S]=o(E);}),h}),P=p(o(p(t)));(b=>immer.produce(b,T=>objectTraversal.traverse(T,L=>{let{key:h,value:S,parent:$}=L;h&&$&&!h?.includes("$")&&(Array.isArray(S)||radash.isObject(S))&&!Array.isArray($)&&(Array.isArray(S)?S:[S]).forEach(g=>{let m=u[e(g.$objectPath)],Q=(j,D)=>j.every(z=>D.includes(z)),I=g.$id?Array.isArray(g.$id)?Q(g.$id,m?m.$ids:[]):m?.$ids.includes(g.$id):m,O=Se(a,$,g.$objectPath.key);if(g.$op==="link"&&I&&O==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${e(g.$objectPath)}" because it is already occupied.`);if(g.$op)switch(g.$op){case"delete":if(!I&&!l.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${g.$id}" because it is not linked to $id:"${$.$id}"`);break;case"update":if(!I&&!l.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${g.$id}" because it is not linked to $id:"${$.$id}"`);break;case"unlink":if(!I&&!l.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${g.$id}" because it is not linked to $id:"${$.$id}"`);break;case"link":if(I)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${g.$id}" because it is already linked to $id:"${$.$id}"`);break;}});})))(P);let q=(b=>immer.produce(b,T=>objectTraversal.traverse(T,L=>{let{parent:h,key:S,value:$,meta:E}=L;radash.isObject($)&&($[Symbol.for("path")]=E.nodePath,delete $.$objectPath,delete $.$parentIsCreate),S&&h&&!S?.includes("$")&&(Array.isArray($)||radash.isObject($))&&!Array.isArray(h)&&(Array.isArray($)?$:[$]).forEach(m=>{radash.isObject(m)&&(m[Symbol.for("parent")]={...$[Symbol.for("parent")],path:h[Symbol.for("path")]});});})))(P);d.filledBqlRequest=q;};var yt=async d=>{let{filledBqlRequest:r,schema:l}=d;if(!r)throw new Error("Filled BQL request is missing");let F=(B=>immer.produce(B,M=>objectTraversal.traverse(M,({value:R})=>{if(radash.isObject(R)){let e=R,s=N(l,e),{unidentifiedFields:u}=G(s,e),{idFields:n,computedFields:p,virtualFields:i}=s;if(!n)throw new Error("No idFields found");let[c]=n,t=radash.listify(e,(w,k)=>k!==void 0?w:void 0),o=t.filter(w=>i?.includes(w));if(o.length>0)throw new Error(`Virtual fields can't be sent to DB: "${o.join(",")}"`);if(p.filter(w=>!t.includes(w)).forEach(w=>{let k=s.dataFields?.find(h=>h.path===w),b=s.linkFields?.find(h=>h.path===w)?.oppositeLinkFieldsPlayedBy[0],T="roles"in s?pe(s.roles,(h,S)=>h===w):void 0,L=k||b||T;if(!L)throw new Error(`no field Def for ${w}`);if(w!==c&&e.$op==="create"&&!e[w]){let h=X({currentThing:e,fieldSchema:L,mandatoryDependencies:!0});e[w]=h;}}),u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(e)}`)}})))(r),y=(B=>immer.produce(B,M=>objectTraversal.traverse(M,({value:R})=>{radash.isObject(R);})))(F);d.filledBqlRequest=y;};var gt=async d=>{let{filledBqlRequest:r}=d;if(!r)throw new Error("Filled BQL request is missing");let a=(y=>immer.produce(y,B=>objectTraversal.traverse(B,({value:M})=>{radash.isObject(M)&&Je();})))(r),f=(y=>immer.produce(y,B=>objectTraversal.traverse(B,({value:M})=>{radash.isObject(M);})))(a);d.filledBqlRequest=f;};var wt=async d=>{let{filledBqlRequest:r}=d;if(!r)throw new Error("Filled BQL request is missing");let l=F=>immer.produce(F,f=>objectTraversal.traverse(f,({value:y})=>{if(radash.isObject(y)&&("$entity"in y||"$relation"in y)){let B=y,{requiredFields:M,enumFields:R,fnValidatedFields:e}=B[be];"$op"in B&&B.$op==="create"&&M.forEach(s=>{if(!(s in B))throw new Error(`[Validations] Required field "${s}" is missing.`)}),("$op"in B&&B.$op==="update"||B.$op==="create")&&R.forEach(s=>{if(s in B){let u=B[be]?.dataFields?.find(n=>n.path===s)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${s}" is missing enum options.`);if(radash.isArray(B[s]))B[s].some(n=>{if(!u.includes(n))throw new Error(`[Validations] Option "${n}" is not a valid option for field "${s}".`)});else if(u&&!u.includes(B[s]))throw new Error(`[Validations] Option "${B[s]}" is not a valid option for field "${s}".`)}}),("$op"in B&&B.$op==="update"||B.$op==="create")&&e.forEach(s=>{if(s in B)try{let u=B[be]?.dataFields?.find(n=>n.path===s)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(B[s]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${s}] ${u.message}`)}});}})),a=F=>immer.produce(F,f=>objectTraversal.traverse(f,({value:y,parent:B,meta:M})=>{if(radash.isObject(y)&&("$entity"in y||"$relation"in y)){let R="$entity"in y?y.$entity:y.$relation,e=y,s=y[Symbol.for("schema")].hooks;if(s){let{pre:u}=s;if(u){let n=`on${_e(e.$op)}`;u.filter(i=>i.triggers[n]).forEach(i=>{let c=n in i.triggers?i.triggers[n]:void 0;if(c!==void 0&&c()){let t=Ve(F,B,M);i.actions.forEach(o=>{if(o.type==="validate"){if(o.severity!=="error")return;try{let P=o.fn(e,t);if(P===!1)throw new Error(`${o.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}`)}}});}});}}}}));l(r),a(r);};var Et=async(d,r)=>{let{schema:l,enrichedBqlQuery:a}=d,{bqlRes:F}=r;if(!F)return;let y=(B=>immer.produce(B,M=>objectTraversal.traverse(M,({value:R})=>{if(radash.isObject(R)){let e=R;if(!e.$thing)throw new Error("[Internal] Thing is missing");if(e.$thing){let s=N(l,e),{virtualFields:u}=s,n=e[U];if(!n)throw new Error("[Internal] QueryPath is missing");let p=objectTraversal.getNodeByPath(a,n),i=p.$fields.map(t=>t.$path),c=p.$excludedFields;u.forEach(t=>{if(c?.includes(t)||i.length>0&&!i.includes(t))return;let o=s.dataFields?.find(P=>P.path===t);if(o?.default){let P=X({currentThing:e,fieldSchema:o,mandatoryDependencies:!0});e[t]=P;}else if(e[t]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${t}`)}),c&&c.forEach(t=>{if(typeof t!="string")throw new Error("[Internal] ExcludedField is not a string");delete e[t];});}}})))(F);r.bqlRes=y;};var kt=async(d,r)=>{let{config:l}=d,{bqlRes:a}=r;if(!a)return;let f=(M=>immer.produce(M,R=>objectTraversal.traverse(R,({value:e})=>{radash.isObject(e);})))(a),B=(M=>immer.produce(M,R=>objectTraversal.traverse(R,({value:e})=>{if(radash.isObject(e)){let s=e;Object.keys(s).forEach(u=>{s[u]===void 0&&delete s[u];}),Object.getOwnPropertySymbols(s).forEach(u=>{delete s[u];}),l.query?.noMetadata===!0&&Object.keys(s).forEach(u=>{u.startsWith("$")&&delete s[u];});}})))(f);r.bqlRes=B;};var Qt={query:[ot,nt,at,dt,Et,kt],mutation:[Ye,ct,yt,gt,wt,tt,Ue,it,We,He]},Ae=async(d,r,l={},a=!0)=>{for(let F of d){let f=await F(r,l);if(f&&Array.isArray(f))for(let y of f)await Ae(y.pipeline,y.req,y.res,!1);}return a&&r.config.query?.debugger===!0&&typeof l.bqlRes=="object"?{...l.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:l.bqlRes},Fe=(d,r,l,a)=>Ae(Qt.query,{config:r,schema:l,rawBqlRequest:d,dbHandles:a},{}),St=(d,r,l,a)=>Ae(Qt.mutation,{config:r,schema:l,rawBqlRequest:d,dbHandles:a},{});var Ce=class{schema;config;dbHandles;constructor({schema:r,config:l}){this.schema=r,this.config=l;}getDbHandles=()=>this.dbHandles;init=async()=>{let r={typeDB:new Map},l=ze(this.schema);await Promise.all(this.config.dbConnectors.map(async a=>{if(a.provider==="typeDB"&&a.dbName){let[F,f]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(a.url);if(F){let y=`[BORM:${a.provider}:${a.dbName}:core] ${F.message??"Can't create TypeDB Client"}`;throw new Error(y)}try{let y=await f.session(a.dbName,typedbDriver.SessionType.DATA);r.typeDB.set(a.id,{client:f,session:y});}catch(y){let B=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(a.provider==="typeDBCluster"&&a.dbName){let[F,f]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(a.addresses,a.credentials);if(F){let y=`[BORM:${a.provider}:${a.dbName}:core] ${F.message??"Can't create TypeDB Cluster Client"}`;throw new Error(y)}try{let y=await f.session(a.dbName,typedbDriver.SessionType.DATA);r.typeDB.set(a.id,{client:f,session:y});}catch(y){let B=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}})),this.schema=l,this.dbHandles=r;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),De(this.config,this.schema,this.dbHandles));query=async(r,l)=>{await this.#e();let a={...this.config,query:{...ke.query,...this.config.query,...l}};return Fe(r,a,this.schema,this.dbHandles)};mutate=async(r,l)=>{await this.#e();let a={...this.config,mutation:{...ke.mutation,...this.config.mutation,...l}};return St(r,a,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:r,session:l})=>{l.isOpen()&&await l.close(),await r.close();});}},vr=Ce;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
61
61
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
62
62
|
//! disabled as it has false positives
|
|
63
|
+
//!todo: use computeNode() in the future instead
|
|
63
64
|
|
|
64
|
-
module.exports =
|
|
65
|
+
module.exports = vr;
|
package/dist/index.mjs
CHANGED
|
@@ -1,62 +1,63 @@
|
|
|
1
|
-
import { tryit, mapEntries,
|
|
2
|
-
import { TypeDB, SessionType, TransactionType } from 'typedb-driver';
|
|
1
|
+
import { tryit, mapEntries, shake, isObject, isArray, parallel, listify, pick } from 'radash';
|
|
2
|
+
import { TypeDB, SessionType, TransactionType, TypeDBOptions } from 'typedb-driver';
|
|
3
3
|
import { produce, current } from 'immer';
|
|
4
4
|
import { traverse, getNodeByPath } from 'object-traversal';
|
|
5
5
|
import { v4 } from 'uuid';
|
|
6
6
|
|
|
7
|
-
var
|
|
8
|
-
`,Object.keys(
|
|
9
|
-
`;let
|
|
10
|
-
`,
|
|
11
|
-
`),
|
|
12
|
-
`,
|
|
7
|
+
var ke={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Nt=d=>{let r=[],l=new Map;return d.forEach(a=>{let{dbPath:F,contentType:f}=a,y=`${F}-${f}`;l.has(y)||(l.set(y,!0),r.push(a));}),r},De=async(d,r,l)=>{let F=(()=>{let c="",t=[];c+=`
|
|
8
|
+
`,Object.keys(r.entities).forEach(w=>{let k=r.entities[w],{idFields:q,dataFields:b,linkFields:T,name:L}=k,h=[],S=[],$=[];if(k.extends){let g=r.entities[k.extends];g.dataFields&&g.dataFields.forEach(m=>{h.push(m.dbPath);}),g.linkFields&&g.linkFields.forEach(m=>{S.push(m.path);}),g.idFields&&g.idFields.forEach(m=>{$.push(m);});}c+=`${L} sub ${k.extends?k.extends:"entity"},
|
|
9
|
+
`;let E=[];if(q&&q.length>0){let g=new Set(q),Q=Array.from(g).map(I=>`${I}`).join(", ");$.includes(Q)||(c+=` owns ${Q} @key,
|
|
10
|
+
`,E.push(Q));}if(b&&b.length>0&&b.forEach(g=>{!h.includes(g.dbPath)&&!E.includes(g.dbPath)&&(c+=` owns ${g.dbPath},
|
|
11
|
+
`),t.push({dbPath:g.dbPath,contentType:g.contentType});}),T&&T.length>0){let g=[];T.forEach(m=>{let{relation:Q,plays:I}=m;!S.includes(m.path)&&!g.includes(`${Q}:${I}`)&&(c+=` plays ${Q}:${I},
|
|
12
|
+
`,g.push(`${Q}:${I}`));});}c=c.replace(/,\s*$/,`;
|
|
13
13
|
`),c+=`
|
|
14
|
-
`;}),Object.keys(
|
|
15
|
-
`;let
|
|
16
|
-
`,
|
|
17
|
-
`),
|
|
18
|
-
`);}),
|
|
19
|
-
`,
|
|
14
|
+
`;}),Object.keys(r.relations).forEach(w=>{let k=r.relations[w],{idFields:q,dataFields:b,roles:T,name:L,linkFields:h}=k,S=[],$=[],E=[],g=[];if(k.extends){let Q=r.relations[k.extends];Q.dataFields&&Q.dataFields.forEach(I=>{S.push(I.dbPath);}),Q.linkFields&&Q.linkFields.forEach(I=>{$.push(I.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(O=>{E.push(O.name);}),Q.idFields&&Q.idFields.forEach(I=>{g.push(I);});}c+=`${L} sub ${k.extends?k.extends:"relation"},
|
|
15
|
+
`;let m=[];if(q&&q.length>0){let Q=new Set(q),O=Array.from(Q).map(j=>`${j}`).join(", ");g.includes(O)||(c+=` owns ${O} @key,
|
|
16
|
+
`,m.push(O));}if(b&&b.length>0&&b.forEach(Q=>{!S.includes(Q.dbPath)&&!m.includes(Q.dbPath)&&(c+=` owns ${Q.dbPath},
|
|
17
|
+
`),t.push({dbPath:Q.dbPath,contentType:Q.contentType});}),T&&Object.keys(T).forEach(Q=>{E.includes(Q)||(c+=` relates ${Q},
|
|
18
|
+
`);}),h&&h.length>0){let Q=[];h.forEach(I=>{let{plays:O}=I;!$.includes(I.path)&&!Q.includes(`${k}:${O}`)&&(c+=` plays ${I.relation}:${O},
|
|
19
|
+
`,Q.push(`${k}:${O}`));});}c=c.replace(/,\s*$/,`;
|
|
20
20
|
`),c+=`
|
|
21
|
-
`;});let
|
|
21
|
+
`;});let o=`define
|
|
22
22
|
|
|
23
|
-
`;return
|
|
24
|
-
`,
|
|
25
|
-
`:
|
|
26
|
-
`,
|
|
27
|
-
`):
|
|
28
|
-
`:
|
|
29
|
-
`:
|
|
30
|
-
`);}),`${
|
|
23
|
+
`;return Nt(t).forEach(w=>{o+=`${w.dbPath} sub attribute,
|
|
24
|
+
`,w.contentType==="TEXT"||w.contentType==="ID"?o+=` value string;
|
|
25
|
+
`:w.contentType==="EMAIL"?(o+=` value string,
|
|
26
|
+
`,o+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
27
|
+
`):w.contentType==="DATE"?o+=` value datetime;
|
|
28
|
+
`:w.contentType==="BOOLEAN"?o+=` value boolean;
|
|
29
|
+
`:w.contentType==="NUMBER"&&(o+=` value long;
|
|
30
|
+
`);}),`${o}
|
|
31
31
|
|
|
32
|
-
${c}`})(),p=l.dbConnectors[0].id,y=d.typeDB.get(p)?.session,b=d.typeDB.get(p)?.client;if(!y){console.log("Session Status: ","NO SESSION");return}await y.close();let[{dbName:E}]=l.dbConnectors;await(await b.databases.get(E)).delete(),await b.databases.create(E);let e=await b.session(l.dbConnectors[0].dbName,SessionType.SCHEMA),s=await e.transaction(TransactionType.WRITE);await s.query.define(w),await s.commit(),await s.close();let h=await e.transaction(TransactionType.READ);(await(await h.query.match("match $a sub thing;")).collect()).forEach(async c=>{c.get("a");}),await h.close();};var _t=(l,o,d)=>d?o:`${l}\xB7${o}`;var ft=(l,o)=>Object.values(Object.fromEntries(Object.entries(l).filter(([d,a])=>o(d,a))))[0],it=(l,o)=>Object.fromEntries(Object.entries(l).filter(([d,a])=>o(d,a))),Wt=l=>{let o=[],d=produce(l,w=>traverse(w,({key:p,value:y,meta:b})=>{if(b.depth===2&&(p&&(y.dataFields=y.dataFields?.map(E=>({...E,cardinality:E.cardinality||"ONE",dbPath:_t(p,E.path,E.shared)}))),y.extends)){let E=w.entities[y.extends]||w.relations[y.extends];if(y.allExtends=[y.extends,...E.allExtends||[]],y.idFields=E.idFields?(y.idFields||[]).concat(E.idFields):y.idFields,y.dataFields=E.dataFields?(y.dataFields||[]).concat(E.dataFields.map(A=>{let e=y.extends,s=l.entities[e]||l.relations[e];for(;!s.dataFields?.find(h=>h.path===A.path);)e=s.extends,s=l.entities[e]||l.relations[e];return {...A,dbPath:_t(e,A.path,A.shared)}})):y.dataFields,y.linkFields=E.linkFields?(y.linkFields||[]).concat(E.linkFields):y.linkFields,"roles"in E){let A=y,e=E;A.roles=A.roles||{},A.roles={...A.roles,...e.roles},Object.keys(A.roles).length===0&&(A.roles={});}}},{traversalType:"breadth-first"}));return traverse(l,({key:w,value:p,meta:y})=>{if(w==="linkFields"){let E=(()=>{if(!y.nodePath)throw new Error("No path");let[e,s]=y.nodePath.split(".");return {thing:s,thingType:e==="entities"?"entity":e==="relations"?"relation":""}})(),A=Array.isArray(p)?p.map(e=>({...e,...E})):[{...p,...E}];o.push(...A);}}),produce(d,w=>traverse(w,({value:p,key:y,meta:b})=>{if(b.depth===2&&p.idFields&&!p.id){p.name=y;let E=()=>{if(b.nodePath?.split(".")[0]==="entities")return "entity";if(b.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=E(),p.computedFields=[],p.virtualFields=[],p.requiredFields=[],p.enumFields=[],p.fnValidatedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([e,s])=>{s.playedBy=o.filter(h=>h.relation===y&&h.plays===e)||[],s.name=e;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(e=>{if(e.target==="relation"){e.oppositeLinkFieldsPlayedBy=[{plays:e.path,thing:e.relation,thingType:"relation"}];return}let s=o.filter(r=>r.relation===e.relation&&r.plays!==e.plays)||[];e.oppositeLinkFieldsPlayedBy=s;let{filter:h}=e;e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>r.target==="role"),h&&Array.isArray(h)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>h.some(u=>r.thing===u.$role)),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>h.some(u=>r.thing===u.$thing))),h&&!Array.isArray(h)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>r.$role===h.$role),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(r=>r.thing===h.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(E=>E.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${y} path:${b.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${y}, path:${b.nodePath}`)}if(b.depth===4){let[E,A]=b.nodePath?.split(".")||[],e=w[E][A];p.validations&&(p.validations.required&&e.requiredFields.push(p.path),p.validations.enum&&e.enumFields.push(p.path),p.validations.fn&&e.fnValidatedFields.push(p.path)),(p.default||p.computedValue)&&(p.isVirtual?e.virtualFields.push(p.path):e.computedFields.push(p.path));}}))},Rt=(l,o,d)=>{let a=D(l,o),w=a.linkFields?.find(b=>b.path===d);if(w)return w.cardinality;let p=a.dataFields?.find(b=>b.path===d);if(p)return p.cardinality;let y=a.roles[d];if(y)return y.cardinality},D=(l,o)=>{if(o.$thing){if(!o.$thingType)throw new Error("Missing $thingType in node$: {JSON.stringify(node, null, 2)");if(o.$thingType==="entity"){if(!(o.$thing in l.entities))throw new Error(`Missing entity '${o.$thing}' in the schema`);return l.entities[o.$thing]}if(o.$thingType==="relation"){if(!(o.$thing in l.relations))throw new Error(`Missing relation '${o.$thing}' in the schema`);return l.relations[o.$thing]}throw new Error(`Wrong schema or query for ${JSON.stringify(o,null,2)}`)}if(o.$entity){if(!(o.$entity in l.entities))throw new Error(`Missing entity '${o.$entity}' in the schema`);return l.entities[o.$entity]}if(o.$relation){if(!(o.$relation in l.relations))throw new Error(`Missing relation '${o.$relation}' in the schema`);return l.relations[o.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(o,null,2)}`)},J=(l,o)=>{let d=l.dataFields?.map(u=>u.path)||[],a=l.linkFields?.map(u=>u.path)||[],w="roles"in l?listify(l.roles,u=>u):[],p=[...d||[],...a||[],...w||[]],b=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!o)return {fields:p,dataFields:d,roleFields:w,linkFields:a};let E=o.$fields?o.$fields.map(u=>{if(typeof u=="string")return u;if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error(" Wrongly structured query")}):listify(o,u=>u),A=o.$filter?listify(o.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&d?.includes(u)):[],e=o.$filter?listify(o.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...w||[],...a||[]].includes(u)):[],s=[...E,...A].filter(u=>!b.includes(u)).filter(u=>u),h=o.$filter?it(o.$filter,(u,n)=>A.includes(u)):{},r=o.$filter?it(o.$filter,(u,n)=>e.includes(u)):{};return {fields:p,dataFields:d,roleFields:w,linkFields:a,usedFields:E,usedLinkFields:a.filter(u=>E.includes(u)),usedRoleFields:w.filter(u=>E.includes(u)),unidentifiedFields:s,...A.length?{localFilters:h}:{},...e.length?{nestedFilters:r}:{}}};var qt=l=>l!==null;var Ht=l=>{if(typeof l!="string")throw new Error("capitalizeFirstLetter: string is not a string");return l.charAt(0).toUpperCase()+l.slice(1).toLowerCase()};var Ut=async(l,o)=>{let{bqlRequest:d,config:a,tqlRequest:w}=l,{rawTqlRes:p}=o;if(d){if(!p)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:y}=d;if(!y){if(p.insertions?.length===0&&!w?.deletions){o.bqlRes={};return}let{mutation:b}=d;if(!b)throw new Error("TQL mutation not executed");let A=[...b.things,...b.edges].map(e=>{let s=p.insertions?.find(h=>h.get(`${e.$bzId}`))?.get(`${e.$bzId}`);if(e.$op==="create"||e.$op==="update"||e.$op==="link"){let h=s?.asThing().iid;return a.mutation?.noMetadata?mapEntries(e,(r,u)=>[r.toString().startsWith("$")?Symbol.for(r):r,u]):{$dbId:h,...e,[e.path]:e.$id}}if(e.$op==="delete"||e.$op==="unlink")return e;if(e.$op!=="match")throw new Error(`Unsupported op ${e.$op}`)}).filter(e=>e);o.bqlRes=A;return}};var Ue=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Ke=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Kt=l=>{let d=l.toString().replace(Ue,"").trim().split("=>")[0].split("{")[0].replace(Ke,"").trim(),a=d.substring(d.indexOf("(")+1,d.lastIndexOf(")")).trim();return a?(a.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(p=>p.includes("{")&&p.includes("}")?(p.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(b=>b.split(":")[0].trim().replace(/['"[\]]/g,"")):p.trim()).filter(Boolean):[]};var Z=({currentThing:l,fieldSchema:o,mandatoryDependencies:d=!1})=>{if(!o||!o.default||!("fn"in o.default||"value"in o.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${o}`);if(o.default.type==="value")return o.default.value;if(d){let{fn:w}=o.default,y=Kt(w).filter(b=>!(b in l));if(y.length)throw new Error(`Virtual field: Missing arguments ${y.join(", ")}`)}return "default"in o?o.default?.fn(l):void 0},Jt=()=>{};var Ze=(l,o)=>l.length===1&&typeof l[0]!="string"&&l[0].$id===o?l[0]:l,Yt=l=>typeof l=="string"||!!l.$show,Gt=(l,o)=>produce(l,d=>traverse(d,({value:a})=>{if(Array.isArray(a)||typeof a!="object"||a===null)return;a.$tempId&&(a.$tempId=`_:${a.$tempId}`),a.$fields&&delete a.$fields,a.$filter&&delete a.$filter,a.$show&&delete a.$show,a.$bzId&&delete a.$bzId,o.query?.noMetadata&&(a.$entity||a.$relation)&&(delete a.$entity,delete a.$relation,delete a.$id),Object.getOwnPropertySymbols(a).forEach(p=>{delete a[p];}),a.$excludedFields&&(a.$excludedFields.forEach(p=>{delete a[p];}),delete a.$excludedFields);})),Pt=(l,o,d,a)=>l.map(([w,p])=>{if(!o||!o.includes(w))return null;if(!d.$fields||d.$fields.includes(a))return w;let y=d.$fields.find(b=>isObject(b)&&b.$path===a);if(y){let b={...it(p,(A,e)=>A.startsWith("$"))},E=y.$fields?{...b,$fields:y.$fields}:b;if(y.$id){if(Array.isArray(y.$id))return y.$id.includes(w)?E:null;if(y.$id===w)return E}if(E.$fields&&E.$fields.includes("id")&&!E.$show){let A="";return E.$fields.forEach(e=>{e==="id"?A=E.$id:A=E;}),A}return E}return null}).filter(w=>w),Ye=(l,o)=>{let d={};return o.forEach(a=>{d[a.$bzId]=a.$id;}),l.forEach(a=>{Object.keys(a).forEach(w=>{d[a[w]]&&w!=="$tempId"&&(a[w]=d[a[w]]);});}),l},Ge=(l,o)=>{let d=o.map(w=>w.$bzId),a=!1;return l.forEach(w=>{Object.keys(w).forEach(p=>{d.includes(w[p])&&(a=!0);});}),a},ee=async(l,o)=>{let{bqlRequest:d,config:a,schema:w}=l,{cache:p}=o;if(!d)throw new Error("BQL request not parsed");let{query:y}=d;if(!y){let c=o.bqlRes[0]?o.bqlRes:[o.bqlRes],i=l.bqlRequest?.mutation?.things;if(Ge(c,i)){let F=Ye(c,i);o.bqlRes=F[1]?F:F[0];}let R=Gt(o.bqlRes,a);o.bqlRes=R;return}if(!p)return;let b="$entity"in y?y.$entity:y.$relation,E=p.entities.get(b.name);if(!E){o.bqlRes=null;return}let e=listify(y.$filter,c=>c).some(c=>b.dataFields?.find(i=>i.path===c)?.validations?.unique),s=!Array.isArray(d.query)&&(d.query?.$id&&!Array.isArray(d.query?.$id)||e);if(Array.isArray(l.rawBqlRequest))throw new Error("Query arrays not implemented yet");let h=E,r=[...h].length?[...h].map(([c,i])=>({...l.rawBqlRequest,$id:c})):l.rawBqlRequest,u=produce(r,c=>traverse(c,({value:i})=>{let t=i;if(!t?.$entity&&!t?.$relation)return;let R="$entity"in t?t.$entity:t.$relation;if(R){let F=Array.isArray(t.$id)?t.$id:[t.$id],T="$relation"in t?w.relations[t.$relation]:w.entities[t.$entity],{dataFields:O,roleFields:B,fields:k}=J(T);a.query?.returnNulls&&(t.$fields?t.$fields.map(m=>typeof m=="string"?m:m.$path):k).forEach(m=>{t[m]=null;});let M=p.entities.get(R);if(!M)return;[...M].forEach(([$,m])=>{if(F.includes($)){let q=t.$fields?t.$fields:O,{virtualFields:S}=T;S?.forEach(Q=>{if(q?.includes(Q)&&(t[Q]===void 0||t[Q]===null)){let I=T.dataFields?.find(x=>x.path===Q),N=Z({currentThing:m,fieldSchema:I});t[Q]=N;}}),listify(m,(Q,I)=>{Q.startsWith("$")||q?.includes(Q)&&(t[Q]=I);});let g=p.roleLinks.get($),L=t.$fields?t.$fields.filter(Q=>typeof Q=="string"):B,P=t.$fields?.filter(Q=>typeof Q=="object")?.map(Q=>Q.$path)||[];Object.entries(g||{}).forEach(([Q,I])=>{if(![...L,...P].includes(Q))return;if(!("roles"in T))throw new Error("No roles in schema");let N=Array.isArray(I)?[...new Set(I)]:[I],{cardinality:x,playedBy:v}=T.roles[Q],W=[...new Set(v?.map(C=>C.thing))]?.flatMap(C=>{let wt=p.entities.get(C);return wt?Pt([...wt],N,t,Q):[]});if(W?.length){if(W.length===1&&W[0]===t.$id)return;if(x==="ONE"){t[Q]=W[0];return}t[Q]=W.filter(C=>typeof C=="string"||typeof C=="object"&&C?.$show);}});}});let f=T.linkFields;f&&f.forEach($=>{let m=p.relations.get($.relation),q=$.oppositeLinkFieldsPlayedBy;if(!m)return null;if($.target==="relation"){let S=[...m].reduce((g,L)=>{let P=L.get($.plays)?.id;if(P&&P===F[0]){let Q=L.get($.relation);if(!Q)return g;g[Q.entityName]||(g[Q.entityName]=new Set),g[Q.entityName].add(Q.id);}return g},{});return Object.entries(S).map(([g,L])=>{let P=p.entities.get(g);if(!P)return null;let Q=Pt([...P],[...L.values()],t,$.path).filter(qt).filter(Yt);if(Q.length===0)return null;if(Q&&Q.length){if($.cardinality==="ONE")return t[$.path]=Q[0],null;t[$.path]=Q;}return null}),null}return $.target==="role"&&q.forEach(S=>{if(!m)return;let g=[...m].reduce((L,P)=>{let Q=P.get($.plays)?.id;if(Q&&Q===F[0]){let I=P.get(S.plays);if(!I)return L;L[I.entityName]||(L[I.entityName]=new Set),L[I.entityName].add(I.id);}return L},{});Object.entries(g).forEach(([L,P])=>{let Q=p.entities.get(L);if(!Q)return;let I=Pt([...Q],[...P.values()],t,$.path).filter(qt).filter(Yt);if(I.length!==0&&I&&I.length){if($.cardinality==="ONE"){t[$.path]=I[0];return}t[$.path]=I;let N={},x=Y=>(Y.$path===$.path&&(N=Y),Y?.$fields?.forEach(x)),v="";y.$fields?.forEach(x),N&&(Array.isArray(N.$id)||(v=N.$id)),t[$.path]=Ze(I,v);}});}),null});}})),n=Gt(u,a);o.bqlRes=s?n[0]:n;};var ie=async l=>{let{bqlRequest:o,schema:d}=l;if(!o)throw new Error("BQL request not parsed");let{mutation:a}=o;if(!a)throw new Error("BQL request is not a mutation");let w=r=>{let u=r.$op,n=`$${r.$bzId}`,c=D(d,r),{idFields:i,defaultDBConnector:t}=c,R=t?.path||r.$entity||r.$relation,F=r.$id,T=i?.[0],O=listify(r,(g,L)=>{if(g.startsWith("$")||g===T||L===void 0||L===null)return "";let P=c.dataFields?.find(N=>N.path===g);if(!P?.path)return "";let I=P.dbPath;if(["TEXT","ID","EMAIL"].includes(P.contentType))return `has ${I} '${L}'`;if(["NUMBER","BOOLEAN"].includes(P.contentType))return `has ${I} ${L}`;if(P.contentType==="DATE"){if(Number.isNaN(L.valueOf()))throw new Error("Invalid format, Nan Date");return L instanceof Date?`has ${I} ${L.toISOString().replace("Z","")}`:`has ${I} ${new Date(L).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${P.contentType}`)}).filter(g=>g),B=`${n}-atts`,k=listify(r,g=>{if(g.startsWith("$")||g===T)return "";let L=c.dataFields?.find(I=>I.path===g);if(!L?.path)return "";let Q=L.dbPath;return `{${B} isa ${Q};}`}).filter(g=>g),M=r[Symbol.for("isLocalId")],f=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,$=!M&&F?[`has ${T} ${f}`]:[],m=[...$,...O].filter(g=>g).join(","),q=()=>{if(u==="delete"||u==="unlink"||u==="match")return `${n} isa ${[R,...$].filter(g=>g).join(",")};`;if(u==="update"){if(!k.length)throw new Error("update without attributes");return `${n} isa ${[R,...$].filter(g=>g).join(",")}, has ${B};
|
|
33
|
-
${k.join(" or ")};`}return ""},S=()=>u==="update"||u==="link"||u==="match"?`${n} isa ${[R,...$].filter(g=>g).join(",")};`:"";if(r.$entity||r.$relation)return {op:u,deletionMatch:q(),insertionMatch:S(),insertion:u==="create"?`${n} isa ${[R,m].filter(g=>g).join(",")};`:u==="update"&&O.length?`${n} ${O.join(",")};`:"",deletion:u==="delete"?`${n} isa ${R};`:u==="update"&&k.length?`${n} has ${B};`:""};throw new Error("in attributes")},p=r=>{let u=r.$op,n=D(d,r),c=`$${r.$bzId}`,i=r.$id,t=n.defaultDBConnector?.path||r.$relation,R="roles"in n?listify(n.roles,g=>g):[],F=r.$relation&&"roles"in n&&mapEntries(n.roles,(g,L)=>[g,L.dbConnector?.path||g]),T=listify(r,(g,L)=>{if(!R.includes(g))return null;if(!("roles"in n))throw new Error("This should have roles! ");let P=F[g];return Array.isArray(L)?L.map(Q=>({path:P,id:Q})):{path:P,id:L}}).filter(g=>g).flat(),O=T.map(g=>{if(!g?.path)throw new Error("Object without path");return `${g.path}: $${g.id}`}),B=T.length>0?`( ${O.join(" , ")} )`:"",k=r[Symbol.for("edgeType")];if(!k)throw new Error("[internal error] Symbol edgeType not defined");let M=B?`${c} ${B} ${k==="linkField"||u==="delete"||u==="unlink"?`isa ${t}`:""}`:"",f=`${c} ${k==="linkField"||u==="delete"?`isa ${t}`:""}`,$=()=>M?u==="link"?`${M};`:u==="create"?`${M}, has id '${i}';`:"":"",m=()=>M&&u==="match"?`${M};`:"",q=()=>M?u==="delete"?`${M};`:u==="match"?`${M};`:"":"",S=()=>M?u==="delete"?`${f};`:u==="unlink"?`${c} ${B};`:"":"";return {deletionMatch:q(),insertionMatch:m(),deletion:S(),insertion:$(),op:""}},y=(r,u)=>{let n=u==="edges"?p:w;if(Array.isArray(r))return r.map(T=>{let{preDeletionBatch:O,insertionMatch:B,deletionMatch:k,insertion:M,deletion:f}=n(T);return shake({preDeletionBatch:O,insertionMatch:B,deletionMatch:k,insertion:M,deletion:f},$=>!$)}).filter(T=>T);let{preDeletionBatch:c,insertionMatch:i,deletionMatch:t,insertion:R,deletion:F}=n(r);return shake({preDeletionBatch:c,insertionMatch:i,deletionMatch:t,insertion:R,deletion:F},T=>!T)},b=y(a.things),E=Array.isArray(b)?b:[b],A=y(a.edges,"edges"),e=Array.isArray(A)?A:[A],s=[...E,...e],h=shake({insertionMatches:s.map(r=>r.insertionMatch).join(" ").trim(),deletionMatches:s.map(r=>r.deletionMatch).join(" ").trim(),insertions:s.map(r=>r.insertion).join(" ").trim(),deletions:s.map(r=>r.deletion).join(" ").trim()},r=>!r);l.tqlRequest=h;};var oi=l=>{if(!l.startsWith("_:"))throw new Error("ID must start with '_:'.");let o=l.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(o))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(l.length>36)throw new Error("$tempId must not be longer than 36 characters.");return o},re=async l=>{let{rawBqlRequest:o,schema:d}=l,w=(s=>produce(s,h=>traverse(h,({value:r,key:u,parent:n})=>{if(isObject(r)&&(r=shake(r,c=>c===void 0)),u==="$tempId"&&(n[u]=oi(r)),n&&isArray(r)){if(!r.some(i=>typeof i=="object"&&"$id"in i))return;let c=r.flatMap(i=>typeof i=="string"?i:typeof i=="object"&&"$id"in i&&isArray(i.$id)?i.$id.map(t=>({...i,$id:t})):i);n[u]=c;}})))(o),y=(s=>produce(s,h=>traverse(h,({value:r,meta:u,key:n})=>{if(isObject(r)){if(r.$arrayOp)throw new Error("Array op not supported yet");if(n==="$filter"||u.nodePath?.includes(".$filter."))return;let c=r;if(c.$op==="create"&&c.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let i=D(d,c),R=u.nodePath?.split(".")?.filter(f=>Number.isNaN(parseInt(f,10))).join(".");if(!i)throw new Error(`Schema not found for ${c.$entity||c.$relation}`);c.$bzId=c.$tempId??`T_${v4()}`,c[Symbol.for("schema")]=i,c[Symbol.for("dbId")]=i.defaultDBConnector.id;let{usedLinkFields:F,usedRoleFields:T}=J(i,c),O=F.map(f=>({fieldType:"linkField",path:f,schema:i.linkFields.find($=>$.path===f)})),B=i.thingType==="relation"?T.map(f=>({fieldType:"roleField",path:f,schema:ft(i.roles,$=>$===f)})):[];if(O.some(f=>f.schema?.target==="role")&&O.some(f=>f.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let k=B.filter(f=>[...new Set(f.schema.playedBy?.map($=>$.thing))].length!==1);if(k.length>1)throw new Error(`Field: ${k[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(k[0].schema.playedBy)}. Schema: ${JSON.stringify(k[0].schema)}`);let M=u.nodePath;if([...O,...B].forEach(f=>{let $=c[f.path];if($===void 0)return;let m=f.schema;if(!m)throw new Error(`Field ${f.path} not found in schema`);let q=f.fieldType==="roleField"?m?.playedBy[0]:m,g=m&&"relation"in m&&q?.relation===c.$relation?"$self":q?.relation?q?.relation:"$self",L=g==="$self"?i:d.relations[g];if(ft(L.roles,(v,Y)=>v===f.path)?.playedBy?.length===0)throw new Error(`unused role: ${M}.${f.path}`);if(!m)throw new Error(`Field ${f.path} not found in schema`);let Q=f.fieldType==="linkField"?m?.oppositeLinkFieldsPlayedBy:m?.playedBy;if(!Q)throw new Error(`No opposite fields found for ${JSON.stringify(m)}`);if([...new Set(Q?.map(v=>v.thing))].length>1)throw new Error(`Field: ${f.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(Q)}. Schema: ${JSON.stringify(m)}`);if(m.cardinality==="ONE"&&Array.isArray($))throw new Error("Can't have an array in a cardinality === ONE link field");if(m.cardinality==="MANY"&&$!==null&&!Array.isArray($)&&!$.$arrayOp)throw new Error(`${f.fieldType==="linkField"?m.path:m.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if($?.$entity||$?.$relation)return;let[I]=Q,N="plays"in m?"linkField":"roleField",x={[`$${I.thingType}`]:I.thing,[Symbol.for("relation")]:g,[Symbol.for("edgeType")]:N,[Symbol.for("parent")]:{path:M,...c.$id?{$id:c.$id}:{},...c.$tempId?{$tempId:c.$tempId}:{},...c.filter?{filter:c.filter}:{},links:Q},[Symbol.for("role")]:I.plays,[Symbol.for("oppositeRole")]:"plays"in m?m.plays:void 0,[Symbol.for("relFieldSchema")]:m};if(isObject($)&&(c[f.path]={...x,...$}),Array.isArray($))if($.every(v=>isObject(v)))c[f.path]=$.map(v=>({...x,...v}));else if($.every(v=>typeof v=="string"))c[f.path]=$.map(v=>({...x,$op:c.$op==="create"?"link":"replace",$id:v}));else throw new Error(`Invalid array value for ${f.path}`);if(typeof $=="string"&&(c[f.path]={...x,$op:c.$op==="create"?"link":"replace",$id:$}),$===null){let v={...x,$op:"unlink"};c[f.path]=m.cardinality==="MANY"?[v]:v;}}),!R&&!c.$entity&&!c.$relation)throw new Error("Root things must specify $entity or $relation")}})))(w),E=(s=>produce(s,h=>traverse(h,({parent:r,key:u,value:n,meta:c})=>{if(isObject(n)){if(Object.keys(n).length===0)throw new Error("Empty object!");if(u==="$filter"||c.nodePath?.includes(".$filter."))return;let i=n,t=c.nodePath?.split(".");if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$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.`);let R=t?.filter(P=>Number.isNaN(parseInt(P,10))).join("."),F=R?Array.isArray(r)?t?.slice(0,-1).join("."):c.nodePath:c.nodePath||"",T=D(d,i),{dataFields:O,roleFields:B,linkFields:k}=J(T,i),M=current(i)[Symbol.for("parent")],f=R&&M.path,m=(f?getNodeByPath(h,f):h)?.$op;if(R&&!m)throw new Error("Error: Parent $op not detected");let q=i[Symbol.for("relFieldSchema")];i.$op==="replace"&&m==="create"&&(i.$op="link");let S=Object.keys(i).some(P=>O?.includes(P)),g=Object.keys(i).some(P=>[...B,...k].includes(P)),L=()=>{if(i.$op)return i.$op;if(R&&!i.$id&&!i.$tempId&&m!=="create"&&q.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${c.nodePath}`);if(i.$tempId)return "create";if((i.$id||i.$filter)&&S)return "update";if((i.$id||i.$filter)&&R&&!S&&!g)return "link";if(!i.$filter&&!i.$id&&!i.$tempId)return "create";if((i.$id||i.$filter)&&!S&&g)return "match";throw new Error("Wrong op")};if(i.$op||(i.$op=L()),r||(i.$parentKey=""),typeof r=="object"&&(Array.isArray(r)&&(i[Symbol.for("index")]=u),i[Symbol.for("path")]=F,i[Symbol.for("isRoot")]=!R,i[Symbol.for("depth")]=R?.split(".").length),!i.$entity&&!i.$relation)throw new Error(`Node ${JSON.stringify(i)} without $entity/$relation`)}})))(y),e=(s=>produce(s,h=>traverse(h,({value:r})=>{if(isObject(r)){let u=r,n=D(d,u),{unidentifiedFields:c}=J(n,u),{idFields:i}=n;if(!i)throw new Error("No idFields found");let[t]=i;if(u.$op==="create"&&!u[t]){let R=n.dataFields?.find(T=>T.path===t),F=Z({currentThing:u,fieldSchema:R,mandatoryDependencies:!0});if(typeof F!="string")throw new Error(`Default id field ${t} is not a string`);u[t]=F,u.$id=F;}if(c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(u)}`)}})))(E);l.filledBqlRequest=e;};var le=async l=>{let{filledBqlRequest:o,schema:d}=l,a=e=>{let s=[],h=[],r=i=>{if(i.$id)return i.$id;let t=D(d,i),{idFields:R}=t;if(!R)throw new Error(`no idFields: ${JSON.stringify(i)}`);let[F]=R;if(!F)throw new Error(`no idField: ${JSON.stringify(i)}`);let T=t.dataFields?.find(k=>k.path===F),O=Z({currentThing:i,fieldSchema:T,mandatoryDependencies:!0}),B=i[F]||i.$id||O;if(!B)throw new Error(`no idValue: ${JSON.stringify(i)}`);return B},u=i=>{if(i.$op==="create"){let t=r(i);if(s.find(R=>R.$id===t))throw new Error(`Duplicate id ${t} for node ${JSON.stringify(i)}`);if(h.find(R=>R.$bzId===i.$bzId))throw new Error(`Duplicate $bzid ${i.$bzId} for node ${JSON.stringify(i)}`);s.push({...i,$id:t});return}i.$tempId&&i.$op==="match"||s.push(i);},n=i=>{if(i.$op==="create"){let t=r(i);if(s.find(R=>R.$id===t),h.find(R=>R.$bzId===i.$bzId))throw new Error(`Duplicate %bzId ${i.$bzIdd} for edge ${JSON.stringify(i)}`);h.push({...i,$id:t});return}h.push(i);};return traverse(e,({value:i})=>{if(!isObject(i))return;let t=i;if(t.$entity||t.$relation){if(!t.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(t)}`);if(!t.$bzId)throw new Error("[internal error] BzId not found");let R=D(d,t),{dataFields:F,roleFields:T,linkFields:O,usedFields:B}=J(R,t),k=()=>{if(t.$op==="create"||t.$op==="delete")return t.$op;if(t.$op==="update"){let f=B.filter(q=>F?.includes(q)),$=B.filter(q=>T?.includes(q)),m=B.filter(q=>O?.includes(q));if(f.length>0)return "update";if($.length>0||m.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(t)}`)}return "match"},M={...t.$entity&&{$entity:t.$entity},...t.$relation&&{$relation:t.$relation},...t.$id&&{$id:t.$id},...t.$tempId&&{$tempId:t.$tempId},...t.$filter&&{$filter:t.$filter},...shake(pick(t,F||[""])),$op:k(),$bzId:t.$bzId,[Symbol.for("dbId")]:R.defaultDBConnector.id,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("isRoot")]:t[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:t[Symbol.for("isLocalId")]||!1};if(u(M),t[Symbol.for("relation")]&&t[Symbol.for("edgeType")]==="linkField"){if((t.$op==="link"||t.$op==="unlink")&&(t.$id||t.$filter)){if(t.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");s.push({...t,$op:"match"});}let f=t[Symbol.for("relation")]===t.$relation,$=f?t.$bzId:v4(),q=t[Symbol.for("parent")].path,g=(q?getNodeByPath(e,q):e).$bzId;if(!g)throw new Error("No parent id found");if(t[Symbol.for("relation")]==="$self")return;let L=()=>{if(t.$op==="delete")return f?"match":"delete";if(t.$op==="unlink")return f?"unlink":"delete";if(t.$op==="link"||t.$op==="create")return f?"link":"create";if(t.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},P={$relation:t[Symbol.for("relation")],$bzId:$,...t.$tempId?{$tempId:t.$tempId}:{},$op:L(),...f?{}:{[t[Symbol.for("role")]]:t.$bzId},[t[Symbol.for("oppositeRole")]]:g,[Symbol.for("dbId")]:d.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]};n(P),(t.$op==="unlink"||L()==="unlink")&&f&&n({$relation:t[Symbol.for("relation")],$bzId:$,$op:"match",[t[Symbol.for("oppositeRole")]]:g,[Symbol.for("dbId")]:d.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]});}if(t.$relation){let f=it(t,(q,S)=>T.includes(q)),$=mapEntries(f,(q,S)=>isArray(S)?[q,S]:isObject(S)?[q,S.$bzId]:[q,S]),m=it(i,(q,S)=>q.startsWith("$")||q.startsWith("Symbol"));if(Object.keys(f).filter(q=>!q.startsWith("$")).length>0){if(t.$op==="create"||t.$op==="delete"){let q=()=>{if(t.$op==="create")return "link";if(t.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=mapEntries($,(L,P)=>Array.isArray(P)?[L,P.map(Q=>Q.$bzId||Q)]:[L,P.$bzId||P]),g={...m,$relation:t.$relation,$op:q(),...S,$bzId:t.$bzId,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("dbId")]:R.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};n(g);return}if(t.$op==="match"||t.$op==="update"&&Object.keys(f).length>0){let q=0;Object.entries(f).forEach(([S,g])=>{let L=isArray(g)?g:[g],P=Q=>Q==="create"||Q==="replace"?"link":Q;L.forEach(Q=>{if(!Q)return;let I=P(Q.$op);if(I==="replace")throw new Error("Not supported yet: replace on roleFields");if(I==="unlink"&&q>0)throw q+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let N={...m,$relation:t.$relation,$op:I==="delete"?"unlink":I,[S]:Q.$bzId,$bzId:t.$bzId,[Symbol.for("dbId")]:R.defaultDBConnector.id,[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};n(N);});});}}}}}),[s,h]};if(!o)throw new Error("Undefined filledBqlRequest");let [w,p]=a(o),y=w.reduce((e,s)=>{if(!s.$bzId)return [...e,s];let h=e.findIndex(r=>r.$bzId===s.$bzId);if(h===-1)return [...e,s];if(e[h].$op==="create"&&s.$op==="match")return e;if(e[h].$op==="match"&&(s.$op==="create"||s.$op==="match"))return [...e.slice(0,h),s,...e.slice(h+1)];throw new Error(`Unsupported operation combination for $tempId "${s.$tempId}". Existing: ${e[h].$op}. Current: ${s.$op}`)},[]),b=p.reduce((e,s)=>{let h=e.find(r=>(r.$id&&r.$id===s.$id||r.$bzId&&r.$bzId===s.$bzId)&&r.$relation===s.$relation&&r.$op===s.$op);if(h){let r={...h};return Object.keys(s).forEach(n=>{if(typeof n=="symbol"||n.startsWith("$"))return;let c=h[n],i=s[n];Array.isArray(c)&&Array.isArray(i)?r[n]=Array.from(new Set([...c,...i])):!Array.isArray(c)&&Array.isArray(i)?c!==void 0?r[n]=Array.from(new Set([c,...i])):r[n]=i:Array.isArray(c)&&!Array.isArray(i)?i!==void 0&&(r[n]=Array.from(new Set([...c,i]))):c!==null&&i!==null&&c!==void 0&&i!==void 0?r[n]=Array.from(new Set([c,i])):c==null&&(r[n]=i);}),[...e.filter(n=>!((n.$id&&n.$id===s.$id||n.$bzId&&n.$bzId===s.$bzId)&&n.$relation===s.$relation&&n.$op===s.$op)),r]}return [...e,s]},[]);[...new Set(b.map(e=>e.$relation))];l.bqlRequest={mutation:{things:y,edges:b}};};var ut=async(l,o)=>{let d=o.dbConnectors[0].id,a=l.typeDB.get(d)?.session,w=l.typeDB.get(d)?.client;if(!a||!a.isOpen()){if(!w)throw new Error("Client not found");a=await w.session(o.dbConnectors[0].dbName,SessionType.DATA),l.typeDB.set(d,{client:w,session:a});}return {client:w,session:a}};var de=async(l,o)=>{let{dbHandles:d,tqlRequest:a,bqlRequest:w,config:p}=l;if(!a)throw new Error("TQL request not built");if(!(a.deletions&&a.deletionMatches||a.insertions))throw new Error("TQL request error, no things");if(!w?.mutation)throw new Error("BQL mutation not parsed");let{session:y}=await ut(d,p),b=await y.transaction(TransactionType.WRITE);if(!b)throw new Error("Can't create transaction");let E=a.deletionMatches&&a.deletions&&`match ${a.deletionMatches} delete ${a.deletions}`,A=a.insertions&&`${a.insertionMatches?`match ${a.insertionMatches}`:""} insert ${a.insertions}`;E&&await b.query.delete(E);let e=A&&b.query.insert(A);try{let s=e?await e.collect():void 0;await b.commit(),await b.close(),o.rawTqlRes={insertions:s};}catch(s){throw await b.close(),new Error(`Transaction failed: ${s.message}`)}};var bt=Symbol.for("schema"),K=Symbol.for("queryPath");var H="___",ce=async l=>{let{enrichedBqlQuery:o}=l;if(!o)throw new Error("BQL query not enriched");let d="",a=(e,s)=>{let h="",r="";for(let u in e){let n=e[u];if(Array.isArray(n))for(let c=0;c<n.length;c++)r+=`{$${s} has ${u} "${n[c]}";}`,c<n.length-1?r+="or":r+=";";else h+=`, has ${u} "${n}"`;}h+=`;
|
|
34
|
-
`,
|
|
35
|
-
`;n
|
|
36
|
-
`,
|
|
37
|
-
`,
|
|
38
|
-
`,
|
|
39
|
-
`,
|
|
40
|
-
`,
|
|
41
|
-
;`;let
|
|
42
|
-
`;}},y=(e,s,
|
|
43
|
-
`,
|
|
44
|
-
`,
|
|
45
|
-
`:
|
|
46
|
-
`,
|
|
47
|
-
`,
|
|
48
|
-
`,
|
|
49
|
-
;`;let
|
|
50
|
-
`;}},
|
|
51
|
-
$${
|
|
52
|
-
`,
|
|
53
|
-
`,
|
|
54
|
-
;`,
|
|
55
|
-
$${
|
|
56
|
-
`,
|
|
57
|
-
`,
|
|
58
|
-
;`,n){let i=n.filter(F=>F.$fieldType==="data");i&&i.length>0&&w(i,h);let t=n.filter(F=>F.$fieldType==="link");t&&t.length>0&&y(t,h,h);let R=n.filter(F=>F.$fieldType==="role");R&&R.length>0&&p(R,h,h);}}})(o),l.tqlRequest=b?E:d;};var It=l=>{let o=l.dataFields?.map(p=>p.path)||[],d=l.linkFields?.map(p=>p.path)||[],a=Object.keys(l.roles||{})||[];return [...o,...d,...a]},Ct=(l,o)=>Object.keys(l||{}).some(a=>{if(!Array.isArray(l[a])){let w=o.idFields?.includes(a),p=o.dataFields?.some(y=>(y.dbPath===a||y.path===a)&&y?.validations?.unique);return w||p}return !1}),Nt=(l,o)=>{let d=o.dataFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],a=o.linkFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],w=Object.keys(o.roles||{}).map(y=>({path:y,dbPath:y}))||[],p=[...d,...a,...w];return Object.entries(l||{}).reduce((y,[b,E])=>{let A=p.find(e=>e.path===b);return y[A?.dbPath||b]=E,y},{})},ue=async l=>{let{rawBqlRequest:o,schema:d}=l;if(Array.isArray(o)){for(let e of o)if(!("$entity"in e)&&!("$relation"in e)&&(!("$thing"in e)||!("$thingType"in e)))throw new Error("No entity specified in query")}else if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let a=(e,s)=>typeof s=="string"?e.idFields?.includes(s):e.idFields?.includes(s.$path),w=(e,s,h,r,u)=>({$path:s,$dbPath:r,$thingType:"attribute",$as:e.$as||s,$var:s,$fieldType:"data",$excludedFields:e.$excludedFields,$justId:h,$id:e.$id,$filter:e.$filter,$isVirtual:u,$filterProcessed:!0}),p=(e,s,h,r,u)=>{let{target:n,oppositeLinkFieldsPlayedBy:c}=h;return c.map(i=>{let t=n==="role"?i.thingType:"relation",R=n==="role"?i.thing:h.relation,F={[`$${t}`]:R},T=D(d,F),O=e?.$fields?.filter(k=>a(T,k)).length===0,B=[];return typeof e!="string"?e.$fields?O?B=[...e.$fields,...T.idFields]:B=e.$fields:B=It(T):B=["id"],e.$excludedFields&&(B=B.filter(k=>a(T,k)?!0:!e.$excludedFields.includes(k.$path))),{$thingType:t,$plays:h.plays,$playedBy:i,$path:i.path,$dbPath:u,$as:e.$as||s,$var:s,$thing:R,$fields:B,$excludedFields:e.$excludedFields,$fieldType:"link",$target:n,$intermediary:i.relation,$justId:r,$id:e.$id,$filter:Nt(e.$filter,T),$idNotIncluded:O,$filterByUnique:Ct(e.$filter,T),$filterProcessed:!0}})},y=(e,s,h,r,u)=>h.playedBy.map(n=>{let{thing:c,thingType:i,relation:t}=n,R={[`$${i}`]:c},F=D(d,R),T=e?.$fields?.filter(B=>F?.idFields?.includes(B)||F?.idFields?.includes(B.$path)).length===0,O=[];return typeof e!="string"?e.$fields?T?O=[...e.$fields,...F.idFields]:O=e.$fields:O=It(F):O=["id"],e.$excludedFields&&(O=O.filter(B=>a(F,B)?!0:!e.$excludedFields.includes(B.$path))),{$thingType:i,$path:s,$dbPath:u,$as:e.$as||s,$var:s,$thing:c,$fields:O,$excludedFields:e.$excludedFields,$fieldType:"role",$intermediary:t,$justId:r,$id:e.$id,$filter:Nt(e.$filter,F),$idNotIncluded:T,$filterByUnique:Ct(e.$filter,F),$playedBy:n,$filterProcessed:!0}}),b=(e,s)=>{let h=typeof e=="string"?e:e.$path,r=typeof e=="string",u=s.dataFields?.find(i=>i.path===h),n=s.linkFields?.find(i=>i.path===h),c=s.roles?.[h];return u?w(e,h,r,u.dbPath,u.isVirtual):n?p(e,h,n,r,n.dbPath):c?y(e,h,c,r,c.dbPath):null},A=(e=>produce(e,s=>traverse(s,h=>{let{value:r,meta:u}=h,n=r;if(isObject(n)){if(n.$id){let c=n.$entity||n.$relation?n:{[`$${n.$thingType}`]:n.$thing},i=D(d,c);if(n.$path=i.name,Array.isArray(n.$id)||(n.$filterByUnique=!0),i?.idFields?.length===1){let[t]=i.idFields;n.$filter={...n.$filter,[t]:n.$id},delete n.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in n||"$relation"in n){let c=D(d,n);n.$path=c.name,n.$as=c.name;}if(n.$entity?(n.$thing=n.$entity,n.$thingType="entity",delete n.$entity):n.$relation&&(n.$thing=n.$relation,n.$thingType="relation",delete n.$relation),isObject(n)&&"$thing"in n){let c=n.$entity||n.$relation?n:{[`$${n.$thingType}`]:n.$thing};n[K]=u.nodePath;let i=D(d,c);if(n.$filter&&(n.$filterByUnique=Ct(n.$filter,i),n.$filterProcessed||(n.$filter=Nt(n.$filter,i))),n.$fields){n.$fields.filter(F=>i?.idFields?.includes(F)||i?.idFields?.includes(F.$path)).length>0||(n.$fields=[...n.$fields,...i.idFields],n.$idNotIncluded=!0);let R=n.$fields?.flatMap(F=>{let T=b(F,i);return Array.isArray(T)?T:[T]}).filter(Boolean);n.$fields=R;}else {let R=It(i)?.flatMap(F=>{let T=b(F,i);return Array.isArray(T)?T:[T]}).filter(Boolean);n.$fields=R;}n.$excludedFields&&(n.$fields=n.$fields.filter(t=>a(i,t)?!0:!n.$excludedFields.includes(t.$path)));}}})))(Array.isArray(o)?o:[o]);l.enrichedBqlQuery=A;};var ye=async(l,o)=>{let{dbHandles:d,enrichedBqlQuery:a,tqlRequest:w,config:p}=l;if(!a)throw new Error("BQL request not parsed");if(!w)throw new Error("TQL request not built");if(Array.isArray(w)){let b=await parallel(w.length,w,async E=>{let{session:A}=await ut(d,p),e=await A.transaction(TransactionType.READ);if(!e)throw new Error("Can't create transaction");let h=await e.query.fetch(E).collect();return await e.close(),h});o.rawTqlRes=b,o.isBatched=!0;}else {let{session:b}=await ut(d,p),E=await b.transaction(TransactionType.READ);if(!E)throw new Error("Can't create transaction");let e=await E.query.fetch(w).collect();await E.close(),o.rawTqlRes=e;}};var he=l=>{let o=/as:([a-zA-Z0-9_\-·]+)/,d=/justId:([a-zA-Z0-9_\-·]+)/,a=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,w=/filterByUnique:([a-zA-Z0-9_\-·]+)/,p=l.match(o),y=l.match(d),b=l.match(a),E=l.match(w);return {as:p?p[1]:null,justId:y?y[1]:null,idNotIncluded:b?b[1]:null,filterByUnique:E?E[1]:null}},mi=l=>{try{let d=(w=>{let p=w.replace("$metadata:","");return p=p.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),p=p.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(y,b,E)=>/^{.*}$/.test(E)?`:${E}`:`:${b}"${E}"`),p=p.replace(/\[([^\]]+)\]/g,(y,b)=>`[${b.split(",").map(E=>E.trim().startsWith("{")&&E.trim().endsWith("}")?E.trim():`"${E.trim()}"`).join(",")}]`),p})(l);return JSON.parse(d)}catch(o){return console.error(o),{as:[],virtual:[]}}},$e=async(l,o)=>{let{enrichedBqlQuery:d,rawBqlRequest:a,schema:w,config:p}=l,{rawTqlRes:y,isBatched:b}=o;if(d){if(!y)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let E=(n,c)=>{let{$metaData:i}=n,{as:t}=mi(i),R=Object.entries(n).filter(([F])=>F!=="type"&&!F.includes("$")).map(([F,T])=>{let O=c.dataFields?.find(f=>f.path===F||f.dbPath===F),B=F==="id",k=Array.isArray(t)?t.find(f=>f[F])?.[F]:F,M;if(O?.cardinality==="ONE"){if(M=T[0]?T[0].value:p.query?.returnNulls?null:void 0,O.contentType==="DATE"&&(M=`${M}Z`),B)return [[k,M],["$id",M]].filter(([f,$])=>$!==void 0)}else if(O?.cardinality==="MANY"){if(!isArray(T))throw new Error("Typedb fetch has changed its format");O.contentType==="DATE"?M=T.map(f=>`${f.value}Z`):M=T.map(f=>f.value);}return [[k,M]].filter(([f,$])=>$!==void 0)}).flat();return Object.fromEntries([...R])},A=n=>n.reduce((c,i)=>{let{$roleFields:t,$metaData:R,$cardinality:F}=i,{as:T,justId:O,idNotIncluded:B,filterByUnique:k}=he(R),M=t.map(f=>{let{dataFields:$,currentSchema:m,linkFields:q,roleFields:S,schemaValue:g}=s(f),L=E($,m);if(O==="T")return L.id;{let P=e(q),Q=A(S),I={...L};return B==="true"&&m?.idFields?.forEach(N=>delete I[N]),{...I,...P,...Q,...g}}});return M.length>0?c[T]=F==="MANY"&&k==="false"?M:M[0]:p.query?.returnNulls&&(c[T]=null),c},{}),e=n=>n.reduce((c,i)=>{let{$linkFields:t,$metaData:R,$cardinality:F}=i,{as:T,justId:O,idNotIncluded:B,filterByUnique:k}=he(R),M=t.map(f=>{let{dataFields:$,currentSchema:m,linkFields:q,roleFields:S,schemaValue:g}=s(f),L=E($,m);if(O==="T")return L.id;{let P=e(q),Q=A(S),I={...L};return B==="true"&&m.idFields?.forEach(N=>delete I[N]),{...I,...P,...Q,...g}}});return c[T]=M.length>0?F==="MANY"&&k==="false"?M:M[0]:p.query?.returnNulls?null:void 0,c},{}),s=n=>{let c=Object.keys(n),i=c.find(f=>f.endsWith(".$dataFields"));if(!i)throw new Error("No datafields");let t=n[i],R=i.split(".")[i.split(".").length-2];if(t.$metaData=R,t.length===0)throw new Error("No datafields");let F=t.type,T={$thing:F.label,$thingType:F.root,[K]:n.queryPath.value},O={[`$${T.$thingType}`]:T.$thing},B=D(w,O),k=c.filter(f=>!f.endsWith(".$dataFields")&&B.linkFields?.some($=>$.path===f.split(".").pop())).map(f=>({$linkFields:n[f],$key:f.split(".").pop(),$metaData:f.split(".")[f.split(".").length-2],$cardinality:B?.linkFields?.find($=>$.path===f.split(".").pop())?.cardinality})),M=c.filter(f=>!f.endsWith(".$dataFields")&&B.roles?.[f.split(".").pop()]).map(f=>({$roleFields:n[f],$key:f.split(".").pop(),$metaData:f.split(".")[f.split(".").length-2],$cardinality:B.roles[f.split(".").pop()].cardinality}));return {dataFields:t,schemaValue:T,currentSchema:B,linkFields:k,roleFields:M}},h=n=>n.map(c=>{let{dataFields:i,currentSchema:t,linkFields:R,roleFields:F,schemaValue:T}=s(c),O=E(i,t),B=e(R),k=A(F),M=a?.$fields?.every($=>!t?.idFields?.includes($)&&!t?.idFields?.includes($.$path));return {...B,...k,...T,...!p.query?.noMetadata&&a.$id?{$id:Array.isArray(a.$id)?O.id:a.$id}:{},...M?Object.fromEntries(Object.entries(O).filter(([$])=>!t?.idFields?.includes($))):O}}),u=(n=>{let c=i=>{let t=h(i);return a.$id&&!Array.isArray(a.$id)||d[0].$filterByUnique?t[0]??null:t.length===0?null:t};return b?n.map(c):c(n)})(y);o.bqlRes=u;};var gi=Symbol.for("grandChildOfCreate"),rt=l=>({...l[Symbol.for("relation")]&&{[Symbol.for("relation")]:l[Symbol.for("relation")]},...l[Symbol.for("parent")]&&{[Symbol.for("parent")]:l[Symbol.for("parent")]},...l[Symbol.for("edgeType")]&&{[Symbol.for("edgeType")]:l[Symbol.for("edgeType")]},...l[Symbol.for("role")]&&{[Symbol.for("role")]:l[Symbol.for("role")]},...l[Symbol.for("oppositeRole")]&&{[Symbol.for("oppositeRole")]:l[Symbol.for("oppositeRole")]},...l[Symbol.for("relFieldSchema")]&&{[Symbol.for("relFieldSchema")]:l[Symbol.for("relFieldSchema")]},...l[Symbol.for("path")]&&{[Symbol.for("path")]:l[Symbol.for("path")]},...l[Symbol.for("isRoot")]&&{[Symbol.for("isRoot")]:l[Symbol.for("isRoot")]},...l[Symbol.for("depth")]&&{[Symbol.for("depth")]:l[Symbol.for("depth")]},...l[Symbol.for("schema")]&&{[Symbol.for("schema")]:l[Symbol.for("schema")]},...l[Symbol.for("dbId")]&&{[Symbol.for("dbId")]:l[Symbol.for("dbId")]},...l[Symbol.for("index")]&&{[Symbol.for("index")]:l[Symbol.for("index")]}}),me=async l=>{let{filledBqlRequest:o,config:d,schema:a}=l,w=(B,k)=>Object.keys(B).filter(M=>M.startsWith("$")?!1:k?!D(a,B).dataFields?.find($=>$.path===M):!0);if(!o)throw new Error("[BQLE-M-PQ-1] No filledBqlRequest found");if(d.mutation?.preQuery===!1)return;let p=[];if(traverse(o,({parent:B,key:k,value:M})=>{B&&k&&!k.includes("$")&&isObject(B)?(Array.isArray(B[k])?B[k]:[B[k]]).forEach($=>{if(isObject($)){if(B.$op!=="create")p.includes($.$op)||p.push($.$op);else if($.$op==="delete"||$.$op==="unlink")throw new Error(`Cannot ${$.$op} under a create`)}}):!B&&isObject(M)&&(p.includes(M.$op)||p.push(M.$op));}),!p.includes("delete")&&!p.includes("unlink")&&!p.includes("replace")&&!p.includes("update")&&!p.includes("link"))return;let b=(B=>{let k=(M,f)=>{let $=[],m={},q=["$op","$bzId","$parentKey"],S=["$relation","$entity","$id",...q];for(let g in M)if(!q.includes(g)&&!(S.includes(g)&&!f))if(!g.includes("$")&&(isObject(M[g])||Array.isArray(M[g]))){let L=M[g];Array.isArray(L)&&L.length>0?L.forEach(P=>{$.push({$path:g,...k(P)});}):$.push({$path:g,...k(L)});}else m[g]=M[g];return {...m,$fields:$}};return B.map(M=>k(M,!0))})(Array.isArray(o)?o:[o]),E=await Ft(b,l.config,l.schema,l.dbHandles),A=(B,k)=>{let M=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:f}=B,$=f?.beforePath||"root",m=Array.isArray(f.ids)?`[${f.ids}]`:f.ids;return {beforePath:`${$}.${m}___${f.key}`,ids:M,key:k}}else return {beforePath:"root",ids:M,key:k}},e=(B,k)=>{let M=B?.beforePath||"root",f=k||(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${M}.${f}___${B?.key}`},s=B=>{if(B.includes("[")&&B.includes("]")){let[k,M,f]=B.split(/[[\]]/);return M.split(",").map(m=>`${k}${m}${f}`)}else return [B]},h={};(B=>produce(B,k=>traverse(k,M=>{let{key:f,parent:$}=M;if($&&f&&$.$id&&!f.includes("$")){let m=A($,f),q=e(m);if(Array.isArray($[f])){let S=[];$[f].forEach(g=>{isObject(g)?(g.$objectPath=m,S.push(g.$id.toString())):g&&S.push(g.toString());}),h[q]={$objectPath:m,$ids:S};}else {let S=$[f];isObject(S)?(h[q]={$objectPath:m,$ids:[S.$id.toString()]},S.$objectPath=m):S&&(h[q]={$objectPath:m,$ids:[S.toString()]});}}})))(E||{});let u=B=>produce(B,k=>traverse(k,M=>{let{key:f,value:$,parent:m}=M;m&&f&&!f.includes("$")&&(Array.isArray($)||isObject($))&&!Array.isArray(m)&&(Array.isArray(m[f])?m[f].forEach(q=>{typeof q!="string"&&(q.$objectPath=A(m,f),q.$parentIsCreate=m.$op==="create",q[gi]=m.$parentIsCreate||m[Symbol.for("grandChildOfCreate")]);}):isObject(m[f])&&(m[f].$parentIsCreate=m.$op==="create",m[f][Symbol.for("grandChildOfCreate")]=m.$parentIsCreate||m[Symbol.for("grandChildOfCreate")],m[f].$objectPath=A(m,f)));})),n=u(o),i=(B=>{let k=(m,q)=>{let S=[];m.filter(Q=>Q).forEach(Q=>{let I=Object.keys(Q).filter(N=>!N.startsWith("$")).length;if(Array.isArray(Q.$id)&&I>0){let N=Q.$id.map(x=>({...Q,$id:x}));S=[...S,...N];}else S.push({...Q});});let g=[],L=[],P=S.filter(Q=>{let N=["delete","update","unlink"].includes(Q.$op||""),x=w(Q,!0).length;if((!Q.$id||Array.isArray(Q.$id)&&x>0||Q.$filter)&&N)return !0;L.push({...Q});});return P.length>0?P.forEach(Q=>{let N=(z=>{let at=(()=>{let V={};for(let j in z){let X=D(a,z);!j.startsWith("$")&&X.dataFields?.find(ot=>ot.path===j)&&(V[j]=z[j]);}return V})(),lt=Object.keys(z),G=lt.filter(V=>!V.startsWith("$")),Et=[],yt=(V,j)=>{if(V===G.length){let ot={...j};lt.forEach(_=>{_.startsWith("$")&&(ot[_]=z[_]);}),Et.push(ot);return}let X={...j,[G[V]]:z[G[V]],...rt(j),...at};yt(V+1,X),yt(V+1,j);};return yt(0,{...rt(z)}),Et})(Q).filter(z=>!(z.$op==="update"&&Object.keys(z).filter(tt=>!tt.startsWith("$")).length===0)),x=[],v=e(Q.$objectPath),W=h[v]?h[v].$ids:[],C=N.map((z,tt)=>{let at=D(a,z),G=Object.keys(z).filter(j=>!j.includes("$")&&!at.dataFields?.some(X=>X.path===j)).map(j=>(Array.isArray(z[j])?z[j].length>1?z[j].filter(_=>!_.$id||Array.isArray(_.$id)||_.$filter):z[j]:[z[j]]).map(_=>{let Lt=e(_.$objectPath);return {idsToKey:(Qt=>{let xt=[],ct=Qt.split("."),ve=ct.slice(0,ct.length-1).join("."),ze=ct.slice(ct.length-1,ct.length)[0].split("___")[1];for(let Mt in h)if(Mt.startsWith(ve)&&Mt.endsWith(ze)){let St=Mt.split("."),Ve=St.slice(St.length-1,St.length)[0].split("___")[0];xt.push(Ve);}return xt})(Lt),key:j,multiple:_}})).filter(j=>j!==void 0),V=(j=>{let X=j.map(_=>_.map(et=>et.idsToKey));return (_=>_.length>0?_.reduce((et,dt)=>et.concat(dt),[]).reduce((et,dt)=>et?dt.filter(Qt=>et.includes(Qt)):dt):[])(X)})(G).filter(j=>!x.includes(j));if(x=[...x,...V],W=W.filter(j=>!V.includes(j)),tt===N.length-1&&W.length>0)return {...z,$id:W,$bzId:`T_${v4()}`,...rt(z)};if(V.length>0)return {...z,$id:V,$bzId:`T_${v4()}`,...rt(z)}}).filter(z=>z!==void 0),xe=(()=>{if(C.length===0&&!q?.$id)return P;if(C.length===0&&q?.$id){let z=Array.isArray(q.$id)?q.$id:[q.$id],tt=[];return z.forEach(at=>{let lt=e({...Q.$objectPath,ids:at}),G=h[lt];G&&tt.push({...Q,$id:G.$ids,...rt(Q),$bzId:`T_${v4()}`});}),tt}else return C})();g=[...L,...xe].map(M);}):g=S.map(M),g},M=m=>{let q={...m,$bzId:`T_${v4()}`,...rt(m)},S=D(a,m);return Object.keys(m).filter(g=>!g.includes("$")&&!S.dataFields?.some(L=>L.path===g)).forEach(g=>{let L=Array.isArray(m[g])?m[g]:[m[g]],P=k(L,m);q[g]=P.length>0?P:void 0;}),q},f=[];return B.forEach(m=>{f=[...f,...k([m])];}),f.map(m=>M(m))})(Array.isArray(n)?n:[n]),t=B=>B.map(k=>{let M=w(k,!0),f={...k};return M.forEach($=>{let m=Array.isArray(k[$])?k[$]:[k[$]],q=[],S=[],g=[],L={},P=Rt(a,k,$);m.filter(C=>C).forEach(C=>{C.$op==="replace"&&C.$id?(L=C,Array.isArray(C.$id)?S=[...S,...C.$id]:S.push(C.$id)):C.$op==="create"&&P==="ONE"&&C.id?(L=C,Array.isArray(C.id)?g=[...S,...C.id]:g.push(C.id)):q.push(C);});let Q=e(L.$objectPath),N=s(Q).map(C=>h[C]),x=[];N.filter(C=>C!=null).forEach(C=>{x=[...x,...C.$ids];});let v=x.filter(C=>!S.includes(C)),Y=S.filter(C=>!x.includes(C)),W=rt(L);v.length>0&&q.push({...L,$op:"unlink",$id:v,$bzId:`T_${v4()}`,id:void 0,...W}),Y.length>0&&Y.forEach(C=>{q.push({...L,$op:"link",$id:C,$bzId:`T_${v4()}`,...W});}),g.length>0&&g.forEach(C=>{q.push({...L,$op:"create",id:C,$bzId:`T_${v4()}`,...W});}),f[$]=t(q);}),f}),R=u(t(u(i)));(B=>produce(B,k=>traverse(k,M=>{let{key:f,value:$,parent:m}=M;f&&m&&!f?.includes("$")&&(Array.isArray($)||isObject($))&&!Array.isArray(m)&&(Array.isArray($)?$:[$]).forEach(S=>{let g=h[e(S.$objectPath)],L=(I,N)=>I.every(x=>N.includes(x)),P=S.$id?Array.isArray(S.$id)?L(S.$id,g?g.$ids:[]):g?.$ids.includes(S.$id):g,Q=Rt(a,m,S.$objectPath.key);if(S.$op==="link"&&P&&Q==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${e(S.$objectPath)}" because it is already occupied.`);if(S.$op)switch(S.$op){case"delete":if(!P&&!d.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${S.$id}" because it is not linked to $id:"${m.$id}"`);break;case"update":if(!P&&!d.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${S.$id}" because it is not linked to $id:"${m.$id}"`);break;case"unlink":if(!P&&!d.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${S.$id}" because it is not linked to $id:"${m.$id}"`);break;case"link":if(P)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${S.$id}" because it is already linked to $id:"${m.$id}"`);break;}});})))(R);let O=(B=>produce(B,k=>traverse(k,M=>{let{parent:f,key:$,value:m,meta:q}=M;isObject(m)&&(m[Symbol.for("path")]=q.nodePath,delete m.$objectPath,delete m.$parentIsCreate),$&&f&&!$?.includes("$")&&(Array.isArray(m)||isObject(m))&&!Array.isArray(f)&&(Array.isArray(m)?m:[m]).forEach(g=>{isObject(g)&&(g[Symbol.for("parent")]={...m[Symbol.for("parent")],path:f[Symbol.for("path")]});});})))(R);l.filledBqlRequest=O;};var Fe=async l=>{let{filledBqlRequest:o,schema:d}=l;if(!o)throw new Error("Filled BQL request is missing");let w=(b=>produce(b,E=>traverse(E,({value:A})=>{if(isObject(A)){let e=A,s=D(d,e),{unidentifiedFields:h}=J(s,e),{idFields:r,computedFields:u,virtualFields:n}=s;if(!r)throw new Error("No idFields found");let[c]=r,i=listify(e,(F,T)=>T!==void 0?F:void 0),t=i.filter(F=>n?.includes(F));if(t.length>0)throw new Error(`Virtual fields can't be sent to DB: "${t.join(",")}"`);if(u.filter(F=>!i.includes(F)).forEach(F=>{let T=s.dataFields?.find(f=>f.path===F),B=s.linkFields?.find(f=>f.path===F)?.oppositeLinkFieldsPlayedBy[0],k="roles"in s?ft(s.roles,(f,$)=>f===F):void 0,M=T||B||k;if(!M)throw new Error(`no field Def for ${F}`);if(F!==c&&e.$op==="create"&&!e[F]){let f=Z({currentThing:e,fieldSchema:M,mandatoryDependencies:!0});e[F]=f;}}),h.length>0)throw new Error(`Unknown fields: [${h.join(",")}] in ${JSON.stringify(e)}`)}})))(o),y=(b=>produce(b,E=>traverse(E,({value:A})=>{isObject(A);})))(w);l.filledBqlRequest=y;};var Qe=async l=>{let{filledBqlRequest:o}=l;if(!o)throw new Error("Filled BQL request is missing");let a=(y=>produce(y,b=>traverse(b,({value:E})=>{isObject(E)&&Jt();})))(o),p=(y=>produce(y,b=>traverse(b,({value:E})=>{isObject(E);})))(a);l.filledBqlRequest=p;};var ke=async l=>{let{filledBqlRequest:o}=l;if(!o)throw new Error("Filled BQL request is missing");let d=w=>produce(w,p=>traverse(p,({value:y})=>{if(isObject(y)&&("$entity"in y||"$relation"in y)){let b=y,{requiredFields:E,enumFields:A,fnValidatedFields:e}=b[bt];"$op"in b&&b.$op==="create"&&E.forEach(s=>{if(!(s in b))throw new Error(`[Validations] Required field "${s}" is missing.`)}),("$op"in b&&b.$op==="update"||b.$op==="create")&&A.forEach(s=>{if(s in b){let h=b[bt]?.dataFields?.find(r=>r.path===s)?.validations?.enum;if(!h)throw new Error(`[Validations] Enum field "${s}" is missing enum options.`);if(isArray(b[s]))b[s].some(r=>{if(!h.includes(r))throw new Error(`[Validations] Option "${r}" is not a valid option for field "${s}".`)});else if(h&&!h.includes(b[s]))throw new Error(`[Validations] Option "${b[s]}" is not a valid option for field "${s}".`)}}),("$op"in b&&b.$op==="update"||b.$op==="create")&&e.forEach(s=>{if(s in b)try{let h=b[bt]?.dataFields?.find(r=>r.path===s)?.validations?.fn;if(!h)throw new Error("Missing validation function.");if(!h(b[s]))throw new Error("Failed validation function.")}catch(h){throw new Error(`[Validations:attribute:${s}] ${h.message}`)}});}})),a=w=>produce(w,p=>traverse(p,({value:y})=>{if(isObject(y)&&("$entity"in y||"$relation"in y)){let b="$entity"in y?y.$entity:y.$relation,E=y,A=y[Symbol.for("schema")].hooks;if(A){let{pre:e}=A;if(e){let s=`on${Ht(E.$op)}`;e.filter(r=>r.triggers[s]).forEach(r=>{let u=s in r.triggers?r.triggers[s]:void 0;u!==void 0&&u()&&r.actions.forEach(n=>{if(n.type==="validate"){if(n.severity!=="error")return;try{let c=n.fn(E);if(c===!1)throw new Error(`${n.message}.`);if(c!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(c){throw new Error(`[Validations:thing:${b}] ${c.message}`)}}});});}}}}));d(o),a(o);};var Re=async(l,o)=>{let{schema:d,enrichedBqlQuery:a}=l,{bqlRes:w}=o;if(!w)return;let y=(b=>produce(b,E=>traverse(E,({value:A})=>{if(isObject(A)){let e=A;if(!e.$thing)throw new Error("[Internal] Thing is missing");if(e.$thing){let s=D(d,e),{virtualFields:h}=s,r=e[K];if(!r)throw new Error("[Internal] QueryPath is missing");let u=getNodeByPath(a,r),n=u.$fields.map(i=>i.$path),c=u.$excludedFields;h.forEach(i=>{if(c?.includes(i)||n.length>0&&!n.includes(i))return;let t=s.dataFields?.find(F=>F.path===i),R=Z({currentThing:e,fieldSchema:t,mandatoryDependencies:!0});e[i]=R;}),c&&c.forEach(i=>{if(typeof i!="string")throw new Error("[Internal] ExcludedField is not a string");delete e[i];});}}})))(w);o.bqlRes=y;};var Oe=async(l,o)=>{let{config:d}=l,{bqlRes:a}=o;if(!a)return;let p=(E=>produce(E,A=>traverse(A,({value:e})=>{isObject(e);})))(a),b=(E=>produce(E,A=>traverse(A,({value:e})=>{if(isObject(e)){let s=e;Object.keys(s).forEach(h=>{s[h]===void 0&&delete s[h];}),Object.getOwnPropertySymbols(s).forEach(h=>{delete s[h];}),d.query?.noMetadata===!0&&Object.keys(s).forEach(h=>{h.startsWith("$")&&delete s[h];});}})))(p);o.bqlRes=b;};var Ie={query:[ue,ce,ye,$e,Re,Oe],mutation:[re,me,Fe,Qe,ke,le,ie,de,Ut,ee]},jt=async(l,o,d={},a=!0)=>{for(let w of l){let p=await w(o,d);if(p&&Array.isArray(p))for(let y of p)await jt(y.pipeline,y.req,y.res,!1);}return a&&o.config.query?.debugger===!0&&typeof d.bqlRes=="object"?{...d.bqlRes,$debugger:{tqlRequest:o.tqlRequest}}:d.bqlRes},Ft=(l,o,d,a)=>jt(Ie.query,{config:o,schema:d,rawBqlRequest:l,dbHandles:a},{}),Ce=(l,o,d,a)=>jt(Ie.mutation,{config:o,schema:d,rawBqlRequest:l,dbHandles:a},{});var Dt=class{schema;config;dbHandles;constructor({schema:o,config:d}){this.schema=o,this.config=d;}init=async()=>{let o={typeDB:new Map},d=Wt(this.schema);await Promise.all(this.config.dbConnectors.map(async a=>{if(a.provider==="typeDB"&&a.dbName){let[w,p]=await tryit(TypeDB.coreDriver)(a.url);if(w){let y=`[BORM:${a.provider}:${a.dbName}:core] ${w.message??"Can't create TypeDB Client"}`;throw new Error(y)}try{let y=await p.session(a.dbName,SessionType.DATA);o.typeDB.set(a.id,{client:p,session:y});}catch(y){let b=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(b)}}if(a.provider==="typeDBCluster"&&a.dbName){let[w,p]=await tryit(TypeDB.cloudDriver)(a.addresses,a.credentials);if(w){let y=`[BORM:${a.provider}:${a.dbName}:core] ${w.message??"Can't create TypeDB Cluster Client"}`;throw new Error(y)}try{let y=await p.session(a.dbName,SessionType.DATA);o.typeDB.set(a.id,{client:p,session:y});}catch(y){let b=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(b)}}})),this.schema=d,this.dbHandles=o;};#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(),zt(this.config,this.schema,this.dbHandles));query=async(o,d)=>{await this.#t();let a={...this.config,query:{...Tt.query,...this.config.query,...d}};return Ft(o,a,this.schema,this.dbHandles)};mutate=async(o,d)=>{await this.#t();let a={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...d}};return Ce(o,a,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:o,session:d})=>{console.log("Closing session"),await d.close(),console.log("Closing client"),await o.close();});}},Gr=Dt;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
32
|
+
${c}`})(),f=d.dbConnectors[0].id,y=l.typeDB.get(f)?.session,B=l.typeDB.get(f)?.client;if(!y){console.log("Session Status: ","NO SESSION");return}await y.close();let[{dbName:M}]=d.dbConnectors;await(await B.databases.get(M)).delete(),await B.databases.create(M);let e=await B.session(d.dbConnectors[0].dbName,SessionType.SCHEMA),s=await e.transaction(TransactionType.WRITE);await s.query.define(F),await s.commit(),await s.close();let u=await e.transaction(TransactionType.READ);(await(await u.query.match("match $a sub thing;")).collect()).forEach(async c=>{c.get("a");}),await u.close();};var ve=(d,r,l)=>l?r:`${d}\xB7${r}`;var pe=(d,r)=>Object.values(Object.fromEntries(Object.entries(d).filter(([l,a])=>r(l,a))))[0],ce=(d,r)=>Object.fromEntries(Object.entries(d).filter(([l,a])=>r(l,a))),ze=d=>{let r=[],l=produce(d,F=>traverse(F,({key:f,value:y,meta:B})=>{if(B.depth===2&&(f&&(y.dataFields=y.dataFields?.map(M=>({...M,cardinality:M.cardinality||"ONE",dbPath:ve(f,M.path,M.shared)}))),y.extends)){let M=F.entities[y.extends]||F.relations[y.extends];if(y.allExtends=[y.extends,...M.allExtends||[]],y.idFields=M.idFields?(y.idFields||[]).concat(M.idFields):y.idFields,y.dataFields=M.dataFields?(y.dataFields||[]).concat(M.dataFields.map(R=>{let e=y.extends,s=d.entities[e]||d.relations[e];for(;!s.dataFields?.find(u=>u.path===R.path);)e=s.extends,s=d.entities[e]||d.relations[e];return {...R,dbPath:ve(e,R.path,R.shared)}})):y.dataFields,y.linkFields=M.linkFields?(y.linkFields||[]).concat(M.linkFields):y.linkFields,"roles"in M){let R=y,e=M;R.roles=R.roles||{},R.roles={...R.roles,...e.roles},Object.keys(R.roles).length===0&&(R.roles={});}}},{traversalType:"breadth-first"}));return traverse(d,({key:F,value:f,meta:y})=>{if(F==="linkFields"){let M=(()=>{if(!y.nodePath)throw new Error("No path");let[e,s]=y.nodePath.split(".");return {thing:s,thingType:e==="entities"?"entity":e==="relations"?"relation":""}})(),R=Array.isArray(f)?f.map(e=>({...e,...M})):[{...f,...M}];r.push(...R);}}),produce(l,F=>traverse(F,({value:f,key:y,meta:B})=>{if(B.depth===2&&f.idFields&&!f.id){f.name=y;let M=()=>{if(B.nodePath?.split(".")[0]==="entities")return "entity";if(B.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};f.thingType=M(),f.computedFields=[],f.virtualFields=[],f.requiredFields=[],f.enumFields=[],f.fnValidatedFields=[],"roles"in f&&Object.entries(f.roles).forEach(([e,s])=>{s.playedBy=r.filter(u=>u.relation===y&&u.plays===e)||[],s.name=e;}),"linkFields"in f&&f.linkFields&&f.linkFields?.forEach(e=>{if(e.target==="relation"){e.oppositeLinkFieldsPlayedBy=[{plays:e.path,thing:e.relation,thingType:"relation"}];return}let s=r.filter(n=>n.relation===e.relation&&n.plays!==e.plays)||[];e.oppositeLinkFieldsPlayedBy=s;let{filter:u}=e;e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>n.target==="role"),u&&Array.isArray(u)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>u.some(p=>n.thing===p.$role)),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>u.some(p=>n.thing===p.$thing))),u&&!Array.isArray(u)&&(e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>n.$role===u.$role),e.oppositeLinkFieldsPlayedBy=e.oppositeLinkFieldsPlayedBy.filter(n=>n.thing===u.$thing));});}if(typeof f=="object"&&"playedBy"in f){if([...new Set(f.playedBy?.map(M=>M.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${y} path:${B.nodePath}`);if(f.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${y}, path:${B.nodePath}`)}if(B.depth===4){let[M,R]=B.nodePath?.split(".")||[],e=F[M][R];f.validations&&(f.validations.required&&e.requiredFields.push(f.path),f.validations.enum&&e.enumFields.push(f.path),f.validations.fn&&e.fnValidatedFields.push(f.path)),f.default?f.isVirtual?e.virtualFields.push(f.path):e.computedFields.push(f.path):f.isVirtual&&e.virtualFields.push(f.path);}}))},Se=(d,r,l)=>{let a=N(d,r),F=a.linkFields?.find(B=>B.path===l);if(F)return F.cardinality;let f=a.dataFields?.find(B=>B.path===l);if(f)return f.cardinality;let y=a.roles[l];if(y)return y.cardinality},N=(d,r)=>{if(r.$thing){if(!r.$thingType)throw new Error("Missing $thingType in node$: {JSON.stringify(node, null, 2)");if(r.$thingType==="entity"){if(!(r.$thing in d.entities))throw new Error(`Missing entity '${r.$thing}' in the schema`);return d.entities[r.$thing]}if(r.$thingType==="relation"){if(!(r.$thing in d.relations))throw new Error(`Missing relation '${r.$thing}' in the schema`);return d.relations[r.$thing]}throw new Error(`Wrong schema or query for ${JSON.stringify(r,null,2)}`)}if(r.$entity){if(!(r.$entity in d.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return d.entities[r.$entity]}if(r.$relation){if(!(r.$relation in d.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return d.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r,null,2)}`)},G=(d,r)=>{let l=d.dataFields?.map(p=>p.path)||[],a=d.linkFields?.map(p=>p.path)||[],F="roles"in d?listify(d.roles,p=>p):[],f=[...l||[],...a||[],...F||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...f];if(!r)return {fields:f,dataFields:l,roleFields:F,linkFields:a};let M=r.$fields?r.$fields.map(p=>{if(typeof p=="string")return p;if("$path"in p&&typeof p.$path=="string")return p.$path;throw new Error(" Wrongly structured query")}):listify(r,p=>p),R=r.$filter?listify(r.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&l?.includes(p)):[],e=r.$filter?listify(r.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&[...F||[],...a||[]].includes(p)):[],s=[...M,...R].filter(p=>!B.includes(p)).filter(p=>p),u=r.$filter?ce(r.$filter,(p,i)=>R.includes(p)):{},n=r.$filter?ce(r.$filter,(p,i)=>e.includes(p)):{};return {fields:f,dataFields:l,roleFields:F,linkFields:a,usedFields:M,usedLinkFields:a.filter(p=>M.includes(p)),usedRoleFields:F.filter(p=>M.includes(p)),unidentifiedFields:s,...R.length?{localFilters:u}:{},...e.length?{nestedFilters:n}:{}}};var _e=d=>{if(typeof d!="string")throw new Error("capitalizeFirstLetter: string is not a string");return d.charAt(0).toUpperCase()+d.slice(1).toLowerCase()},Ve=(d,r,l)=>{let F=(l.nodePath||"").split("."),f=isArray(r)?F.slice(0,-2).join("."):F.slice(0,-1).join(".");return r?getNodeByPath(d,f):{}};var We=async(d,r)=>{let{bqlRequest:l,config:a,tqlRequest:F}=d,{rawTqlRes:f}=r;if(l){if(!f)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:y}=l;if(!y){if(f.insertions?.length===0&&!F?.deletions){r.bqlRes={};return}let{mutation:B}=l;if(!B)throw new Error("TQL mutation not executed");let R=[...B.things,...B.edges].map(e=>{let s=f.insertions?.find(u=>u.get(`${e.$bzId}`))?.get(`${e.$bzId}`);if(e.$op==="create"||e.$op==="update"||e.$op==="link"){let u=s?.asThing().iid;return a.mutation?.noMetadata?mapEntries(e,(n,p)=>[n.toString().startsWith("$")?Symbol.for(n):n,p]):{$dbId:u,...e,[e.path]:e.$id}}if(e.$op==="delete"||e.$op==="unlink")return e;if(e.$op!=="match")throw new Error(`Unsupported op ${e.$op}`)}).filter(e=>e);r.bqlRes=R;return}};var Vt=(d,r)=>produce(d,l=>traverse(l,({value:a})=>{if(Array.isArray(a)||typeof a!="object"||a===null)return;a.$tempId&&(a.$tempId=`_:${a.$tempId}`),a.$fields&&delete a.$fields,a.$filter&&delete a.$filter,a.$show&&delete a.$show,a.$bzId&&delete a.$bzId,r.query?.noMetadata&&(a.$entity||a.$relation)&&(delete a.$entity,delete a.$relation,delete a.$id),Object.getOwnPropertySymbols(a).forEach(f=>{delete a[f];}),a.$excludedFields&&(a.$excludedFields.forEach(f=>{delete a[f];}),delete a.$excludedFields);})),Wt=(d,r)=>{let l={};return r.forEach(a=>{l[a.$bzId]=a.$id;}),d.forEach(a=>{Object.keys(a).forEach(F=>{l[a[F]]&&F!=="$tempId"&&(a[F]=l[a[F]]);});}),d},Ht=(d,r)=>{let l=r.map(F=>F.$bzId),a=!1;return d.forEach(F=>{Object.keys(F).forEach(f=>{l.includes(F[f])&&(a=!0);});}),a},He=async(d,r)=>{let{bqlRequest:l,config:a}=d;if(!l)throw new Error("BQL request not parsed");let F=r.bqlRes[0]?r.bqlRes:[r.bqlRes],f=d.bqlRequest?.mutation?.things;if(Ht(F,f)){let M=Wt(F,f);r.bqlRes=M[1]?M:M[0];}let B=Vt(r.bqlRes,a);r.bqlRes=B;};var Ue=async d=>{let{bqlRequest:r,schema:l}=d;if(!r)throw new Error("BQL request not parsed");let{mutation:a}=r;if(!a)throw new Error("BQL request is not a mutation");let F=n=>{let p=n.$op,i=`$${n.$bzId}`,c=N(l,n),{idFields:t,defaultDBConnector:o}=c,P=o?.path||n.$entity||n.$relation,w=n.$id,k=t?.[0],q=listify(n,(m,Q)=>{if(m.startsWith("$")||m===k||Q===void 0||Q===null)return "";let I=c.dataFields?.find(D=>D.path===m);if(!I?.path)return "";let j=I.dbPath;if(["TEXT","ID","EMAIL"].includes(I.contentType))return `has ${j} '${Q}'`;if(["NUMBER","BOOLEAN"].includes(I.contentType))return `has ${j} ${Q}`;if(I.contentType==="DATE"){if(Number.isNaN(Q.valueOf()))throw new Error("Invalid format, Nan Date");return Q instanceof Date?`has ${j} ${Q.toISOString().replace("Z","")}`:`has ${j} ${new Date(Q).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${I.contentType}`)}).filter(m=>m),b=`${i}-atts`,T=listify(n,m=>{if(m.startsWith("$")||m===k)return "";let Q=c.dataFields?.find(j=>j.path===m);if(!Q?.path)return "";let O=Q.dbPath;return `{${b} isa ${O};}`}).filter(m=>m),L=n[Symbol.for("isLocalId")],h=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,S=!L&&w?[`has ${k} ${h}`]:[],$=[...S,...q].filter(m=>m).join(","),E=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${i} isa ${[P,...S].filter(m=>m).join(",")};`;if(p==="update"){if(!T.length)throw new Error("update without attributes");return `${i} isa ${[P,...S].filter(m=>m).join(",")}, has ${b};
|
|
33
|
+
${T.join(" or ")};`}return ""},g=()=>p==="update"||p==="link"||p==="match"?`${i} isa ${[P,...S].filter(m=>m).join(",")};`:"";if(n.$entity||n.$relation)return {op:p,deletionMatch:E(),insertionMatch:g(),insertion:p==="create"?`${i} isa ${[P,$].filter(m=>m).join(",")};`:p==="update"&&q.length?`${i} ${q.join(",")};`:"",deletion:p==="delete"?`${i} isa ${P};`:p==="update"&&T.length?`${i} has ${b};`:""};throw new Error("in attributes")},f=n=>{let p=n.$op,i=N(l,n),c=`$${n.$bzId}`,t=n.$id,o=i.defaultDBConnector?.path||n.$relation,P="roles"in i?listify(i.roles,m=>m):[],w=n.$relation&&"roles"in i&&mapEntries(i.roles,(m,Q)=>[m,Q.dbConnector?.path||m]),k=listify(n,(m,Q)=>{if(!P.includes(m))return null;if(!("roles"in i))throw new Error("This should have roles! ");let I=w[m];return Array.isArray(Q)?Q.map(O=>({path:I,id:O})):{path:I,id:Q}}).filter(m=>m).flat(),q=k.map(m=>{if(!m?.path)throw new Error("Object without path");return `${m.path}: $${m.id}`}),b=k.length>0?`( ${q.join(" , ")} )`:"",T=n[Symbol.for("edgeType")];if(!T)throw new Error("[internal error] Symbol edgeType not defined");let L=b?`${c} ${b} ${T==="linkField"||p==="delete"||p==="unlink"?`isa ${o}`:""}`:"",h=`${c} ${T==="linkField"||p==="delete"?`isa ${o}`:""}`,S=()=>L?p==="link"?`${L};`:p==="create"?`${L}, has id '${t}';`:"":"",$=()=>L&&p==="match"?`${L};`:"",E=()=>L?p==="delete"?`${L};`:p==="match"?`${L};`:"":"",g=()=>L?p==="delete"?`${h};`:p==="unlink"?`${c} ${b};`:"":"";return {deletionMatch:E(),insertionMatch:$(),deletion:g(),insertion:S(),op:""}},y=(n,p)=>{let i=p==="edges"?f:F;if(Array.isArray(n))return n.map(k=>{let{preDeletionBatch:q,insertionMatch:b,deletionMatch:T,insertion:L,deletion:h}=i(k);return shake({preDeletionBatch:q,insertionMatch:b,deletionMatch:T,insertion:L,deletion:h},S=>!S)}).filter(k=>k);let{preDeletionBatch:c,insertionMatch:t,deletionMatch:o,insertion:P,deletion:w}=i(n);return shake({preDeletionBatch:c,insertionMatch:t,deletionMatch:o,insertion:P,deletion:w},k=>!k)},B=y(a.things),M=Array.isArray(B)?B:[B],R=y(a.edges,"edges"),e=Array.isArray(R)?R:[R],s=[...M,...e],u=shake({insertionMatches:s.map(n=>n.insertionMatch).join(" ").trim(),deletionMatches:s.map(n=>n.deletionMatch).join(" ").trim(),insertions:s.map(n=>n.insertion).join(" ").trim(),deletions:s.map(n=>n.deletion).join(" ").trim()},n=>!n);d.tqlRequest=u;};var Jt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Zt=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Ke=d=>{let l=d.toString().replace(Jt,"").trim().split("=>")[0].split("{")[0].replace(Zt,"").trim(),a=l.substring(l.indexOf("(")+1,l.lastIndexOf(")")).trim();return a?(a.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(f=>f.includes("{")&&f.includes("}")?(f.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):f.trim()).filter(Boolean):[]};var X=({currentThing:d,fieldSchema:r,mandatoryDependencies:l=!1})=>{if(!r||!r.default||!("fn"in r.default||"value"in r.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(r,null,3)}`);if(r.default.type==="value")return r.default.value;if(l){let{fn:F}=r.default,y=Ke(F).filter(B=>!(B in d));if(y.length)throw new Error(`Virtual field: Missing arguments ${y.join(", ")}`)}return "default"in r?r.default?.fn(d):void 0},Je=()=>{};var ti=d=>{if(!d.startsWith("_:"))throw new Error("ID must start with '_:'.");let r=d.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(r))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(d.length>36)throw new Error("$tempId must not be longer than 36 characters.");return r},Ye=async d=>{let{rawBqlRequest:r,schema:l}=d,F=(s=>produce(s,u=>traverse(u,({value:n,key:p,parent:i})=>{if(isObject(n)&&(n=shake(n,c=>c===void 0)),p==="$tempId"&&(i[p]=ti(n)),i&&isArray(n)){if(!n.some(t=>typeof t=="object"&&"$id"in t))return;let c=n.flatMap(t=>typeof t=="string"?t:typeof t=="object"&&"$id"in t&&isArray(t.$id)?t.$id.map(o=>({...t,$id:o})):t);i[p]=c;}})))(r),y=(s=>produce(s,u=>traverse(u,({value:n,meta:p,key:i})=>{if(isObject(n)){if(n.$arrayOp)throw new Error("Array op not supported yet");if(i==="$filter"||p.nodePath?.includes(".$filter."))return;let c=n;if(c.$op==="create"&&c.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let t=N(l,c),P=Object.keys(c).filter($=>t.virtualFields?.includes($));if(P.length>0){let $=P.filter(E=>c[E]);if($.length>0)throw new Error(`Can't set virtual fields: ["${$.join('","')}"]`)}let k=p.nodePath?.split(".")?.filter($=>Number.isNaN(parseInt($,10))).join(".");if(!t)throw new Error(`Schema not found for ${c.$entity||c.$relation}`);c.$bzId=c.$tempId??`T_${v4()}`,c[Symbol.for("schema")]=t,c[Symbol.for("dbId")]=t.defaultDBConnector.id;let{usedLinkFields:q,usedRoleFields:b}=G(t,c),T=q.map($=>({fieldType:"linkField",path:$,schema:t.linkFields.find(E=>E.path===$)})),L=t.thingType==="relation"?b.map($=>({fieldType:"roleField",path:$,schema:pe(t.roles,E=>E===$)})):[];if(T.some($=>$.schema?.target==="role")&&T.some($=>$.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let h=L.filter($=>[...new Set($.schema.playedBy?.map(E=>E.thing))].length!==1);if(h.length>1)throw new Error(`Field: ${h[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(h[0].schema.playedBy)}. Schema: ${JSON.stringify(h[0].schema)}`);let S=p.nodePath;if([...T,...L].forEach($=>{let E=c[$.path];if(E===void 0)return;let g=$.schema;if(!g)throw new Error(`Field ${$.path} not found in schema`);let m=$.fieldType==="roleField"?g?.playedBy[0]:g,I=g&&"relation"in g&&m?.relation===c.$relation?"$self":m?.relation?m?.relation:"$self",O=I==="$self"?t:l.relations[I];if(pe(O.roles,(v,A)=>v===$.path)?.playedBy?.length===0)throw new Error(`unused role: ${S}.${$.path}`);if(!g)throw new Error(`Field ${$.path} not found in schema`);let D=$.fieldType==="linkField"?g?.oppositeLinkFieldsPlayedBy:g?.playedBy;if(!D)throw new Error(`No opposite fields found for ${JSON.stringify(g)}`);if([...new Set(D?.map(v=>v.thing))].length>1)throw new Error(`Field: ${$.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(D)}. Schema: ${JSON.stringify(g)}`);if(g.cardinality==="ONE"&&Array.isArray(E))throw new Error("Can't have an array in a cardinality === ONE link field");if(g.cardinality==="MANY"&&E!==null&&!Array.isArray(E)&&!E.$arrayOp)throw new Error(`${$.fieldType==="linkField"?g.path:g.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(E?.$entity||E?.$relation)return;let[z]=D,J="plays"in g?"linkField":"roleField",K={[`$${z.thingType}`]:z.thing,[Symbol.for("relation")]:I,[Symbol.for("edgeType")]:J,[Symbol.for("parent")]:{path:S,...c.$id?{$id:c.$id}:{},...c.$tempId?{$tempId:c.$tempId}:{},...c.filter?{filter:c.filter}:{},links:D},[Symbol.for("role")]:z.plays,[Symbol.for("oppositeRole")]:"plays"in g?g.plays:void 0,[Symbol.for("relFieldSchema")]:g};if(isObject(E)&&(c[$.path]={...K,...E}),Array.isArray(E))if(E.every(v=>isObject(v)))c[$.path]=E.map(v=>({...K,...v}));else if(E.every(v=>typeof v=="string"))c[$.path]=E.map(v=>({...K,$op:c.$op==="create"?"link":"replace",$id:v}));else throw new Error(`Invalid array value for ${$.path}`);if(typeof E=="string"&&(c[$.path]={...K,$op:c.$op==="create"?"link":"replace",$id:E}),E===null){let v={...K,$op:"unlink"};c[$.path]=g.cardinality==="MANY"?[v]:v;}}),!k&&!c.$entity&&!c.$relation)throw new Error("Root things must specify $entity or $relation")}})))(F),M=(s=>produce(s,u=>traverse(u,({parent:n,key:p,value:i,meta:c})=>{if(isObject(i)){if(Object.keys(i).length===0)throw new Error("Empty object!");if(p==="$filter"||c.nodePath?.includes(".$filter."))return;let t=i,o=c.nodePath?.split(".");if(t.$tempId&&!(t.$op===void 0||t.$op==="link"||t.$op==="create"||t.$op==="update"))throw new Error(`Invalid op ${t.$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.`);let P=o?.filter(I=>Number.isNaN(parseInt(I,10))).join("."),w=P?Array.isArray(n)?o?.slice(0,-1).join("."):c.nodePath:c.nodePath||"",k=N(l,t),{dataFields:q,roleFields:b,linkFields:T}=G(k,t),L=current(t)[Symbol.for("parent")],h=P&&L.path,$=(h?getNodeByPath(u,h):u)?.$op;if(P&&!$)throw new Error("Error: Parent $op not detected");let E=t[Symbol.for("relFieldSchema")];t.$op==="replace"&&$==="create"&&(t.$op="link");let g=Object.keys(t).some(I=>q?.includes(I)),m=Object.keys(t).some(I=>[...b,...T].includes(I)),Q=()=>{if(t.$op)return t.$op;if(P&&!t.$id&&!t.$tempId&&$!=="create"&&E.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${c.nodePath}`);if(t.$tempId)return "create";if((t.$id||t.$filter)&&g)return "update";if((t.$id||t.$filter)&&P&&!g&&!m)return "link";if(!t.$filter&&!t.$id&&!t.$tempId)return "create";if((t.$id||t.$filter)&&!g&&m)return "match";throw new Error("Wrong op")};if(t.$op||(t.$op=Q()),n||(t.$parentKey=""),typeof n=="object"&&(Array.isArray(n)&&(t[Symbol.for("index")]=p),t[Symbol.for("path")]=w,t[Symbol.for("isRoot")]=!P,t[Symbol.for("depth")]=P?.split(".").length),!t.$entity&&!t.$relation)throw new Error(`Node ${JSON.stringify(t)} without $entity/$relation`)}})))(y),e=(s=>produce(s,u=>traverse(u,({value:n})=>{if(isObject(n)){let p=n,i=N(l,p),{unidentifiedFields:c}=G(i,p),{idFields:t}=i;if(!t)throw new Error("No idFields found");let[o]=t;if(p.$op==="create"&&!p[o]){let P=i.dataFields?.find(k=>k.path===o),w=X({currentThing:p,fieldSchema:P,mandatoryDependencies:!0});if(typeof w!="string")throw new Error(`Default id field ${o} is not a string`);p[o]=w,p.$id=w;}if(c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(p)}`)}})))(M);d.filledBqlRequest=e;};var tt=async d=>{let{filledBqlRequest:r,schema:l}=d,a=e=>{let s=[],u=[],n=t=>{if(t.$id)return t.$id;let o=N(l,t),{idFields:P}=o;if(!P)throw new Error(`no idFields: ${JSON.stringify(t)}`);let[w]=P;if(!w)throw new Error(`no idField: ${JSON.stringify(t)}`);let k=o.dataFields?.find(T=>T.path===w),q=X({currentThing:t,fieldSchema:k,mandatoryDependencies:!0}),b=t[w]||t.$id||q;if(!b)throw new Error(`no idValue: ${JSON.stringify(t)}`);return b},p=t=>{if(t.$op==="create"){let o=n(t);if(s.find(P=>P.$id===o))throw new Error(`Duplicate id ${o} for node ${JSON.stringify(t)}`);if(u.find(P=>P.$bzId===t.$bzId))throw new Error(`Duplicate $bzid ${t.$bzId} for node ${JSON.stringify(t)}`);s.push({...t,$id:o});return}t.$tempId&&t.$op==="match"||s.push(t);},i=t=>{if(t.$op==="create"){let o=n(t);if(s.find(P=>P.$id===o),u.find(P=>P.$bzId===t.$bzId))throw new Error(`Duplicate %bzId ${t.$bzIdd} for edge ${JSON.stringify(t)}`);u.push({...t,$id:o});return}u.push(t);};return traverse(e,({value:t})=>{if(!isObject(t))return;let o=t;if(o.$entity||o.$relation){if(!o.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(o)}`);if(!o.$bzId)throw new Error("[internal error] BzId not found");let P=N(l,o),{dataFields:w,roleFields:k,linkFields:q,usedFields:b}=G(P,o),T=()=>{if(o.$op==="create"||o.$op==="delete")return o.$op;if(o.$op==="update"){let h=b.filter(E=>w?.includes(E)),S=b.filter(E=>k?.includes(E)),$=b.filter(E=>q?.includes(E));if(h.length>0)return "update";if(S.length>0||$.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(o)}`)}return "match"},L={...o.$entity&&{$entity:o.$entity},...o.$relation&&{$relation:o.$relation},...o.$id&&{$id:o.$id},...o.$tempId&&{$tempId:o.$tempId},...o.$filter&&{$filter:o.$filter},...shake(pick(o,w||[""])),$op:T(),$bzId:o.$bzId,[Symbol.for("dbId")]:P.defaultDBConnector.id,[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("parent")]:o[Symbol.for("parent")],[Symbol.for("isRoot")]:o[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:o[Symbol.for("isLocalId")]||!1};if(p(L),o[Symbol.for("relation")]&&o[Symbol.for("edgeType")]==="linkField"){if((o.$op==="link"||o.$op==="unlink")&&(o.$id||o.$filter)){if(o.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");s.push({...o,$op:"match"});}let h=o[Symbol.for("relation")]===o.$relation,S=h?o.$bzId:`LT_${v4()}`,E=o[Symbol.for("parent")].path,m=(E?getNodeByPath(e,E):e).$bzId;if(!m)throw new Error("No parent id found");if(o[Symbol.for("relation")]==="$self")return;let Q=()=>{if(o.$op==="delete")return h?"match":"delete";if(o.$op==="unlink")return h?"unlink":"delete";if(o.$op==="link"||o.$op==="create")return h?"link":"create";if(o.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},I={$relation:o[Symbol.for("relation")],$bzId:S,...o.$tempId?{$tempId:o.$tempId}:{},$op:Q(),...h?{}:{[o[Symbol.for("role")]]:o.$bzId},[o[Symbol.for("oppositeRole")]]:m,[Symbol.for("dbId")]:l.relations[o[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("parent")]:o[Symbol.for("parent")]};i(I),(o.$op==="unlink"||Q()==="unlink")&&h&&i({$relation:o[Symbol.for("relation")],$bzId:S,$op:"match",[o[Symbol.for("oppositeRole")]]:m,[Symbol.for("dbId")]:l.relations[o[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("parent")]:o[Symbol.for("parent")]});}if(o.$relation){let h=ce(o,(E,g)=>k.includes(E)),S=mapEntries(h,(E,g)=>isArray(g)?[E,g]:isObject(g)?[E,g.$bzId]:[E,g]),$=ce(t,(E,g)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(h).filter(E=>!E.startsWith("$")).length>0){if(o.$op==="create"||o.$op==="delete"){let E=()=>{if(o.$op==="create")return "link";if(o.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},g=mapEntries(S,(Q,I)=>Array.isArray(I)?[Q,I.map(O=>O.$bzId||O)]:[Q,I.$bzId||I]),m={...$,$relation:o.$relation,$op:E(),...g,$bzId:o.$bzId,[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("dbId")]:P.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};i(m);return}if(o.$op==="match"||o.$op==="update"&&Object.keys(h).length>0){let E=0;Object.entries(h).forEach(([g,m])=>{let Q=isArray(m)?m:[m],I=O=>O==="create"||O==="replace"?"link":O;Q.forEach(O=>{if(!O)return;let j=I(O.$op);if(j==="replace")throw new Error("Not supported yet: replace on roleFields");if(j==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let D={...$,$relation:o.$relation,$op:j==="delete"?"unlink":j,[g]:O.$bzId,$bzId:o.$bzId,[Symbol.for("dbId")]:P.defaultDBConnector.id,[Symbol.for("parent")]:o[Symbol.for("parent")],[Symbol.for("path")]:o[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};i(D);});});}}}}}),[s,u]};if(!r)throw new Error("Undefined filledBqlRequest");let [F,f]=a(r),y=F.reduce((e,s)=>{if(!s.$bzId)return [...e,s];let u=e.findIndex(n=>n.$bzId===s.$bzId);if(u===-1)return [...e,s];if(e[u].$op==="create"&&s.$op==="match")return e;if(e[u].$op==="match"&&(s.$op==="create"||s.$op==="match"))return [...e.slice(0,u),s,...e.slice(u+1)];throw new Error(`Unsupported operation combination for $tempId "${s.$tempId}". Existing: ${e[u].$op}. Current: ${s.$op}`)},[]),B=f.reduce((e,s)=>{let u=e.find(n=>(n.$id&&n.$id===s.$id||n.$bzId&&n.$bzId===s.$bzId)&&n.$relation===s.$relation&&n.$op===s.$op);if(u){let n={...u};return Object.keys(s).forEach(i=>{if(typeof i=="symbol"||i.startsWith("$"))return;let c=u[i],t=s[i];Array.isArray(c)&&Array.isArray(t)?n[i]=Array.from(new Set([...c,...t])):!Array.isArray(c)&&Array.isArray(t)?c!==void 0?n[i]=Array.from(new Set([c,...t])):n[i]=t:Array.isArray(c)&&!Array.isArray(t)?t!==void 0&&(n[i]=Array.from(new Set([...c,t]))):c!==null&&t!==null&&c!==void 0&&t!==void 0?n[i]=Array.from(new Set([c,t])):c==null&&(n[i]=t);}),[...e.filter(i=>!((i.$id&&i.$id===s.$id||i.$bzId&&i.$bzId===s.$bzId)&&i.$relation===s.$relation&&i.$op===s.$op)),n]}return [...e,s]},[]);[...new Set(B.map(e=>e.$relation))];d.bqlRequest={mutation:{things:y,edges:B}};};var fe=async(d,r)=>{let l=r.dbConnectors[0].id,a=d.typeDB.get(l)?.session,F=d.typeDB.get(l)?.client;if(!a||!a.isOpen()){if(!F)throw new Error("Client not found");a=await F.session(r.dbConnectors[0].dbName,SessionType.DATA),d.typeDB.set(l,{client:F,session:a});}return {client:F,session:a}};var it=async(d,r)=>{let{dbHandles:l,tqlRequest:a,bqlRequest:F,config:f}=d;if(!a)throw new Error("TQL request not built");if(!(a.deletions&&a.deletionMatches||a.insertions))throw new Error("TQL request error, no things");if(!F?.mutation)throw new Error("BQL mutation not parsed");let{session:y}=await fe(l,f),B=await y.transaction(TransactionType.WRITE);if(!B)throw new Error("Can't create transaction");let M=a.deletionMatches&&a.deletions&&`match ${a.deletionMatches} delete ${a.deletions}`,R=a.insertions&&`${a.insertionMatches?`match ${a.insertionMatches}`:""} insert ${a.insertions}`;M&&await B.query.delete(M);let e=R&&B.query.insert(R);try{let s=e?await e.collect():void 0;await B.commit(),await B.close(),r.rawTqlRes={insertions:s};}catch(s){throw await B.close(),new Error(`Transaction failed: ${s.message}`)}};var be=Symbol.for("schema"),U=Symbol.for("queryPath");var W="___",nt=async d=>{let{enrichedBqlQuery:r}=d;if(!r)throw new Error("BQL query not enriched");let l="",a=(e,s)=>{let u="",n="";for(let p in e){let i=e[p];if(Array.isArray(i))for(let c=0;c<i.length;c++)n+=`{$${s} has ${p} "${i[c]}";}`,c<i.length-1?n+="or":n+=";";else u+=`, has ${p} "${i}"`;}u+=`;
|
|
34
|
+
`,l+=u,l+=n;},F=(e,s)=>{let u=[],n=[],p="";for(let t=0;t<e.length;t++)e[t].$isVirtual||u.push(` ${e[t].$dbPath}`),n.push(`{${e[t].$dbPath}:${e[t].$as}}`);let i=`${u.join(",")};
|
|
35
|
+
`;p=n.join(",");let c=`$metadata:{as:[${p}]}`;l+=`$${s} as "${s}.${c}.$dataFields": `,l+=i;},f=(e,s,u)=>{for(let n of e){let{$fields:p,$as:i,$justId:c,$idNotIncluded:t,$filterByUnique:o}=n,P=n[U],w=`$metadata:{as:${i},justId:${c?"T":"F"},idNotIncluded:${t},filterByUnique:${o}}`;if(l+=`"${u}.${w}.${n.$var}":{
|
|
36
|
+
`,l+=` match
|
|
37
|
+
`,n.$filter&&(l+=` $${s}${W}${n.$var} isa ${n.$thing}`,a(n.$filter,`${s}${W}${n.$var}`)),l+=` $${s} (${n.$var}: $${s}${W}${n.$var}) isa ${n.$intermediary};
|
|
38
|
+
`,p){let k=`M_${v4()}`;l+=`?queryPath${k} = "${P}";
|
|
39
|
+
`,l+=` fetch
|
|
40
|
+
`,l+=`?queryPath${k} as "queryPath"
|
|
41
|
+
;`;let q=p?.filter(L=>L.$fieldType==="data");q&&q.length>0&&F(q,`${s}${W}${n.$var}`,`${s}.${n.$var}`);let b=p?.filter(L=>L.$fieldType==="link");b&&b.length>0&&y(b,`${s}${W}${n.$var}`,`${s}.${n.$var}`);let T=p?.filter(L=>L.$fieldType==="role");T&&T.length>0&&f(T,`${s}${W}${n.$var}`,`${s}.${n.$var}`);}l+=`};
|
|
42
|
+
`;}},y=(e,s,u)=>{for(let n of e){let{$fields:p,$as:i,$justId:c,$idNotIncluded:t,$filterByUnique:o,$playedBy:P}=n,w=n[U],k=`$metadata:{as:${i},justId:${c?"T":"F"},idNotIncluded:${t},filterByUnique:${o}}`;if(l+=`"${u}.${k}.${n.$var}":{
|
|
43
|
+
`,l+=` match
|
|
44
|
+
`,n.$filter&&(l+=` $${s}${W}${n.$var} isa ${n.$thing}`,a(n.$filter,`${s}${W}${n.$var}`)),n.$target==="role"?l+=` $${s}_intermediary (${n.$plays}: $${s}, ${P.plays}: $${s}${W}${n.$var}) isa ${n.$intermediary};
|
|
45
|
+
`:l+=` $${s}${W}${n.$var} (${n.$plays}: $${s}) isa ${n.$thing};
|
|
46
|
+
`,p){let q=`M_${v4()}`;l+=`?queryPath${q} = "${w}";
|
|
47
|
+
`,l+=` fetch
|
|
48
|
+
`,l+=`?queryPath${q} as "queryPath"
|
|
49
|
+
;`;let b=p?.filter(h=>h.$fieldType==="data");b&&b.length>0&&F(b,`${s}${W}${n.$var}`);let T=p?.filter(h=>h.$fieldType==="link");T&&T.length>0&&y(T,`${s}${W}${n.$var}`,`${s}.${n.$var}`);let L=p?.filter(h=>h.$fieldType==="role");L&&L.length>0&&f(L,`${s}${W}${n.$var}`,`${s}.${n.$var}`);}l+=`};
|
|
50
|
+
`;}},B=r.length>1,M=[];(e=>{if(B)for(let s of e){let{$path:u,$thing:n,$filter:p,$fields:i}=s,c=s[U];l+=`match
|
|
51
|
+
$${u} isa ${n} `,p?a(p,u):l+="; ";let t=`M_${v4()}`;if(l+=`?queryPath${t} = "${c}";
|
|
52
|
+
`,l+=`fetch
|
|
53
|
+
`,l+=`?queryPath${t} as "queryPath"
|
|
54
|
+
;`,i){let o=i.filter(k=>k.$fieldType==="data");o&&o.length>0&&F(o,u);let P=i.filter(k=>k.$fieldType==="link");P&&P.length>0&&y(P,u,u);let w=i.filter(k=>k.$fieldType==="role");w&&w.length>0&&f(w,u,u);}M.push(l),l="";}else for(let s of e){let{$path:u,$thing:n,$filter:p,$fields:i}=s,c=s[U];if(l+=`match
|
|
55
|
+
$${u} isa ${n} `,p?a(p,u):l+="; ",l+=`?queryPath = "${c}";
|
|
56
|
+
`,l+=`fetch
|
|
57
|
+
`,l+=`?queryPath as "queryPath"
|
|
58
|
+
;`,i){let t=i.filter(w=>w.$fieldType==="data");t&&t.length>0&&F(t,u);let o=i.filter(w=>w.$fieldType==="link");o&&o.length>0&&y(o,u,u);let P=i.filter(w=>w.$fieldType==="role");P&&P.length>0&&f(P,u,u);}}})(r),d.tqlRequest=B?M:l;};var Re=d=>{let r=d.dataFields?.map(f=>f.path)||[],l=d.linkFields?.map(f=>f.path)||[],a=Object.keys(d.roles||{})||[];return [...r,...l,...a]},qe=(d,r)=>Object.keys(d||{}).some(a=>{if(!Array.isArray(d[a])){let F=r.idFields?.includes(a),f=r.dataFields?.some(y=>(y.dbPath===a||y.path===a)&&y?.validations?.unique);return F||f}return !1}),Oe=(d,r)=>{let l=r.dataFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],a=r.linkFields?.map(y=>({path:y.path,dbPath:y.dbPath}))||[],F=Object.keys(r.roles||{}).map(y=>({path:y,dbPath:y}))||[],f=[...l,...a,...F];return Object.entries(d||{}).reduce((y,[B,M])=>{let R=f.find(e=>e.path===B);return y[R?.dbPath||B]=M,y},{})},ot=async d=>{let{rawBqlRequest:r,schema:l}=d;if(Array.isArray(r)){for(let e of r)if(!("$entity"in e)&&!("$relation"in e)&&(!("$thing"in e)||!("$thingType"in e)))throw new Error("No entity specified in query")}else if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query");let a=(e,s)=>typeof s=="string"?e.idFields?.includes(s):e.idFields?.includes(s.$path),F=(e,s,u,n,p)=>({$path:s,$dbPath:n,$thingType:"attribute",$as:e.$as||s,$var:s,$fieldType:"data",$excludedFields:e.$excludedFields,$justId:u,$id:e.$id,$filter:e.$filter,$isVirtual:p,$filterProcessed:!0}),f=(e,s,u,n,p)=>{let{target:i,oppositeLinkFieldsPlayedBy:c}=u;return c.map(t=>{let o=i==="role"?t.thingType:"relation",P=i==="role"?t.thing:u.relation,w={[`$${o}`]:P},k=N(l,w),q=e?.$fields?.filter(T=>a(k,T)).length===0,b=[];return typeof e!="string"?e.$fields?q?b=[...e.$fields,...k.idFields]:b=e.$fields:b=Re(k):b=["id"],e.$excludedFields&&(b=b.filter(T=>a(k,T)?!0:!e.$excludedFields.includes(T.$path))),{$thingType:o,$plays:u.plays,$playedBy:t,$path:t.path,$dbPath:p,$as:e.$as||s,$var:s,$thing:P,$fields:b,$excludedFields:e.$excludedFields,$fieldType:"link",$target:i,$intermediary:t.relation,$justId:n,$id:e.$id,$filter:Oe(e.$filter,k),$idNotIncluded:q,$filterByUnique:qe(e.$filter,k),$filterProcessed:!0}})},y=(e,s,u,n,p)=>u.playedBy.map(i=>{let{thing:c,thingType:t,relation:o}=i,P={[`$${t}`]:c},w=N(l,P),k=e?.$fields?.filter(b=>w?.idFields?.includes(b)||w?.idFields?.includes(b.$path)).length===0,q=[];return typeof e!="string"?e.$fields?k?q=[...e.$fields,...w.idFields]:q=e.$fields:q=Re(w):q=["id"],e.$excludedFields&&(q=q.filter(b=>a(w,b)?!0:!e.$excludedFields.includes(b.$path))),{$thingType:t,$path:s,$dbPath:p,$as:e.$as||s,$var:s,$thing:c,$fields:q,$excludedFields:e.$excludedFields,$fieldType:"role",$intermediary:o,$justId:n,$id:e.$id,$filter:Oe(e.$filter,w),$idNotIncluded:k,$filterByUnique:qe(e.$filter,w),$playedBy:i,$filterProcessed:!0}}),B=(e,s)=>{let u=typeof e=="string"?e:e.$path,n=typeof e=="string",p=s.dataFields?.find(t=>t.path===u),i=s.linkFields?.find(t=>t.path===u),c=s.roles?.[u];if(p){let t=p.isVirtual&&p.default;return F(e,u,n,p.dbPath,t)}else {if(i)return f(e,u,i,n,i.dbPath);if(c)return y(e,u,c,n,c.dbPath)}return null},R=(e=>produce(e,s=>traverse(s,u=>{let{value:n,meta:p}=u,i=n;if(isObject(i)){if(i.$id){let c=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},t=N(l,c);if(i.$path=t.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),t?.idFields?.length===1){let[o]=t.idFields;i.$filter={...i.$filter,[o]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i){let c=N(l,i);i.$path=c.name,i.$as=c.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),isObject(i)&&"$thing"in i){let c=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[U]=p.nodePath;let t=N(l,c);if(i.$filter&&(i.$filterByUnique=qe(i.$filter,t),i.$filterProcessed||(i.$filter=Oe(i.$filter,t))),i.$fields){i.$fields.filter(w=>t?.idFields?.includes(w)||t?.idFields?.includes(w.$path)).length>0||(i.$fields=[...i.$fields,...t.idFields],i.$idNotIncluded=!0);let P=i.$fields?.flatMap(w=>{let k=B(w,t);return Array.isArray(k)?k:[k]}).filter(Boolean);i.$fields=P;}else {let P=Re(t)?.flatMap(w=>{let k=B(w,t);return Array.isArray(k)?k:[k]}).filter(Boolean);i.$fields=P;}i.$excludedFields&&(i.$fields=i.$fields.filter(o=>a(t,o)?!0:!i.$excludedFields.includes(o.$path)));}}})))(Array.isArray(r)?r:[r]);d.enrichedBqlQuery=R;};var at=async(d,r)=>{let{dbHandles:l,enrichedBqlQuery:a,tqlRequest:F,config:f}=d;if(!a)throw new Error("BQL request not parsed");if(!F)throw new Error("TQL request not built");let y=new TypeDBOptions;if(y.infer=!0,Array.isArray(F)){let M=await parallel(F.length,F,async R=>{let{session:e}=await fe(l,f),s=await e.transaction(TransactionType.READ,y);if(!s)throw new Error("Can't create transaction");let n=await s.query.fetch(R).collect();return await s.close(),n});r.rawTqlRes=M,r.isBatched=!0;}else {let{session:M}=await fe(l,f),R=await M.transaction(TransactionType.READ,y);if(!R)throw new Error("Can't create transaction");let s=await R.query.fetch(F).collect();await R.close(),r.rawTqlRes=s;}};var lt=d=>{let r=/as:([a-zA-Z0-9_\-·]+)/,l=/justId:([a-zA-Z0-9_\-·]+)/,a=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,F=/filterByUnique:([a-zA-Z0-9_\-·]+)/,f=d.match(r),y=d.match(l),B=d.match(a),M=d.match(F);return {as:f?f[1]:null,justId:y?y[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:M?M[1]:null}},yi=d=>{try{let l=(F=>{let f=F.replace("$metadata:","");return f=f.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),f=f.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(y,B,M)=>/^{.*}$/.test(M)?`:${M}`:`:${B}"${M}"`),f=f.replace(/\[([^\]]+)\]/g,(y,B)=>`[${B.split(",").map(M=>M.trim().startsWith("{")&&M.trim().endsWith("}")?M.trim():`"${M.trim()}"`).join(",")}]`),f})(d);return JSON.parse(l)}catch(r){return console.error(r),{as:[]}}},dt=async(d,r)=>{let{enrichedBqlQuery:l,rawBqlRequest:a,schema:F,config:f}=d,{rawTqlRes:y,isBatched:B}=r;if(l){if(!y)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let M=(i,c)=>{let{$metaData:t}=i,{as:o}=yi(t),P=Object.entries(i).filter(([w])=>w!=="type"&&!w.includes("$")).map(([w,k])=>{let q=c.dataFields?.find(h=>h.path===w||h.dbPath===w),b=w==="id",T=Array.isArray(o)?o.find(h=>h[w])?.[w]:w,L;if(q?.cardinality==="ONE"){if(L=k[0]?k[0].value:f.query?.returnNulls?null:void 0,q.contentType==="DATE"&&(L=L&&`${L}Z`),b)return [[T,L],["$id",L]].filter(([h,S])=>S!==void 0)}else if(q?.cardinality==="MANY"){if(!isArray(k))throw new Error("Typedb fetch has changed its format");if(k.length===0)return f.query?.returnNulls?[[T,null]]:[];q.contentType==="DATE"?L=k.map(h=>`${h.value}Z`):L=k.map(h=>h.value);}return [[T,L]].filter(([h,S])=>S!==void 0)}).flat();return Object.fromEntries([...P])},R=i=>i.reduce((c,t)=>{let{$roleFields:o,$metaData:P,$cardinality:w}=t,{as:k,justId:q,idNotIncluded:b,filterByUnique:T}=lt(P),L=o.map(h=>{let{dataFields:S,currentSchema:$,linkFields:E,roleFields:g,schemaValue:m}=s(h),Q=M(S,$);if(q==="T")return Q.id;{let I=e(E),O=R(g),j={...Q};return b==="true"&&$?.idFields?.forEach(D=>delete j[D]),{...j,...I,...O,...m}}});return L.length>0?c[k]=w==="MANY"&&T==="false"?L:L[0]:f.query?.returnNulls&&(c[k]=null),c},{}),e=i=>i.reduce((c,t)=>{let{$linkFields:o,$metaData:P,$cardinality:w}=t,{as:k,justId:q,idNotIncluded:b,filterByUnique:T}=lt(P),L=o.map(h=>{let{dataFields:S,currentSchema:$,linkFields:E,roleFields:g,schemaValue:m}=s(h),Q=M(S,$);if(q==="T")return Q.id;{let I=e(E),O=R(g),j={...Q};return b==="true"&&$.idFields?.forEach(D=>delete j[D]),{...j,...I,...O,...m}}});return c[k]=L.length>0?w==="MANY"&&T==="false"?L:L[0]:f.query?.returnNulls?null:void 0,c},{}),s=i=>{let c=Object.keys(i),t=c.find(h=>h.endsWith(".$dataFields"));if(!t)throw new Error("No datafields");let o=i[t],P=t.split(".")[t.split(".").length-2];if(o.$metaData=P,o.length===0)throw new Error("No datafields");let w=o.type,k={$thing:w.label,$thingType:w.root,[U]:i.queryPath.value},q={[`$${k.$thingType}`]:k.$thing},b=N(F,q),T=c.filter(h=>!h.endsWith(".$dataFields")&&b.linkFields?.some(S=>S.path===h.split(".").pop())).map(h=>({$linkFields:i[h],$key:h.split(".").pop(),$metaData:h.split(".")[h.split(".").length-2],$cardinality:b?.linkFields?.find(S=>S.path===h.split(".").pop())?.cardinality})),L=c.filter(h=>!h.endsWith(".$dataFields")&&b.roles?.[h.split(".").pop()]).map(h=>({$roleFields:i[h],$key:h.split(".").pop(),$metaData:h.split(".")[h.split(".").length-2],$cardinality:b.roles[h.split(".").pop()].cardinality}));return {dataFields:o,schemaValue:k,currentSchema:b,linkFields:T,roleFields:L}},u=i=>i.map(c=>{let{dataFields:t,currentSchema:o,linkFields:P,roleFields:w,schemaValue:k}=s(c),q=M(t,o),b=e(P),T=R(w),L=a?.$fields?.every(S=>!o?.idFields?.includes(S)&&!o?.idFields?.includes(S.$path));return {...b,...T,...k,...!f.query?.noMetadata&&a.$id?{$id:Array.isArray(a.$id)?q.id:a.$id}:{},...L?Object.fromEntries(Object.entries(q).filter(([S])=>!o?.idFields?.includes(S))):q}}),p=(i=>{let c=t=>{let o=u(t);return a.$id&&!Array.isArray(a.$id)||l[0].$filterByUnique?o[0]??null:o.length===0?null:o};return B?i.map(c):c(i)})(y);r.bqlRes=p;};var hi=Symbol.for("grandChildOfCreate"),ne=d=>({...d[Symbol.for("relation")]&&{[Symbol.for("relation")]:d[Symbol.for("relation")]},...d[Symbol.for("parent")]&&{[Symbol.for("parent")]:d[Symbol.for("parent")]},...d[Symbol.for("edgeType")]&&{[Symbol.for("edgeType")]:d[Symbol.for("edgeType")]},...d[Symbol.for("role")]&&{[Symbol.for("role")]:d[Symbol.for("role")]},...d[Symbol.for("oppositeRole")]&&{[Symbol.for("oppositeRole")]:d[Symbol.for("oppositeRole")]},...d[Symbol.for("relFieldSchema")]&&{[Symbol.for("relFieldSchema")]:d[Symbol.for("relFieldSchema")]},...d[Symbol.for("path")]&&{[Symbol.for("path")]:d[Symbol.for("path")]},...d[Symbol.for("isRoot")]&&{[Symbol.for("isRoot")]:d[Symbol.for("isRoot")]},...d[Symbol.for("depth")]&&{[Symbol.for("depth")]:d[Symbol.for("depth")]},...d[Symbol.for("schema")]&&{[Symbol.for("schema")]:d[Symbol.for("schema")]},...d[Symbol.for("dbId")]&&{[Symbol.for("dbId")]:d[Symbol.for("dbId")]},...d[Symbol.for("index")]&&{[Symbol.for("index")]:d[Symbol.for("index")]}}),ct=async d=>{let{filledBqlRequest:r,config:l,schema:a}=d,F=(b,T)=>Object.keys(b).filter(L=>L.startsWith("$")?!1:T?!N(a,b).dataFields?.find(S=>S.path===L):!0);if(!r)throw new Error("[BQLE-M-PQ-1] No filledBqlRequest found");if(l.mutation?.preQuery===!1)return;let f=[];if(traverse(r,({parent:b,key:T,value:L})=>{b&&T&&!T.includes("$")&&isObject(b)?(Array.isArray(b[T])?b[T]:[b[T]]).forEach(S=>{if(isObject(S)){if(b.$op!=="create")f.includes(S.$op)||f.push(S.$op);else if(S.$op==="delete"||S.$op==="unlink")throw new Error(`Cannot ${S.$op} under a create`)}}):!b&&isObject(L)&&(f.includes(L.$op)||f.push(L.$op));}),!f.includes("delete")&&!f.includes("unlink")&&!f.includes("replace")&&!f.includes("update")&&!f.includes("link"))return;let B=(b=>{let T=(L,h)=>{let S=[],$={},E=["$op","$bzId","$parentKey"],g=["$relation","$entity","$id",...E];for(let m in L)if(!E.includes(m)&&!(g.includes(m)&&!h))if(!m.includes("$")&&(isObject(L[m])||Array.isArray(L[m]))){let Q=L[m];Array.isArray(Q)&&Q.length>0?Q.forEach(I=>{S.push({$path:m,...T(I)});}):S.push({$path:m,...T(Q)});}else $[m]=L[m];return {...$,$fields:S}};return b.map(L=>T(L,!0))})(Array.isArray(r)?r:[r]),M=await Fe(B,d.config,d.schema,d.dbHandles),R=(b,T)=>{let L=b.$id||b.id||b.$bzId;if(b.$objectPath){let{$objectPath:h}=b,S=h?.beforePath||"root",$=Array.isArray(h.ids)?`[${h.ids}]`:h.ids;return {beforePath:`${S}.${$}___${h.key}`,ids:L,key:T}}else return {beforePath:"root",ids:L,key:T}},e=(b,T)=>{let L=b?.beforePath||"root",h=T||(Array.isArray(b?.ids)?`[${b?.ids}]`:b?.ids);return `${L}.${h}___${b?.key}`},s=b=>{if(b.includes("[")&&b.includes("]")){let[T,L,h]=b.split(/[[\]]/);return L.split(",").map($=>`${T}${$}${h}`)}else return [b]},u={};(b=>produce(b,T=>traverse(T,L=>{let{key:h,parent:S}=L;if(S&&h&&S.$id&&!h.includes("$")){let $=R(S,h),E=e($);if(Array.isArray(S[h])){let g=[];S[h].forEach(m=>{isObject(m)?(m.$objectPath=$,g.push(m.$id.toString())):m&&g.push(m.toString());}),u[E]={$objectPath:$,$ids:g};}else {let g=S[h];isObject(g)?(u[E]={$objectPath:$,$ids:[g.$id.toString()]},g.$objectPath=$):g&&(u[E]={$objectPath:$,$ids:[g.toString()]});}}})))(M||{});let p=b=>produce(b,T=>traverse(T,L=>{let{key:h,value:S,parent:$}=L;$&&h&&!h.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray($)&&(Array.isArray($[h])?$[h].forEach(E=>{typeof E!="string"&&(E.$objectPath=R($,h),E.$parentIsCreate=$.$op==="create",E[hi]=$.$parentIsCreate||$[Symbol.for("grandChildOfCreate")]);}):isObject($[h])&&($[h].$parentIsCreate=$.$op==="create",$[h][Symbol.for("grandChildOfCreate")]=$.$parentIsCreate||$[Symbol.for("grandChildOfCreate")],$[h].$objectPath=R($,h)));})),i=p(r),t=(b=>{let T=($,E)=>{let g=[];$.filter(O=>O).forEach(O=>{let j=Object.keys(O).filter(D=>!D.startsWith("$")).length;if(Array.isArray(O.$id)&&j>0){let D=O.$id.map(z=>({...O,$id:z}));g=[...g,...D];}else g.push({...O});});let m=[],Q=[],I=g.filter(O=>{let D=["delete","update","unlink"].includes(O.$op||""),z=F(O,!0).length;if((!O.$id||Array.isArray(O.$id)&&z>0||O.$filter)&&D)return !0;Q.push({...O});});return I.length>0?I.forEach(O=>{let D=(x=>{let se=(()=>{let _={};for(let C in x){let Y=N(a,x);!C.startsWith("$")&&Y.dataFields?.find(re=>re.path===C)&&(_[C]=x[C]);}return _})(),ae=Object.keys(x),Z=ae.filter(_=>!_.startsWith("$")),we=[],ye=(_,C)=>{if(_===Z.length){let re={...C};ae.forEach(V=>{V.startsWith("$")&&(re[V]=x[V]);}),we.push(re);return}let Y={...C,[Z[_]]:x[Z[_]],...ne(C),...se};ye(_+1,Y),ye(_+1,C);};return ye(0,{...ne(x)}),we})(O).filter(x=>!(x.$op==="update"&&Object.keys(x).filter(ee=>!ee.startsWith("$")).length===0)),z=[],J=e(O.$objectPath),v=u[J]?u[J].$ids:[],A=D.map((x,ee)=>{let se=N(a,x),Z=Object.keys(x).filter(C=>!C.includes("$")&&!se.dataFields?.some(Y=>Y.path===C)).map(C=>(Array.isArray(x[C])?x[C].length>1?x[C].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):x[C]:[x[C]]).map(V=>{let Ee=e(V.$objectPath);return {idsToKey:(Le=>{let je=[],de=Le.split("."),Ot=de.slice(0,de.length-1).join("."),At=de.slice(de.length-1,de.length)[0].split("___")[1];for(let Me in u)if(Me.startsWith(Ot)&&Me.endsWith(At)){let Te=Me.split("."),Ct=Te.slice(Te.length-1,Te.length)[0].split("___")[0];je.push(Ct);}return je})(Ee),key:C,multiple:V}})).filter(C=>C!==void 0),_=(C=>{let Y=C.map(V=>V.map(te=>te.idsToKey));return (V=>V.length>0?V.reduce((te,le)=>te.concat(le),[]).reduce((te,le)=>te?le.filter(Le=>te.includes(Le)):le):[])(Y)})(Z).filter(C=>!z.includes(C));if(z=[...z,..._],v=v.filter(C=>!_.includes(C)),ee===D.length-1&&v.length>0)return {...x,$id:v,$bzId:`T_${v4()}`,...ne(x)};if(_.length>0)return {...x,$id:_,$bzId:`T_${v4()}`,...ne(x)}}).filter(x=>x!==void 0),qt=(()=>{if(A.length===0&&!E?.$id)return I;if(A.length===0&&E?.$id){let x=Array.isArray(E.$id)?E.$id:[E.$id],ee=[];return x.forEach(se=>{let ae=e({...O.$objectPath,ids:se}),Z=u[ae];Z&&ee.push({...O,$id:Z.$ids,...ne(O),$bzId:`T_${v4()}`});}),ee}else return A})();m=[...Q,...qt].map(L);}):m=g.map(L),m},L=$=>{let E={...$,$bzId:`T_${v4()}`,...ne($)},g=N(a,$);return Object.keys($).filter(m=>!m.includes("$")&&!g.dataFields?.some(Q=>Q.path===m)).forEach(m=>{let Q=Array.isArray($[m])?$[m]:[$[m]],I=T(Q,$);E[m]=I.length>0?I:void 0;}),E},h=[];return b.forEach($=>{h=[...h,...T([$])];}),h.map($=>L($))})(Array.isArray(i)?i:[i]),o=b=>b.map(T=>{let L=F(T,!0),h={...T};return L.forEach(S=>{let $=Array.isArray(T[S])?T[S]:[T[S]],E=[],g=[],m=[],Q={},I=Se(a,T,S);$.filter(A=>A).forEach(A=>{A.$op==="replace"&&A.$id?(Q=A,Array.isArray(A.$id)?g=[...g,...A.$id]:g.push(A.$id)):A.$op==="create"&&I==="ONE"&&A.id?(Q=A,Array.isArray(A.id)?m=[...g,...A.id]:m.push(A.id)):E.push(A);});let O=e(Q.$objectPath),D=s(O).map(A=>u[A]),z=[];D.filter(A=>A!=null).forEach(A=>{z=[...z,...A.$ids];});let J=z.filter(A=>!g.includes(A)),K=g.filter(A=>!z.includes(A)),v=ne(Q);J.length>0&&E.push({...Q,$op:"unlink",$id:J,$bzId:`T_${v4()}`,id:void 0,...v}),K.length>0&&K.forEach(A=>{E.push({...Q,$op:"link",$id:A,$bzId:`T_${v4()}`,...v});}),m.length>0&&m.forEach(A=>{E.push({...Q,$op:"create",id:A,$bzId:`T_${v4()}`,...v});}),h[S]=o(E);}),h}),P=p(o(p(t)));(b=>produce(b,T=>traverse(T,L=>{let{key:h,value:S,parent:$}=L;h&&$&&!h?.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray($)&&(Array.isArray(S)?S:[S]).forEach(g=>{let m=u[e(g.$objectPath)],Q=(j,D)=>j.every(z=>D.includes(z)),I=g.$id?Array.isArray(g.$id)?Q(g.$id,m?m.$ids:[]):m?.$ids.includes(g.$id):m,O=Se(a,$,g.$objectPath.key);if(g.$op==="link"&&I&&O==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${e(g.$objectPath)}" because it is already occupied.`);if(g.$op)switch(g.$op){case"delete":if(!I&&!l.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${g.$id}" because it is not linked to $id:"${$.$id}"`);break;case"update":if(!I&&!l.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${g.$id}" because it is not linked to $id:"${$.$id}"`);break;case"unlink":if(!I&&!l.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${g.$id}" because it is not linked to $id:"${$.$id}"`);break;case"link":if(I)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${g.$id}" because it is already linked to $id:"${$.$id}"`);break;}});})))(P);let q=(b=>produce(b,T=>traverse(T,L=>{let{parent:h,key:S,value:$,meta:E}=L;isObject($)&&($[Symbol.for("path")]=E.nodePath,delete $.$objectPath,delete $.$parentIsCreate),S&&h&&!S?.includes("$")&&(Array.isArray($)||isObject($))&&!Array.isArray(h)&&(Array.isArray($)?$:[$]).forEach(m=>{isObject(m)&&(m[Symbol.for("parent")]={...$[Symbol.for("parent")],path:h[Symbol.for("path")]});});})))(P);d.filledBqlRequest=q;};var yt=async d=>{let{filledBqlRequest:r,schema:l}=d;if(!r)throw new Error("Filled BQL request is missing");let F=(B=>produce(B,M=>traverse(M,({value:R})=>{if(isObject(R)){let e=R,s=N(l,e),{unidentifiedFields:u}=G(s,e),{idFields:n,computedFields:p,virtualFields:i}=s;if(!n)throw new Error("No idFields found");let[c]=n,t=listify(e,(w,k)=>k!==void 0?w:void 0),o=t.filter(w=>i?.includes(w));if(o.length>0)throw new Error(`Virtual fields can't be sent to DB: "${o.join(",")}"`);if(p.filter(w=>!t.includes(w)).forEach(w=>{let k=s.dataFields?.find(h=>h.path===w),b=s.linkFields?.find(h=>h.path===w)?.oppositeLinkFieldsPlayedBy[0],T="roles"in s?pe(s.roles,(h,S)=>h===w):void 0,L=k||b||T;if(!L)throw new Error(`no field Def for ${w}`);if(w!==c&&e.$op==="create"&&!e[w]){let h=X({currentThing:e,fieldSchema:L,mandatoryDependencies:!0});e[w]=h;}}),u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(e)}`)}})))(r),y=(B=>produce(B,M=>traverse(M,({value:R})=>{isObject(R);})))(F);d.filledBqlRequest=y;};var gt=async d=>{let{filledBqlRequest:r}=d;if(!r)throw new Error("Filled BQL request is missing");let a=(y=>produce(y,B=>traverse(B,({value:M})=>{isObject(M)&&Je();})))(r),f=(y=>produce(y,B=>traverse(B,({value:M})=>{isObject(M);})))(a);d.filledBqlRequest=f;};var wt=async d=>{let{filledBqlRequest:r}=d;if(!r)throw new Error("Filled BQL request is missing");let l=F=>produce(F,f=>traverse(f,({value:y})=>{if(isObject(y)&&("$entity"in y||"$relation"in y)){let B=y,{requiredFields:M,enumFields:R,fnValidatedFields:e}=B[be];"$op"in B&&B.$op==="create"&&M.forEach(s=>{if(!(s in B))throw new Error(`[Validations] Required field "${s}" is missing.`)}),("$op"in B&&B.$op==="update"||B.$op==="create")&&R.forEach(s=>{if(s in B){let u=B[be]?.dataFields?.find(n=>n.path===s)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${s}" is missing enum options.`);if(isArray(B[s]))B[s].some(n=>{if(!u.includes(n))throw new Error(`[Validations] Option "${n}" is not a valid option for field "${s}".`)});else if(u&&!u.includes(B[s]))throw new Error(`[Validations] Option "${B[s]}" is not a valid option for field "${s}".`)}}),("$op"in B&&B.$op==="update"||B.$op==="create")&&e.forEach(s=>{if(s in B)try{let u=B[be]?.dataFields?.find(n=>n.path===s)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(B[s]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${s}] ${u.message}`)}});}})),a=F=>produce(F,f=>traverse(f,({value:y,parent:B,meta:M})=>{if(isObject(y)&&("$entity"in y||"$relation"in y)){let R="$entity"in y?y.$entity:y.$relation,e=y,s=y[Symbol.for("schema")].hooks;if(s){let{pre:u}=s;if(u){let n=`on${_e(e.$op)}`;u.filter(i=>i.triggers[n]).forEach(i=>{let c=n in i.triggers?i.triggers[n]:void 0;if(c!==void 0&&c()){let t=Ve(F,B,M);i.actions.forEach(o=>{if(o.type==="validate"){if(o.severity!=="error")return;try{let P=o.fn(e,t);if(P===!1)throw new Error(`${o.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}`)}}});}});}}}}));l(r),a(r);};var Et=async(d,r)=>{let{schema:l,enrichedBqlQuery:a}=d,{bqlRes:F}=r;if(!F)return;let y=(B=>produce(B,M=>traverse(M,({value:R})=>{if(isObject(R)){let e=R;if(!e.$thing)throw new Error("[Internal] Thing is missing");if(e.$thing){let s=N(l,e),{virtualFields:u}=s,n=e[U];if(!n)throw new Error("[Internal] QueryPath is missing");let p=getNodeByPath(a,n),i=p.$fields.map(t=>t.$path),c=p.$excludedFields;u.forEach(t=>{if(c?.includes(t)||i.length>0&&!i.includes(t))return;let o=s.dataFields?.find(P=>P.path===t);if(o?.default){let P=X({currentThing:e,fieldSchema:o,mandatoryDependencies:!0});e[t]=P;}else if(e[t]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${t}`)}),c&&c.forEach(t=>{if(typeof t!="string")throw new Error("[Internal] ExcludedField is not a string");delete e[t];});}}})))(F);r.bqlRes=y;};var kt=async(d,r)=>{let{config:l}=d,{bqlRes:a}=r;if(!a)return;let f=(M=>produce(M,R=>traverse(R,({value:e})=>{isObject(e);})))(a),B=(M=>produce(M,R=>traverse(R,({value:e})=>{if(isObject(e)){let s=e;Object.keys(s).forEach(u=>{s[u]===void 0&&delete s[u];}),Object.getOwnPropertySymbols(s).forEach(u=>{delete s[u];}),l.query?.noMetadata===!0&&Object.keys(s).forEach(u=>{u.startsWith("$")&&delete s[u];});}})))(f);r.bqlRes=B;};var Qt={query:[ot,nt,at,dt,Et,kt],mutation:[Ye,ct,yt,gt,wt,tt,Ue,it,We,He]},Ae=async(d,r,l={},a=!0)=>{for(let F of d){let f=await F(r,l);if(f&&Array.isArray(f))for(let y of f)await Ae(y.pipeline,y.req,y.res,!1);}return a&&r.config.query?.debugger===!0&&typeof l.bqlRes=="object"?{...l.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:l.bqlRes},Fe=(d,r,l,a)=>Ae(Qt.query,{config:r,schema:l,rawBqlRequest:d,dbHandles:a},{}),St=(d,r,l,a)=>Ae(Qt.mutation,{config:r,schema:l,rawBqlRequest:d,dbHandles:a},{});var Ce=class{schema;config;dbHandles;constructor({schema:r,config:l}){this.schema=r,this.config=l;}getDbHandles=()=>this.dbHandles;init=async()=>{let r={typeDB:new Map},l=ze(this.schema);await Promise.all(this.config.dbConnectors.map(async a=>{if(a.provider==="typeDB"&&a.dbName){let[F,f]=await tryit(TypeDB.coreDriver)(a.url);if(F){let y=`[BORM:${a.provider}:${a.dbName}:core] ${F.message??"Can't create TypeDB Client"}`;throw new Error(y)}try{let y=await f.session(a.dbName,SessionType.DATA);r.typeDB.set(a.id,{client:f,session:y});}catch(y){let B=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(a.provider==="typeDBCluster"&&a.dbName){let[F,f]=await tryit(TypeDB.cloudDriver)(a.addresses,a.credentials);if(F){let y=`[BORM:${a.provider}:${a.dbName}:core] ${F.message??"Can't create TypeDB Cluster Client"}`;throw new Error(y)}try{let y=await f.session(a.dbName,SessionType.DATA);r.typeDB.set(a.id,{client:f,session:y});}catch(y){let B=`[BORM:${a.provider}:${a.dbName}:session] ${(y.messageTemplate?._messageBody()||y.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}})),this.schema=l,this.dbHandles=r;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),De(this.config,this.schema,this.dbHandles));query=async(r,l)=>{await this.#e();let a={...this.config,query:{...ke.query,...this.config.query,...l}};return Fe(r,a,this.schema,this.dbHandles)};mutate=async(r,l)=>{await this.#e();let a={...this.config,mutation:{...ke.mutation,...this.config.mutation,...l}};return St(r,a,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:r,session:l})=>{l.isOpen()&&await l.close(),await r.close();});}},vr=Ce;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
59
59
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
60
60
|
//! disabled as it has false positives
|
|
61
|
+
//!todo: use computeNode() in the future instead
|
|
61
62
|
|
|
62
|
-
export {
|
|
63
|
+
export { vr as default };
|