@blitznocode/blitz-orm 0.11.12 → 0.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -2
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -711,7 +711,6 @@ type NextPipeline<Res extends BaseResponse> = {
|
|
|
711
711
|
type PipelineOperation<Res extends BaseResponse> = (req: Request, res: Res) => Promise<void | NextPipeline<Res>[]>;
|
|
712
712
|
type Pipeline<Res extends BaseResponse> = PipelineOperation<Res>[];
|
|
713
713
|
|
|
714
|
-
declare const VERSION: string | undefined;
|
|
715
714
|
type BormProps = {
|
|
716
715
|
schema: BormSchema;
|
|
717
716
|
config: BormConfig;
|
|
@@ -736,4 +735,4 @@ declare class BormClient {
|
|
|
736
735
|
close: () => Promise<void>;
|
|
737
736
|
}
|
|
738
737
|
|
|
739
|
-
export { type Action, type AllDbHandles, type BQLField, type BQLFieldObj, type BQLMutation, type BQLMutationBlock, type BQLResponse, type BQLResponseMulti, type BQLResponseSingle, type BaseResponse, type BormConfig, type BormEntity, type BormField, type BormMetadata, type BormOperation, type BormRelation, type BormSchema, type BormTrigger, type Cardinality, type CommonProvider, type ContentType, type ContentTypeMapping, type DBConnector, type DBHandleKey, type DBHandles, type DataField, type DiscreteCardinality, type EnrichedAttributeQuery, type EnrichedBQLMutationBlock, type EnrichedBQLQuery, type EnrichedBormEntity, type EnrichedBormRelation, type EnrichedBormSchema, type EnrichedDataField, type EnrichedEntityQuery, type EnrichedFieldQuery, type EnrichedLinkField, type EnrichedLinkQuery, type EnrichedRelationQuery, type EnrichedRoleField, type EnrichedRoleQuery, type FilledBQLMutationBlock, type Filter, type FilterValue, type Hooks, type LinkField, type LinkedFieldWithThing, type MutationConfig, type NegativeFilter, type NodeFunctionParams, type ParsedBQLMutation, type Pipeline, type PipelineOperation, type PlayedBy, type PositiveFilter, type PreHook, type Provider, type QueryConfig, type RawBQLMutation, type RawBQLQuery, type Request, type RightType, type RoleField, type RootBQLMutationBlock, type Sorter, type TQLEntityMutation, type TQLRequest, type ThingType, type TransFormAction, type TypeDBClusterProvider, type TypeDBHandles, type TypeDBProvider, type TypeGen,
|
|
738
|
+
export { type Action, type AllDbHandles, type BQLField, type BQLFieldObj, type BQLMutation, type BQLMutationBlock, type BQLResponse, type BQLResponseMulti, type BQLResponseSingle, type BaseResponse, type BormConfig, type BormEntity, type BormField, type BormMetadata, type BormOperation, type BormRelation, type BormSchema, type BormTrigger, type Cardinality, type CommonProvider, type ContentType, type ContentTypeMapping, type DBConnector, type DBHandleKey, type DBHandles, type DataField, type DiscreteCardinality, type EnrichedAttributeQuery, type EnrichedBQLMutationBlock, type EnrichedBQLQuery, type EnrichedBormEntity, type EnrichedBormRelation, type EnrichedBormSchema, type EnrichedDataField, type EnrichedEntityQuery, type EnrichedFieldQuery, type EnrichedLinkField, type EnrichedLinkQuery, type EnrichedRelationQuery, type EnrichedRoleField, type EnrichedRoleQuery, type FilledBQLMutationBlock, type Filter, type FilterValue, type Hooks, type LinkField, type LinkedFieldWithThing, type MutationConfig, type NegativeFilter, type NodeFunctionParams, type ParsedBQLMutation, type Pipeline, type PipelineOperation, type PlayedBy, type PositiveFilter, type PreHook, type Provider, type QueryConfig, type RawBQLMutation, type RawBQLQuery, type Request, type RightType, type RoleField, type RootBQLMutationBlock, type Sorter, type TQLEntityMutation, type TQLRequest, type ThingType, type TransFormAction, type TypeDBClusterProvider, type TypeDBHandles, type TypeDBProvider, type TypeGen, type ValidateAction, type Validations, type WithBormMetadata, BormClient as default };
|
package/dist/index.mjs
CHANGED
|
@@ -94,7 +94,7 @@ ${o}`}).join(`
|
|
|
94
94
|
`)},_t=e=>{let{queries:t,schema:r,level:n,parentQuery:s}=e,i=[],a=s[ie];return i.push(M(`"${a}" as \`$$queryPath\``,n)),i.push(M("record::id(id) as `$id`",n)),i.push(M("record::tb(id) as `$thing`",n)),t.forEach(o=>{let c=Mo({query:o,level:n,schema:r});c&&i.push(c);}),i.length===0?null:i.join(`,
|
|
95
95
|
`)},Mo=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?So({query:t,level:n}):t.$fieldType==="link"?Lo({query:t,level:n,schema:r}):t.$fieldType==="role"?Qo({query:t,level:n,schema:r}):null},So=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},Lo=e=>{let{query:t,schema:r,level:n}=e,{$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push(M("(",n));let u=n+1;p.push(M("SELECT",u));let d=_t({parentQuery:t,queries:s,level:u+1,schema:r});d&&p.push(d);let l=t[oe][Se].queryPath;if(p.push(M(`FROM ${l}`,u)),i){let f=ye(i,t.$thing,r),h=pe(f);p.push(`WHERE ${h}`);}return c&&p.push(M(Ve(c),u)),typeof o=="number"&&p.push(M(`LIMIT ${o}`,u)),typeof a=="number"&&p.push(M(`START ${a}`,u)),p.push(M(`) AS \`${t.$as}\``,n)),p.join(`
|
|
96
96
|
`)},Qo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let s=[];s.push(M("(",n));let i=n+1;s.push(M("SELECT",i));let a=i+1,o=_t({parentQuery:t,queries:t.$fields,level:a,schema:r});o&&s.push(o);let c=t[oe][Se].queryPath;if(s.push(M(`FROM ${c}`,i)),t.$filter){let p=ye(t.$filter,t.$playedBy.thing,r),u=pe(p);s.push(`WHERE ${u}`);}return s.push(M(`) AS \`${t.$as}\``,n)),s.join(`
|
|
97
|
-
`)};var mn=async e=>{let{client:t,queries:r,config:n}=e,s=`
|
|
97
|
+
`)};var De="0.11.14";var mn=async e=>{let{client:t,queries:r,config:n}=e,s=`
|
|
98
98
|
BEGIN TRANSACTION;
|
|
99
99
|
${r.join(";")};
|
|
100
100
|
COMMIT TRANSACTION;
|
|
@@ -108,7 +108,7 @@ ${m}`);}let f=Yt({schema:r,$thing:s,$var:n,$sort:o,depth:0});f&&d.push(f.match);
|
|
|
108
108
|
offset ${c};`),typeof p=="number"&&d.push(`
|
|
109
109
|
limit ${p};`),d.join(`
|
|
110
110
|
`)},Kt=(e,t,r)=>{let n=[],s=[],i=[];for(let u=0;u<e.length;u++)e[u].$isVirtual||n.push(e[u].$dbPath),e[u][oe].contentType==="FLEX"&&i.push({path:e[u][oe].dbPath}),s.push(`{${e[u].$dbPath}:${e[u].$as}}`);let a=n.join(", "),c=`$metadata:{as:[${s.join(",")}]}`,p=[M(`$${t} as "${t}.${c}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(u=>{p.push(M(`"${u.path}.$multiVal": {match $${t} has ${u.path} $${u.path}; fetch $${u.path}: attribute;};`,r));}),p},vt=(e,t,r,n,s)=>{let i=n+1,a=[];for(let o of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:d,$filterByUnique:l,$thing:f,$sort:h,$offset:$,$limit:g}=o,m=o[ie],F=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${F}.${o.$var}": {`,n)),a.push(M("match",i));let b=`${t}${Ht}${o.$var}`;if(a.push(M(`$${b} isa ${o.$thing};`,i)),a.push(M(`$${t} (${o.$var}: $${t}${Ht}${o.$var}) isa ${o.$intermediary};`,i)),o.$filter||o.$id){let R=ot(s,o),L=o.$id?{[R]:o.$id}:{},D={...o.$filter,...L};a.push(pt({$filter:D,$var:b,$thing:o.$thing,schema:s,depth:i}));}let y=Yt({schema:s,$thing:f,$var:b,$sort:h,depth:i});if(y&&a.push(y.match),c){let R=`M_${v4()}`;a.push(M(`
|
|
111
|
-
?queryPath${R} = "${m}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${R} as "queryPath";`,i));let L=c?.filter(_=>_.$fieldType==="data");L&&L.length>0&&a.push(...Kt(L,b,i));let D=c?.filter(_=>_.$fieldType==="link");D&&D.length>0&&a.push(...Jt(D,b,`${t}.${o.$var}`,i,s));let C=c?.filter(_=>_.$fieldType==="role");C&&C.length>0&&a.push(...vt(C,b,`${t}.${o.$var}`,i,s));}y&&a.push(y.sort),typeof $=="number"&&a.push(M(`offset ${$};`,i)),typeof g=="number"&&a.push(M(`limit ${g};`,i)),a.push(M("};",n));}return a},Jt=(e,t,r,n,s)=>{let i=n+1,a=[];for(let o of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:d,$filterByUnique:l,$playedBy:f,$thing:h,$sort:$,$offset:g,$limit:m}=o,F=o[ie],b=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${b}.${o.$var}": {`,n)),a.push(M("match",i));let y=`${t}${Ht}${o.$var}`;if(a.push(M(`$${y} isa ${o.$thing};`,i)),o.$filter||o.$id){let L=ot(s,o),D=o.$id?{[L]:o.$id}:{},C={...o.$filter,...D};a.push(pt({$filter:C,$var:y,$thing:o.$thing,schema:s,depth:i}));}let R=Yt({schema:s,$thing:h,$var:y,$sort:$,depth:i});if(R&&a.push(R.match),o.$target==="role"?a.push(M(`$${t}_intermediary (${o.$plays}: $${t}, ${f.plays}: $${y}) isa ${o.$intermediary};`,i)):a.push(M(`$${y} (${o.$plays}: $${t});`,i)),c){let L=`M_${v4()}`;a.push(M(`?queryPath${L} = "${F}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${L} as "queryPath";`,i));let D=c?.filter(J=>J.$fieldType==="data");D&&D.length>0&&a.push(...Kt(D,y,i));let C=c?.filter(J=>J.$fieldType==="link");C&&C.length>0&&a.push(...Jt(C,y,`${t}.${o.$var}`,i,s));let _=c?.filter(J=>J.$fieldType==="role");_&&_.length>0&&a.push(...vt(_,y,`${t}.${o.$var}`,i,s));}R&&a.push(R.sort),typeof g=="number"&&a.push(M(`offset ${g};`,i)),typeof m=="number"&&a.push(M(`limit ${m};`,i)),a.push(M("};",n));}return a},jo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Yt=e=>{let{$var:t,$thing:r,schema:n,$sort:s,depth:i}=e,a=v(n,r),o=[],c=[];if(s?.forEach(p=>{let u=jo(p),d=a.dataFields?.find(h=>h.path===u.field);if(!d)throw new Error(`"${r}" does not have data field "${u.field}"`);let l=`${u.field}_${v4()}`;o.push(M("{",i)),o.push(M(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),o.push(M("not {",i+1)),o.push(M(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),o.push(M(`$${l}_2 < $${l}_1;`,i+2)),o.push(M("};",i+1)),o.push(M(`?${l}_ = $${l}_1;`,i+1)),o.push(M("} or {",i)),o.push(M(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),o.push(M(`?${l}_ = "~";`,i+1)),o.push(M("};",i)),o.push(M(`?${l} = ?${l}_;`,i));let f=u.desc?"desc":"asc";c.push(`?${l} ${f}`);}),o.length!==0)return {match:o.join(""),sort:M(`sort ${c.join(", ")};`,i)}};var Rn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:s,rawTqlRes:i}=e;if(t){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((a,o)=>{let c=r[o],p=t[o];return Uo(a,c,p,n,s)})},Uo=(e,t,r,n,s)=>e.length===0?null:r.$filterByUnique?Qn(e[0],t,n,s):e.map(i=>Qn(i,t,n,s)),Qn=(e,t,r,n)=>{let{dataFields:s,currentSchema:i,linkFields:a,roleFields:o,schemaValue:c}=Gt(e,r),p=Xt(s,i,n),u=er(a,r,n),d=Zt(o,r,n),l=t?.$fields?.every(h=>!i?.idFields?.includes(typeof h=="string"?h:h.$path));return {...u,...d,...c,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...l?Object.fromEntries(Object.entries(p).filter(([h])=>!i?.idFields?.includes(h))):p}},Gt=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),s=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");s?.length>0&&s.forEach(f=>{let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let o=i.type,c={$thing:o.label,$thingType:o.root,[ie]:e.queryPath.value},p={[`$${c.$thingType}`]:c.$thing},u=N(t,p),d=r.filter(f=>{let h=he(f.split(".").pop());return !f.endsWith(".$dataFields")&&u.linkFields?.some($=>$.path===h)}).map(f=>{let h=he(f.split(".").pop()),$=he(u.linkFields?.find(g=>g.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&u.thingType==="relation"&&u.roles?.[h]}).map(f=>{let h=he(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:u.roles[h].cardinality}});return {dataFields:i,schemaValue:c,currentSchema:u,linkFields:d,roleFields:l}},Xt=(e,t,r)=>{let{$metaData:n}=e,{as:s}=Wo(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,o])=>{let c=t.dataFields?.find(l=>l.path===a||l.dbPath===a),p=a==="id",u=Array.isArray(s)?s.find(l=>l[a])?.[a]:a,d;if(c?.cardinality==="ONE"){if(d=o[0]?o[0].value:r.query?.returnNulls?null:void 0,c.contentType==="DATE"||c.contentType==="FLEX"&&o[0].type.value_type==="datetime"?d=d&&`${d}Z`:c.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[u,d],["$id",d]].filter(([l,f])=>f!==void 0)}else if(c?.cardinality==="MANY"){if(!isArray(o))throw new Error("Typedb fetch has changed its format");if(o.length===0)return r.query?.returnNulls?[[u,null]]:[];c.contentType==="DATE"?d=o.map(l=>`${l.value}Z`):c.contentType==="FLEX"?d=o.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):c.contentType==="JSON"?d=o.map(l=>l.value&&JSON.parse(l.value)):d=o.map(l=>l.value);}return [[u,d]].filter(([l,f])=>f!==void 0)}).flat();return Object.fromEntries([...i])},Zt=(e,t,r)=>{let n={};return e.forEach(s=>{let{$roleFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Dn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:F}=Gt(f,t),b=Xt(h,$,r);if(p==="T")return b.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...b};return u==="true"&&$?.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...F}}});l.length>0?n[c]=o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[c]=null);}),n},er=(e,t,r)=>{let n={};return e.forEach(s=>{let{$linkFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Dn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:F}=Gt(f,t),b=Xt(h,$,r);if(p==="T")return b.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...b};return u==="true"&&$.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...F}}});n[c]=l.length>0?o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},Dn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,s=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),o=e.match(n),c=e.match(s);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:o?o[1]:null,filterByUnique:c?c[1]:null}},Wo=e=>{try{let r=(s=>{let i=s.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,o,c)=>/^{.*}$/.test(c)?`:${c}`:`:${o}"${c}"`),i=i.replace(/\[([^\]]+)\]/g,(a,o)=>`[${o.split(",").map(c=>c.trim().startsWith("{")&&c.trim().endsWith("}")?c.trim():`"${c.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var $t=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,s=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!s)throw new Error("Client not found");n=await s.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:s,session:n});}return {client:s,session:n}};var Cn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,s=new TypeDBOptions;s.infer=!0;let{session:i}=await $t(r,n),a=await i.transaction(TransactionType.READ,s),[o,c]=await tryit(parallel)(t.length,t,async p=>await a.query.fetch(p).collect());if(o){await a.rollback();let p=o;throw new Error(`Error running TQL query: ${p.errors}`)}return await a.close(),c};var Jo=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Yo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Go=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,tr=j("error","error",x((e,t)=>({...e,error:t.error}))),Xo=me("build",{build:z(async e=>Ln({queries:e.bql.queries,schema:e.schema}),j("done","run",x(Yo)),tr),run:z(async e=>Cn({dbHandles:e.handles,tqlRequest:he(e.tql.queries),config:e.config}),j("done","parse",x(Go)),tr),parse:z(async e=>Rn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:he(e.tql.res)}),j("done","success",x(Jo)),tr),success:se(),error:se()},e=>e),Zo=async e=>new Promise((t,r)=>{fe(Xo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),In=async(e,t,r,n,s)=>Zo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:s,error:null});var es=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,rr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,mt=j("error","error",x((e,t)=>({...e,error:t.error}))),ts=me("enrich",{enrich:z(async e=>(e.config.query?.debugger&&console.log(`originalBQLQuery[${De}]`,e.bql.raw),Vr(e.bql.raw,e.schema)),j("done","adapter",x(es)),mt),adapter:z(async e=>{let t={};e.bql.queries?.forEach((o,c)=>{let p=e.bql.raw[c],u=v(e.schema,o.$thing),{id:d}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let l=t[d];l.rawBql.push(p),l.bqlQueries.push(o),l.indices.push(c);});let r=Object.values(t),n=r.map(o=>{if(o.db==="typeDB")return In(o.rawBql,o.bqlQueries,e.schema,e.config,e.handles);if(o.db==="surrealDB")return wn(o.bqlQueries,e.schema,e.config,o.client);throw new Error(`Unsupported DB "${JSON.stringify(o,null,2)}"`)}),s=await Promise.all(n),i=r.flatMap((o,c)=>{let p=s[c];return o.indices.map((u,d)=>({index:u,result:p[d]}))});return i.sort((o,c)=>o.index<c.index?-1:o.index>c.index?1:0),i.map(({result:o})=>o)},j("done","postHooks",x(rr)),mt),postHooks:z(async e=>pn(e.schema,he(e.bql.queries),he(e.bql.res)),j("done","clean",x(rr)),mt),clean:z(async e=>hn(e.config,he(e.bql.res)),j("done","success",x(rr)),mt),success:se(),error:se()},e=>e),rs=async e=>new Promise((t,r)=>{fe(ts,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>rs({bql:{raw:e},schema:t,config:r,handles:n,error:null});var nr="___",is=Symbol.for("grandChildOfCreate"),An=async(e,t,r,n)=>{let s=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(E,B)=>Object.keys(E).filter(T=>!T.startsWith("$")&&!s.includes(T)&&E[T]!==void 0?B?!N(t,E).dataFields?.find(w=>w.path===T):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let a=[];if(traverse(e,({parent:E,key:B,value:T})=>{E&&B&&!B.includes("$")&&!s.includes(B)&&isObject(E)?(Array.isArray(E[B])?E[B]:[E[B]]).forEach(w=>{if(isObject(w)){if(E.$op!=="create")a.includes(w.$op)||a.push(w.$op);else if(w.$op==="delete"||w.$op==="unlink")throw new Error(`Cannot ${w.$op} under a create`)}}):!E&&isObject(T)&&(a.includes(T.$op)||a.push(T.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let c=(E=>{let B=(T,S)=>{let w=[],Q={},A=["$op","$bzId","$parentKey"],U=["$relation","$entity","$id",...A];for(let P in T)if(!A.includes(P)&&!(U.includes(P)&&!S))if(!P.includes("$")&&(isObject(T[P])||Array.isArray(T[P]))){let Z=os(T[P]);if(Array.isArray(Z)&&Z.length>0)Z.forEach(Be=>{let ge={$path:P,...B(Be),...Be.$filter&&{$as:Be.$bzId}};w.find(Y=>Y.$path===ge.$path&&!Y.$filter)||(w=[...w,ge]);});else {let Be={$path:P,...B(Z),...!Z.$filter&&{$as:Z.$bzId}};w=[...w,Be];}}else Q[P]=T[P];return {...Q,$fields:w}};return E.map(T=>B(T,!0))})(Array.isArray(e)?e:[e]),u=(await ze(c,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,d=(E,B)=>{let T=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:S}=E,w=S?.beforePath||"root",Q=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${w}.${Q}___${S.key}`,ids:T,key:B}}else return {beforePath:"root",ids:T,key:B}},l=(E,B)=>{let T=E?.beforePath||"root";if(typeof T!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${T}.${S}___${E?.key}`},f=E=>{if(E.includes("[")&&E.includes("]")){let[B,T,S]=E.split(/[[\]]/);return T.split(",").map(Q=>`${B}${Q}${S}`)}else return [E]},h={};(E=>produce(E,B=>traverse(B,({key:T,parent:S})=>{if(S&&T&&S.$id&&!T.includes("$")){let w=d(S,T),Q=l(w);if(Array.isArray(S[T])){let A=[];S[T].forEach(U=>{isObject(U)?(U.$objectPath=w,A.push(U.$id.toString())):U&&A.push(U.toString());}),h[Q]={$objectPath:w,$ids:A};}else {let A=S[T];isObject(A)?(h[Q]={$objectPath:w,$ids:[A.$id.toString()]},A.$objectPath=w):A?h[Q]={$objectPath:w,$ids:[A.toString()]}:A===null&&(h[Q]=null);}}})))(u||{});let g=E=>produce(E,B=>traverse(B,({key:T,value:S,parent:w})=>{w&&T&&!T.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(w)&&(Array.isArray(w[T])?w[T].forEach(Q=>{typeof Q!="string"&&(Q.$objectPath=d(w,T),Q.$parentIsCreate=w.$op==="create",Q[is]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[T])&&(w[T].$parentIsCreate=w.$op==="create",w[T][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[T].$objectPath=d(w,T)));})),m=g(e),F=E=>{let B=[];return E.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let w=l({...S.$objectPath,key:S.$bzId}),Q=h[w];Q&&(Array.isArray(Q.$ids)?Q.$ids:[Q.$ids]).forEach(U=>{let P={...S,$id:U,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};B.push(P);});}else {let w=l(S.$objectPath),Q=h[w];Q?Q?.$ids?.forEach(A=>{let U={...S,$id:A,$bzId:`T4_${v4()}`};B.push(U);}):B.push(S);}else B.push(S);}),B.map(S=>{let w={...S};return i(w,!0).forEach(Q=>{let A=Array.isArray(w[Q])?w[Q]:[w[Q]],U=F(A);w[Q]=U;}),w})},b=F(Array.isArray(m)?m:[m]),y=g(b),L=(E=>{let B=T=>{let S=Y=>{let X=[],H=[],k=[];return Y.forEach(W=>{let ne=i(W,!0);if(ne.length>0){let O=!1;ne.forEach(V=>{(Array.isArray(W[V])?W[V]:[W[V]]).filter(te=>!te.$id&&!te.id&&typeof W=="object").length&&(O=!0);}),O?X.push(W):H.push(W);}else W.$id?k.push({...W,$bzId:W.$tempId||W.$bzId}):k.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:X,operationWithoutMultiples:H,otherOps:k}},{operationWithMultiples:w,operationWithoutMultiples:Q,otherOps:A}=S(T),U=Y=>{let H=(()=>{let V={};for(let ae in Y){let G=N(t,Y);!ae.startsWith("$")&&G.dataFields?.find(te=>te.path===ae)&&(V[ae]=Y[ae]);}return V})(),k=Object.keys(Y),W=i(Y,!0),ne=[],O=(V,ae)=>{if(V===W.length){let te={...ae};k.forEach(le=>{le.startsWith("$")&&(te[le]=Y[le]);}),ne.push({...te,...H});return}let G={...ae,[W[V]]:Y[W[V]],...Le(ae),...H};O(V+1,G),O(V+1,ae);};return O(0,{...Le(Y)}),ne},P=[];return w.forEach(Y=>{let X=U(Y),H=[];X.forEach(k=>{let W=i(k,!0);if(k.$op==="create")H.push(k);else if(k.$id){let ne=l(k.$objectPath),O=[];if(W.forEach(V=>{let ae=`${ne.includes("undefined")?"root":ne}.${k.$id}${nr}${V}`,G=h[ae];k[V].filter(le=>le.$op==="unlink"||le.$op==="delete"||le.$op==="update").length>0?G?.$ids&&O.push({key:V,ids:G.$ids}):O.push({key:V,ids:[""]});}),O.length===W.length&&!H.find(V=>V.$id===k.$id))H.push(k);else {let V={...k,$bzId:k.$tempId||`T4_${v4()}`};W.forEach(G=>{let te=k[G].filter(le=>le.$id);te.length>0?V[G]=te:V[G]=void 0;}),i(V,!0).length>0&&H.push(V);}}else if(k.$objectPath){let ne=l(k.$objectPath),O=h[ne]?.$ids||[];O.forEach(V=>{let ae=[];W.forEach(G=>{let te=`${ne}.${V}${nr}${G}`,le=h[te];le&&ae.push({key:G,ids:le.$ids});}),W.length===0?O.filter(te=>!H.find(le=>le.$id===te)).forEach(te=>{H.push({...k,$id:te,$bzId:k.$tempId||`PQT2_${v4()}`});}):ae.length===W.length&&!H.find(G=>G.$id===V)&&(W.forEach(G=>{let te=`${l(k.$objectPath)}.${V}${nr}${G}`,le=h[te]?.$ids||[],di=k[G].find(qe=>!qe.$id),ur=[...le.map(qe=>({...di,$id:qe,$objectPath:{beforePath:k.$objectPath.beforePath,ids:qe,key:G}})),...k[G].filter(qe=>qe.$id)];ur.length>0&&(k[G]=ur);}),H.push({...k,$id:V,$bzId:k.$tempId||`PQ3_${v4()}`}));});}else H.push(k);}),H.forEach(k=>{P.push(k);});}),[...P,...Q,...A].filter(Y=>i(Y).length>0?!0:Y.$op!=="update").map(Y=>{let X={...Y};return i(X,!0).forEach(H=>{let k=Array.isArray(X[H])?X[H]:[X[H]],W=B(k);X[H]=W;}),X})};return B(E)})(Array.isArray(y)?y:[y]),D=E=>E.map(B=>{let T=i(B,!0),S={...B};return T.forEach(w=>{let Q=Array.isArray(B[w])?B[w]:[B[w]],A=[],U=[],P=[],Z={},Be=Rt(t,B,w);Q.filter(O=>O).forEach(O=>{O.$op==="replace"&&O.$id?(Z=O,Array.isArray(O.$id)?U=[...U,...O.$id]:U.push(O.$id)):O.$op==="create"&&Be==="ONE"&&O.id?(Z=O,Array.isArray(O.id)?P=[...U,...O.id]:P.push(O.id)):A.push(O);});let ge=l(Z.$objectPath),X=f(ge).map(O=>h[O]),H=[];X.filter(O=>O!=null).forEach(O=>{H=[...H,...O?.$ids||[]];});let k=H.filter(O=>!U.includes(O)),W=U.filter(O=>!H.includes(O)),ne=Le(Z);k.length>0&&A.push({...Z,$op:"unlink",$id:k,$bzId:Z.$tempId||`T4_${v4()}`,id:void 0,...ne}),W.length>0&&W.forEach(O=>{A.push({...Z,$op:"link",$id:O,$bzId:Z.$tempId||`T5_${v4()}`,...ne});}),P.length>0&&P.forEach(O=>{A.push({...Z,$op:"create",id:O,$bzId:Z.$tempId||`T6_${v4()}`,...ne});}),S[w]=D(A);}),S}),C=g(D(g(L)));(E=>produce(E,B=>traverse(B,T=>{let{key:S,value:w,parent:Q,meta:A}=T;S&&Q&&!S?.includes("$")&&S!=="$filter"&&!A.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(Q)&&(Array.isArray(w)?w:[w]).forEach(P=>{let Z=P.$filter?{...P.$objectPath,key:P.$filterBzId}:P.$objectPath,Be=l(Z),ge=h[Be],Y=(k,W)=>k.every(ne=>W.includes(ne)),X=P.$id?Array.isArray(P.$id)?Y(P.$id,ge&&ge.$ids?ge.$ids:[]):ge?.$ids?.includes(P.$id):ge,H=Rt(t,Q,P.$objectPath.key);if(P.$op==="link"&&X&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${l(P.$objectPath)}" because it is already occupied.`);if(P.$op)switch(P.$op){case"delete":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${P.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"update":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${P.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"unlink":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${P.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"link":if(X)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${P.$id}" because it is already linked to $id:"${Q.$id}"`);break;}});})))(C);let ue=(E=>produce(E,B=>traverse(B,T=>{let{value:S,meta:w}=T;isObject(S)&&(S[Symbol.for("path")]=w.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(C);return [...Array.isArray(ue)?ue:[ue]].sort((E,B)=>E.$op==="create"&&B.$op!=="create"?-1:E.$op!=="create"&&B.$op==="create"?1:0)},os=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var On=(e,t)=>produce(e,n=>gt(t,n)),gt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(s=>gt(e,s,r));return}let n=v(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([s])=>{s.startsWith("$")||as(e,t,s,n);});},as=(e,t,r,n)=>{let s=t[r];if(!s)return;let i=n.dataFields?.find(o=>o.path===r);if(i){i.contentType==="JSON"&&s!=null&&(t[r]=JSON.stringify(s));return}let a=n.linkFields?.find(o=>o.path===r);if(a){let o=a.oppositeLinkFieldsPlayedBy[0]?.thing;gt(e,s,o);return}if(n.thingType==="relation"){let o=n.roles[r];if(!o)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[c]=o.playedBy||[];if(!c)throw new Error(`Role ${o.path} in ${n} is not played by anything`);gt(e,s,c.thing);}};var Nn=async(e,t,r,n)=>{let s=Array.isArray(e)?e:[e],i=s.map(c=>ir(c,!0)),o=(await ze(i,t,r,n)).bql.res;return s.map((c,p)=>{let u=v(t,c.$thing);return jn({mut:c,node:o[p],schema:t,thing:u})})},xn=new Set(["$op","$bzId","$parentKey"]),cs=new Set(["$relation","$entity","$id",...xn]),ir=(e,t)=>{let r={};e.$fields?.forEach(s=>{typeof s=="string"?r[s]=s:r[s.$path]=s;});let n={};for(let s in e){if(xn.has(s)||cs.has(s)&&!t)continue;let i=e[s];s.startsWith("$")?n[s]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[s]={$path:s,...ir(i[0],!1)}):isObject(i)&&(r[s]={$path:s,...ir(i,!1)});}return n.$fields=Object.values(r),n},jn=e=>{let{mut:t,node:r,schema:n,thing:s}=e,i=Un(s),a=us(r);if(Array.isArray(t))return t.map(c=>{let p=a[c.$id];return p?Pn({mut:c,node:p,schema:n,thing:s,...i}):c});let o=a[t.$id];return Pn({mut:t,node:o,schema:n,thing:s,...i})},Pn=e=>{let{mut:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,{$fields:c,...p}=t;if(!r)return p;let u=_n({$fields:t.$fields,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}),d={...p,[Ne]:u};for(let l in t){if(l.startsWith("$"))continue;let f=t[l];if(i[l]||!f||typeof f!="object"){d[l]=f;continue}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);let g=v(n,$);d[l]=jn({mut:f,schema:n,node:r[l],thing:g});}return d},_n=e=>{let{$fields:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,c=t||ds(s),p={$id:r.$id};return c.forEach(u=>{let d=typeof u!="string",l=d?u.$path:u,f=r[l];if(i[l]){p[l]=f;return}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);if(!d){f&&(p[l]=Array.isArray(f)?f.map(kn):kn(f));return}let g=v(n,$),m=Un(g);p[l]=Array.isArray(f)?f.map(F=>qn({...m,$fields:u.$fields,value:F,schema:n,thing:g})):qn({...m,$fields:u.$fields,value:f,schema:n,thing:g});}),p},ds=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},kn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},qn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return _n({...e,node:t})},Un=e=>{let t=Object.fromEntries(e.dataFields?.map(s=>[s.path,s])||[]),r=Object.fromEntries(e.linkFields?.map(s=>[s.path,s])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},us=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var or=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Vn=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let n=l=>{let f=l.$op,h=`$${l.$bzId}`,$=N(r,l),{idFields:g,defaultDBConnector:m}=$,F=m?.path||l.$thing,b=l.$id,y=g?.[0],R=listify(l,(I,q)=>{if(I.startsWith("$")||I.startsWith("%")||I===y||q===void 0||q===null)return "";let E=$.dataFields?.find(S=>S.path===I);if(!E?.path)return "";let T=E.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(E.contentType))return `has ${T} '${q}'`;if(["NUMBER","BOOLEAN"].includes(E.contentType))return `has ${T} ${q}`;if(E.contentType==="DATE"){if(Number.isNaN(q.valueOf()))throw new Error("Invalid format, Nan Date");return q instanceof Date?`has ${T} ${q.toISOString().replace("Z","")}`:`has ${T} ${new Date(q).toISOString().replace("Z","")}`}if(E.contentType==="FLEX"){let S=`bza${Ae()}`,w=isArray(q)?q.map(Q=>or(Q)):or(q);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${T} $${S}; $${S} '${S}' isa ${T}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${E.contentType}`)}).filter(I=>I),L=`${h}-atts`,D=listify(l,I=>{if(I.startsWith("$")||I.startsWith("%")||I===y)return "";let q=$.dataFields?.find(T=>T.path===I);if(!q?.path)return "";let B=q.dbPath;return `{${L} isa ${B};}`}).filter(I=>I),C=isArray(b)?`like '${b.join("|")}'`:`'${b}'`,_=b?[`has ${y} ${C}`]:[],J=[..._,...R].filter(I=>I).join(","),ue=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[F,..._].filter(I=>I).join(",")};`;if(f==="update"){if(!D.length)throw new Error("update without attributes");return `${h} isa ${[F,..._].filter(I=>I).join(",")}, has ${L};
|
|
111
|
+
?queryPath${R} = "${m}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${R} as "queryPath";`,i));let L=c?.filter(_=>_.$fieldType==="data");L&&L.length>0&&a.push(...Kt(L,b,i));let D=c?.filter(_=>_.$fieldType==="link");D&&D.length>0&&a.push(...Jt(D,b,`${t}.${o.$var}`,i,s));let C=c?.filter(_=>_.$fieldType==="role");C&&C.length>0&&a.push(...vt(C,b,`${t}.${o.$var}`,i,s));}y&&a.push(y.sort),typeof $=="number"&&a.push(M(`offset ${$};`,i)),typeof g=="number"&&a.push(M(`limit ${g};`,i)),a.push(M("};",n));}return a},Jt=(e,t,r,n,s)=>{let i=n+1,a=[];for(let o of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:d,$filterByUnique:l,$playedBy:f,$thing:h,$sort:$,$offset:g,$limit:m}=o,F=o[ie],b=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${b}.${o.$var}": {`,n)),a.push(M("match",i));let y=`${t}${Ht}${o.$var}`;if(a.push(M(`$${y} isa ${o.$thing};`,i)),o.$filter||o.$id){let L=ot(s,o),D=o.$id?{[L]:o.$id}:{},C={...o.$filter,...D};a.push(pt({$filter:C,$var:y,$thing:o.$thing,schema:s,depth:i}));}let R=Yt({schema:s,$thing:h,$var:y,$sort:$,depth:i});if(R&&a.push(R.match),o.$target==="role"?a.push(M(`$${t}_intermediary (${o.$plays}: $${t}, ${f.plays}: $${y}) isa ${o.$intermediary};`,i)):a.push(M(`$${y} (${o.$plays}: $${t});`,i)),c){let L=`M_${v4()}`;a.push(M(`?queryPath${L} = "${F}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${L} as "queryPath";`,i));let D=c?.filter(J=>J.$fieldType==="data");D&&D.length>0&&a.push(...Kt(D,y,i));let C=c?.filter(J=>J.$fieldType==="link");C&&C.length>0&&a.push(...Jt(C,y,`${t}.${o.$var}`,i,s));let _=c?.filter(J=>J.$fieldType==="role");_&&_.length>0&&a.push(...vt(_,y,`${t}.${o.$var}`,i,s));}R&&a.push(R.sort),typeof g=="number"&&a.push(M(`offset ${g};`,i)),typeof m=="number"&&a.push(M(`limit ${m};`,i)),a.push(M("};",n));}return a},jo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Yt=e=>{let{$var:t,$thing:r,schema:n,$sort:s,depth:i}=e,a=v(n,r),o=[],c=[];if(s?.forEach(p=>{let u=jo(p),d=a.dataFields?.find(h=>h.path===u.field);if(!d)throw new Error(`"${r}" does not have data field "${u.field}"`);let l=`${u.field}_${v4()}`;o.push(M("{",i)),o.push(M(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),o.push(M("not {",i+1)),o.push(M(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),o.push(M(`$${l}_2 < $${l}_1;`,i+2)),o.push(M("};",i+1)),o.push(M(`?${l}_ = $${l}_1;`,i+1)),o.push(M("} or {",i)),o.push(M(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),o.push(M(`?${l}_ = "~";`,i+1)),o.push(M("};",i)),o.push(M(`?${l} = ?${l}_;`,i));let f=u.desc?"desc":"asc";c.push(`?${l} ${f}`);}),o.length!==0)return {match:o.join(""),sort:M(`sort ${c.join(", ")};`,i)}};var Rn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:s,rawTqlRes:i}=e;if(t){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((a,o)=>{let c=r[o],p=t[o];return Uo(a,c,p,n,s)})},Uo=(e,t,r,n,s)=>e.length===0?null:r.$filterByUnique?Qn(e[0],t,n,s):e.map(i=>Qn(i,t,n,s)),Qn=(e,t,r,n)=>{let{dataFields:s,currentSchema:i,linkFields:a,roleFields:o,schemaValue:c}=Gt(e,r),p=Xt(s,i,n),u=er(a,r,n),d=Zt(o,r,n),l=t?.$fields?.every(h=>!i?.idFields?.includes(typeof h=="string"?h:h.$path));return {...u,...d,...c,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...l?Object.fromEntries(Object.entries(p).filter(([h])=>!i?.idFields?.includes(h))):p}},Gt=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),s=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");s?.length>0&&s.forEach(f=>{let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let o=i.type,c={$thing:o.label,$thingType:o.root,[ie]:e.queryPath.value},p={[`$${c.$thingType}`]:c.$thing},u=N(t,p),d=r.filter(f=>{let h=he(f.split(".").pop());return !f.endsWith(".$dataFields")&&u.linkFields?.some($=>$.path===h)}).map(f=>{let h=he(f.split(".").pop()),$=he(u.linkFields?.find(g=>g.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&u.thingType==="relation"&&u.roles?.[h]}).map(f=>{let h=he(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:u.roles[h].cardinality}});return {dataFields:i,schemaValue:c,currentSchema:u,linkFields:d,roleFields:l}},Xt=(e,t,r)=>{let{$metaData:n}=e,{as:s}=Wo(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,o])=>{let c=t.dataFields?.find(l=>l.path===a||l.dbPath===a),p=a==="id",u=Array.isArray(s)?s.find(l=>l[a])?.[a]:a,d;if(c?.cardinality==="ONE"){if(d=o[0]?o[0].value:r.query?.returnNulls?null:void 0,c.contentType==="DATE"||c.contentType==="FLEX"&&o[0].type.value_type==="datetime"?d=d&&`${d}Z`:c.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[u,d],["$id",d]].filter(([l,f])=>f!==void 0)}else if(c?.cardinality==="MANY"){if(!isArray(o))throw new Error("Typedb fetch has changed its format");if(o.length===0)return r.query?.returnNulls?[[u,null]]:[];c.contentType==="DATE"?d=o.map(l=>`${l.value}Z`):c.contentType==="FLEX"?d=o.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):c.contentType==="JSON"?d=o.map(l=>l.value&&JSON.parse(l.value)):d=o.map(l=>l.value);}return [[u,d]].filter(([l,f])=>f!==void 0)}).flat();return Object.fromEntries([...i])},Zt=(e,t,r)=>{let n={};return e.forEach(s=>{let{$roleFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Dn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:F}=Gt(f,t),b=Xt(h,$,r);if(p==="T")return b.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...b};return u==="true"&&$?.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...F}}});l.length>0?n[c]=o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[c]=null);}),n},er=(e,t,r)=>{let n={};return e.forEach(s=>{let{$linkFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Dn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:F}=Gt(f,t),b=Xt(h,$,r);if(p==="T")return b.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...b};return u==="true"&&$.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...F}}});n[c]=l.length>0?o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},Dn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,s=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),o=e.match(n),c=e.match(s);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:o?o[1]:null,filterByUnique:c?c[1]:null}},Wo=e=>{try{let r=(s=>{let i=s.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,o,c)=>/^{.*}$/.test(c)?`:${c}`:`:${o}"${c}"`),i=i.replace(/\[([^\]]+)\]/g,(a,o)=>`[${o.split(",").map(c=>c.trim().startsWith("{")&&c.trim().endsWith("}")?c.trim():`"${c.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var $t=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,s=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!s)throw new Error("Client not found");n=await s.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:s,session:n});}return {client:s,session:n}};var Cn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,s=new TypeDBOptions;s.infer=!0;let{session:i}=await $t(r,n),a=await i.transaction(TransactionType.READ,s),[o,c]=await tryit(parallel)(t.length,t,async p=>await a.query.fetch(p).collect());if(o){await a.rollback();let p=o;throw new Error(`Error running TQL query: ${p.errors}`)}return await a.close(),c};var Jo=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Yo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Go=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,tr=j("error","error",x((e,t)=>({...e,error:t.error}))),Xo=me("build",{build:z(async e=>Ln({queries:e.bql.queries,schema:e.schema}),j("done","run",x(Yo)),tr),run:z(async e=>Cn({dbHandles:e.handles,tqlRequest:he(e.tql.queries),config:e.config}),j("done","parse",x(Go)),tr),parse:z(async e=>Rn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:he(e.tql.res)}),j("done","success",x(Jo)),tr),success:se(),error:se()},e=>e),Zo=async e=>new Promise((t,r)=>{fe(Xo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),In=async(e,t,r,n,s)=>Zo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:s,error:null});var es=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,rr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,mt=j("error","error",x((e,t)=>({...e,error:t.error}))),ts=me("enrich",{enrich:z(async e=>(e.config.query?.debugger&&console.log(`originalBQLQuery[${De}]`,JSON.stringify(e.bql.raw,null,2)),Vr(e.bql.raw,e.schema)),j("done","adapter",x(es)),mt),adapter:z(async e=>{let t={};e.bql.queries?.forEach((o,c)=>{let p=e.bql.raw[c],u=v(e.schema,o.$thing),{id:d}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let l=t[d];l.rawBql.push(p),l.bqlQueries.push(o),l.indices.push(c);});let r=Object.values(t),n=r.map(o=>{if(o.db==="typeDB")return In(o.rawBql,o.bqlQueries,e.schema,e.config,e.handles);if(o.db==="surrealDB")return wn(o.bqlQueries,e.schema,e.config,o.client);throw new Error(`Unsupported DB "${JSON.stringify(o,null,2)}"`)}),s=await Promise.all(n),i=r.flatMap((o,c)=>{let p=s[c];return o.indices.map((u,d)=>({index:u,result:p[d]}))});return i.sort((o,c)=>o.index<c.index?-1:o.index>c.index?1:0),i.map(({result:o})=>o)},j("done","postHooks",x(rr)),mt),postHooks:z(async e=>pn(e.schema,he(e.bql.queries),he(e.bql.res)),j("done","clean",x(rr)),mt),clean:z(async e=>hn(e.config,he(e.bql.res)),j("done","success",x(rr)),mt),success:se(),error:se()},e=>e),rs=async e=>new Promise((t,r)=>{fe(ts,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>rs({bql:{raw:e},schema:t,config:r,handles:n,error:null});var nr="___",is=Symbol.for("grandChildOfCreate"),An=async(e,t,r,n)=>{let s=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(E,B)=>Object.keys(E).filter(T=>!T.startsWith("$")&&!s.includes(T)&&E[T]!==void 0?B?!N(t,E).dataFields?.find(w=>w.path===T):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let a=[];if(traverse(e,({parent:E,key:B,value:T})=>{E&&B&&!B.includes("$")&&!s.includes(B)&&isObject(E)?(Array.isArray(E[B])?E[B]:[E[B]]).forEach(w=>{if(isObject(w)){if(E.$op!=="create")a.includes(w.$op)||a.push(w.$op);else if(w.$op==="delete"||w.$op==="unlink")throw new Error(`Cannot ${w.$op} under a create`)}}):!E&&isObject(T)&&(a.includes(T.$op)||a.push(T.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let c=(E=>{let B=(T,S)=>{let w=[],Q={},A=["$op","$bzId","$parentKey"],U=["$relation","$entity","$id",...A];for(let P in T)if(!A.includes(P)&&!(U.includes(P)&&!S))if(!P.includes("$")&&(isObject(T[P])||Array.isArray(T[P]))){let Z=os(T[P]);if(Array.isArray(Z)&&Z.length>0)Z.forEach(Be=>{let ge={$path:P,...B(Be),...Be.$filter&&{$as:Be.$bzId}};w.find(Y=>Y.$path===ge.$path&&!Y.$filter)||(w=[...w,ge]);});else {let Be={$path:P,...B(Z),...!Z.$filter&&{$as:Z.$bzId}};w=[...w,Be];}}else Q[P]=T[P];return {...Q,$fields:w}};return E.map(T=>B(T,!0))})(Array.isArray(e)?e:[e]),u=(await ze(c,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,d=(E,B)=>{let T=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:S}=E,w=S?.beforePath||"root",Q=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${w}.${Q}___${S.key}`,ids:T,key:B}}else return {beforePath:"root",ids:T,key:B}},l=(E,B)=>{let T=E?.beforePath||"root";if(typeof T!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${T}.${S}___${E?.key}`},f=E=>{if(E.includes("[")&&E.includes("]")){let[B,T,S]=E.split(/[[\]]/);return T.split(",").map(Q=>`${B}${Q}${S}`)}else return [E]},h={};(E=>produce(E,B=>traverse(B,({key:T,parent:S})=>{if(S&&T&&S.$id&&!T.includes("$")){let w=d(S,T),Q=l(w);if(Array.isArray(S[T])){let A=[];S[T].forEach(U=>{isObject(U)?(U.$objectPath=w,A.push(U.$id.toString())):U&&A.push(U.toString());}),h[Q]={$objectPath:w,$ids:A};}else {let A=S[T];isObject(A)?(h[Q]={$objectPath:w,$ids:[A.$id.toString()]},A.$objectPath=w):A?h[Q]={$objectPath:w,$ids:[A.toString()]}:A===null&&(h[Q]=null);}}})))(u||{});let g=E=>produce(E,B=>traverse(B,({key:T,value:S,parent:w})=>{w&&T&&!T.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(w)&&(Array.isArray(w[T])?w[T].forEach(Q=>{typeof Q!="string"&&(Q.$objectPath=d(w,T),Q.$parentIsCreate=w.$op==="create",Q[is]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[T])&&(w[T].$parentIsCreate=w.$op==="create",w[T][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[T].$objectPath=d(w,T)));})),m=g(e),F=E=>{let B=[];return E.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let w=l({...S.$objectPath,key:S.$bzId}),Q=h[w];Q&&(Array.isArray(Q.$ids)?Q.$ids:[Q.$ids]).forEach(U=>{let P={...S,$id:U,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};B.push(P);});}else {let w=l(S.$objectPath),Q=h[w];Q?Q?.$ids?.forEach(A=>{let U={...S,$id:A,$bzId:`T4_${v4()}`};B.push(U);}):B.push(S);}else B.push(S);}),B.map(S=>{let w={...S};return i(w,!0).forEach(Q=>{let A=Array.isArray(w[Q])?w[Q]:[w[Q]],U=F(A);w[Q]=U;}),w})},b=F(Array.isArray(m)?m:[m]),y=g(b),L=(E=>{let B=T=>{let S=Y=>{let X=[],H=[],k=[];return Y.forEach(W=>{let ne=i(W,!0);if(ne.length>0){let O=!1;ne.forEach(V=>{(Array.isArray(W[V])?W[V]:[W[V]]).filter(te=>!te.$id&&!te.id&&typeof W=="object").length&&(O=!0);}),O?X.push(W):H.push(W);}else W.$id?k.push({...W,$bzId:W.$tempId||W.$bzId}):k.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:X,operationWithoutMultiples:H,otherOps:k}},{operationWithMultiples:w,operationWithoutMultiples:Q,otherOps:A}=S(T),U=Y=>{let H=(()=>{let V={};for(let ae in Y){let G=N(t,Y);!ae.startsWith("$")&&G.dataFields?.find(te=>te.path===ae)&&(V[ae]=Y[ae]);}return V})(),k=Object.keys(Y),W=i(Y,!0),ne=[],O=(V,ae)=>{if(V===W.length){let te={...ae};k.forEach(le=>{le.startsWith("$")&&(te[le]=Y[le]);}),ne.push({...te,...H});return}let G={...ae,[W[V]]:Y[W[V]],...Le(ae),...H};O(V+1,G),O(V+1,ae);};return O(0,{...Le(Y)}),ne},P=[];return w.forEach(Y=>{let X=U(Y),H=[];X.forEach(k=>{let W=i(k,!0);if(k.$op==="create")H.push(k);else if(k.$id){let ne=l(k.$objectPath),O=[];if(W.forEach(V=>{let ae=`${ne.includes("undefined")?"root":ne}.${k.$id}${nr}${V}`,G=h[ae];k[V].filter(le=>le.$op==="unlink"||le.$op==="delete"||le.$op==="update").length>0?G?.$ids&&O.push({key:V,ids:G.$ids}):O.push({key:V,ids:[""]});}),O.length===W.length&&!H.find(V=>V.$id===k.$id))H.push(k);else {let V={...k,$bzId:k.$tempId||`T4_${v4()}`};W.forEach(G=>{let te=k[G].filter(le=>le.$id);te.length>0?V[G]=te:V[G]=void 0;}),i(V,!0).length>0&&H.push(V);}}else if(k.$objectPath){let ne=l(k.$objectPath),O=h[ne]?.$ids||[];O.forEach(V=>{let ae=[];W.forEach(G=>{let te=`${ne}.${V}${nr}${G}`,le=h[te];le&&ae.push({key:G,ids:le.$ids});}),W.length===0?O.filter(te=>!H.find(le=>le.$id===te)).forEach(te=>{H.push({...k,$id:te,$bzId:k.$tempId||`PQT2_${v4()}`});}):ae.length===W.length&&!H.find(G=>G.$id===V)&&(W.forEach(G=>{let te=`${l(k.$objectPath)}.${V}${nr}${G}`,le=h[te]?.$ids||[],di=k[G].find(qe=>!qe.$id),ur=[...le.map(qe=>({...di,$id:qe,$objectPath:{beforePath:k.$objectPath.beforePath,ids:qe,key:G}})),...k[G].filter(qe=>qe.$id)];ur.length>0&&(k[G]=ur);}),H.push({...k,$id:V,$bzId:k.$tempId||`PQ3_${v4()}`}));});}else H.push(k);}),H.forEach(k=>{P.push(k);});}),[...P,...Q,...A].filter(Y=>i(Y).length>0?!0:Y.$op!=="update").map(Y=>{let X={...Y};return i(X,!0).forEach(H=>{let k=Array.isArray(X[H])?X[H]:[X[H]],W=B(k);X[H]=W;}),X})};return B(E)})(Array.isArray(y)?y:[y]),D=E=>E.map(B=>{let T=i(B,!0),S={...B};return T.forEach(w=>{let Q=Array.isArray(B[w])?B[w]:[B[w]],A=[],U=[],P=[],Z={},Be=Rt(t,B,w);Q.filter(O=>O).forEach(O=>{O.$op==="replace"&&O.$id?(Z=O,Array.isArray(O.$id)?U=[...U,...O.$id]:U.push(O.$id)):O.$op==="create"&&Be==="ONE"&&O.id?(Z=O,Array.isArray(O.id)?P=[...U,...O.id]:P.push(O.id)):A.push(O);});let ge=l(Z.$objectPath),X=f(ge).map(O=>h[O]),H=[];X.filter(O=>O!=null).forEach(O=>{H=[...H,...O?.$ids||[]];});let k=H.filter(O=>!U.includes(O)),W=U.filter(O=>!H.includes(O)),ne=Le(Z);k.length>0&&A.push({...Z,$op:"unlink",$id:k,$bzId:Z.$tempId||`T4_${v4()}`,id:void 0,...ne}),W.length>0&&W.forEach(O=>{A.push({...Z,$op:"link",$id:O,$bzId:Z.$tempId||`T5_${v4()}`,...ne});}),P.length>0&&P.forEach(O=>{A.push({...Z,$op:"create",id:O,$bzId:Z.$tempId||`T6_${v4()}`,...ne});}),S[w]=D(A);}),S}),C=g(D(g(L)));(E=>produce(E,B=>traverse(B,T=>{let{key:S,value:w,parent:Q,meta:A}=T;S&&Q&&!S?.includes("$")&&S!=="$filter"&&!A.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(Q)&&(Array.isArray(w)?w:[w]).forEach(P=>{let Z=P.$filter?{...P.$objectPath,key:P.$filterBzId}:P.$objectPath,Be=l(Z),ge=h[Be],Y=(k,W)=>k.every(ne=>W.includes(ne)),X=P.$id?Array.isArray(P.$id)?Y(P.$id,ge&&ge.$ids?ge.$ids:[]):ge?.$ids?.includes(P.$id):ge,H=Rt(t,Q,P.$objectPath.key);if(P.$op==="link"&&X&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${l(P.$objectPath)}" because it is already occupied.`);if(P.$op)switch(P.$op){case"delete":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${P.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"update":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${P.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"unlink":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${P.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"link":if(X)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${P.$id}" because it is already linked to $id:"${Q.$id}"`);break;}});})))(C);let ue=(E=>produce(E,B=>traverse(B,T=>{let{value:S,meta:w}=T;isObject(S)&&(S[Symbol.for("path")]=w.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(C);return [...Array.isArray(ue)?ue:[ue]].sort((E,B)=>E.$op==="create"&&B.$op!=="create"?-1:E.$op!=="create"&&B.$op==="create"?1:0)},os=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var On=(e,t)=>produce(e,n=>gt(t,n)),gt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(s=>gt(e,s,r));return}let n=v(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([s])=>{s.startsWith("$")||as(e,t,s,n);});},as=(e,t,r,n)=>{let s=t[r];if(!s)return;let i=n.dataFields?.find(o=>o.path===r);if(i){i.contentType==="JSON"&&s!=null&&(t[r]=JSON.stringify(s));return}let a=n.linkFields?.find(o=>o.path===r);if(a){let o=a.oppositeLinkFieldsPlayedBy[0]?.thing;gt(e,s,o);return}if(n.thingType==="relation"){let o=n.roles[r];if(!o)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[c]=o.playedBy||[];if(!c)throw new Error(`Role ${o.path} in ${n} is not played by anything`);gt(e,s,c.thing);}};var Nn=async(e,t,r,n)=>{let s=Array.isArray(e)?e:[e],i=s.map(c=>ir(c,!0)),o=(await ze(i,t,r,n)).bql.res;return s.map((c,p)=>{let u=v(t,c.$thing);return jn({mut:c,node:o[p],schema:t,thing:u})})},xn=new Set(["$op","$bzId","$parentKey"]),cs=new Set(["$relation","$entity","$id",...xn]),ir=(e,t)=>{let r={};e.$fields?.forEach(s=>{typeof s=="string"?r[s]=s:r[s.$path]=s;});let n={};for(let s in e){if(xn.has(s)||cs.has(s)&&!t)continue;let i=e[s];s.startsWith("$")?n[s]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[s]={$path:s,...ir(i[0],!1)}):isObject(i)&&(r[s]={$path:s,...ir(i,!1)});}return n.$fields=Object.values(r),n},jn=e=>{let{mut:t,node:r,schema:n,thing:s}=e,i=Un(s),a=us(r);if(Array.isArray(t))return t.map(c=>{let p=a[c.$id];return p?Pn({mut:c,node:p,schema:n,thing:s,...i}):c});let o=a[t.$id];return Pn({mut:t,node:o,schema:n,thing:s,...i})},Pn=e=>{let{mut:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,{$fields:c,...p}=t;if(!r)return p;let u=_n({$fields:t.$fields,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}),d={...p,[Ne]:u};for(let l in t){if(l.startsWith("$"))continue;let f=t[l];if(i[l]||!f||typeof f!="object"){d[l]=f;continue}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);let g=v(n,$);d[l]=jn({mut:f,schema:n,node:r[l],thing:g});}return d},_n=e=>{let{$fields:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,c=t||ds(s),p={$id:r.$id};return c.forEach(u=>{let d=typeof u!="string",l=d?u.$path:u,f=r[l];if(i[l]){p[l]=f;return}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);if(!d){f&&(p[l]=Array.isArray(f)?f.map(kn):kn(f));return}let g=v(n,$),m=Un(g);p[l]=Array.isArray(f)?f.map(F=>qn({...m,$fields:u.$fields,value:F,schema:n,thing:g})):qn({...m,$fields:u.$fields,value:f,schema:n,thing:g});}),p},ds=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},kn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},qn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return _n({...e,node:t})},Un=e=>{let t=Object.fromEntries(e.dataFields?.map(s=>[s.path,s])||[]),r=Object.fromEntries(e.linkFields?.map(s=>[s.path,s])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},us=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var or=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Vn=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let n=l=>{let f=l.$op,h=`$${l.$bzId}`,$=N(r,l),{idFields:g,defaultDBConnector:m}=$,F=m?.path||l.$thing,b=l.$id,y=g?.[0],R=listify(l,(I,q)=>{if(I.startsWith("$")||I.startsWith("%")||I===y||q===void 0||q===null)return "";let E=$.dataFields?.find(S=>S.path===I);if(!E?.path)return "";let T=E.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(E.contentType))return `has ${T} '${q}'`;if(["NUMBER","BOOLEAN"].includes(E.contentType))return `has ${T} ${q}`;if(E.contentType==="DATE"){if(Number.isNaN(q.valueOf()))throw new Error("Invalid format, Nan Date");return q instanceof Date?`has ${T} ${q.toISOString().replace("Z","")}`:`has ${T} ${new Date(q).toISOString().replace("Z","")}`}if(E.contentType==="FLEX"){let S=`bza${Ae()}`,w=isArray(q)?q.map(Q=>or(Q)):or(q);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${T} $${S}; $${S} '${S}' isa ${T}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${E.contentType}`)}).filter(I=>I),L=`${h}-atts`,D=listify(l,I=>{if(I.startsWith("$")||I.startsWith("%")||I===y)return "";let q=$.dataFields?.find(T=>T.path===I);if(!q?.path)return "";let B=q.dbPath;return `{${L} isa ${B};}`}).filter(I=>I),C=isArray(b)?`like '${b.join("|")}'`:`'${b}'`,_=b?[`has ${y} ${C}`]:[],J=[..._,...R].filter(I=>I).join(","),ue=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[F,..._].filter(I=>I).join(",")};`;if(f==="update"){if(!D.length)throw new Error("update without attributes");return `${h} isa ${[F,..._].filter(I=>I).join(",")}, has ${L};
|
|
112
112
|
${D.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[F,..._].filter(I=>I).join(",")};`:"";if(st(l))return {op:f,deletionMatch:ue(),insertionMatch:K(),insertion:f==="create"?`${h} isa ${[F,J].filter(I=>I).join(",")};`:f==="update"&&R.length?`${h} ${R.join(",")};`:"",deletion:f==="delete"?`${h} isa ${F};`:f==="update"&&D.length?`${h} has ${L};`:""};throw new Error("in attributes")},s=l=>{let f=l.$op,h=N(r,l),$=`$${l.$bzId}`,g=l.$id,m=h.defaultDBConnector?.path||l.$thing,F="roles"in h?listify(h.roles,q=>q):[],b="roles"in h?mapEntries(h.roles,(q,E)=>[q,E.dbConnector?.path||q]):{},y=listify(l,(q,E)=>{if(!F.includes(q))return null;if(!("roles"in h))throw new Error("This should have roles! ");let B=b[q];return Array.isArray(E)?E.map(T=>({path:B,id:T})):{path:B,id:E}}).filter(q=>q).flat(),R=y.map(q=>{if(!q?.path)throw new Error("Object without path");return `${q.path}: $${q.id}`}),L=y.length>0?`( ${R.join(" , ")} )`:"",D=l[Ie];if(!D)throw new Error("[internal error] Symbol edgeType not defined");let C=L?`${$} ${L} ${D==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",_=`${$} ${D==="linkField"||f==="delete"?`isa ${m}`:""}`,J=()=>C?f==="link"?`${C};`:f==="create"?`${C}, has id '${g}';`:"":"",ue=()=>C&&f==="match"?`${C};`:"",K=()=>C?f==="delete"?`${C};`:f==="match"?`${C};`:"":"",I=()=>C?f==="delete"?`${_};`:f==="unlink"?`${$} ${L};`:"":"";return {deletionMatch:K(),insertionMatch:ue(),deletion:I(),insertion:J(),op:""}},i=(l,f)=>{let h=f==="edges"?s:n;if(Array.isArray(l))return l.map(y=>{let{preDeletionBatch:R,insertionMatch:L,deletionMatch:D,insertion:C,deletion:_}=h(y);return shake({preDeletionBatch:R,insertionMatch:L,deletionMatch:D,insertion:C,deletion:_},J=>!J)}).filter(y=>y);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:F,deletion:b}=h(l);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:F,deletion:b},y=>!y)},a=i(e),o=Array.isArray(a)?a:[a],c=i(t,"edges"),p=Array.isArray(c)?c:[c],u=[...o,...p];return shake({insertionMatches:u.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:u.map(l=>l.deletionMatch).join(" ").trim(),insertions:u.map(l=>l.insertion).join(" ").trim(),deletions:u.map(l=>l.deletion).join(" ").trim()},l=>!l)};var zn=async(e,t,r,n,s)=>{let i=[...t,...r],a=i.map(o=>{let c=e.insertions?.find(d=>d.get(`${o.$bzId}`))?.get(`${o.$bzId}`),p=o.$thing||o.$relation||o.$entity,u=p?v(n,p):void 0;if(o.$op==="create"||o.$op==="update"||o.$op==="link"){if(o.$op!=="update"&&!c&&o.$id)return {$id:o.$id,$error:"Does not exist or it's not linked to the parent"};let d=c?.asThing().iid,l=Object.entries(o).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,g])=>{if(u?.dataFields?.find(F=>F.path===$)?.contentType==="JSON")return h[$]=JSON.parse(g),h;if(o.$thingType==="relation"){let F=i.filter(b=>b.$id&&b.$bzId===g);return F.length===1?(h[$]=F[0].$id,h):(h[$]=g,h)}return h[$]=g,h},{});if(s.mutation?.noMetadata)return l;let f=o.$tempId&&!o.$tempId.startsWith("_:")?{$tempId:`_:${o.$tempId}`}:{};return {$dbId:d,...o,...l,[o.path]:o.$id,...f}}if(o.$op==="delete"||o.$op==="unlink")return o;if(o.$op!=="match")throw new Error(`Unsupported op ${o.$op}`)}).filter(o=>o);return clone(a)};var Hn=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:n}=await $t(t,r),s=await n.transaction(TransactionType.WRITE),i=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{i&&await s.query.delete(i);let o=a&&s.query.insert(a),c=o?await o.collect():void 0;return await s.commit(),{insertions:c}}catch(o){throw new Error(`Transaction failed: ${o.message}`)}finally{await s.close();}};var ms=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ys=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),gs=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),ar=j("error","error",x((e,t)=>({...e,error:t.error}))),Es=me("buildMutation",{buildMutation:z(async e=>Vn(e.bql.things,e.bql.edges,e.schema),j("done","runMutation",x(ys)),ar),runMutation:z(async e=>Hn(e.tql.mutation,e.handles,e.config),j("done","parseMutation",x(gs)),ar),parseMutation:z(async e=>zn(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),j("done","success",x(ms)),ar),success:se(),error:se()},e=>e),Bs=async e=>new Promise((t,r)=>{fe(Es,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Kn=async(e,t,r,n,s,i,a)=>Bs({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:s,config:i,handles:a,error:null});var vn=async(e,t)=>{let r=a=>{let{$filter:o,$thing:c,$bzId:p,$op:u,$id:d,$tempId:l}=a,f=v(t,c),{usedDataFields:h}=de(f,a),{idFields:$}=f,g=d||a[$[0]],m=(a[Fe]?.$things||[c]).map(ee),F=ce(a,E=>E.startsWith("$")),b=ce(a,E=>!E.startsWith("$")),y=JSON.stringify(b),R=Object.entries(F).map(([E,B])=>E=="$tempId"?`'$tempId': '_:${B}'`:`'${E}': '${B}'`).join(","),L=a[rt],D=h.filter(E=>!$.includes(E)).map(E=>{let B=f.dataFields?.find(S=>S.path===E||S.dbPath===E);if(!B)throw new Error(`Data field schema not found for ${E}`);let T=a[E];return T===null?`${E} = NONE`:`${E} = ${Ze(T,B.contentType)}`}).filter(Boolean),C=`$\u27E8${l||p}\u27E9`,_=L?.bzId?`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:g?isArray(g)?m.flatMap(E=>g.map(B=>`${E}:\u27E8${B}\u27E9`)).join(", "):m.map(E=>`${E}:\u27E8${g}\u27E9`).join(", "):!0,J=(()=>{if(L?.bzId){let E=`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return g?isArray(g)?`${E}[? $this.id() IN [${g.map(B=>`'${B}'`).join(", ")}] ]`:`${E}[? $this.id() IN ['${g}'] ]`:E}else return g?isArray(g)?m.flatMap(E=>g.map(B=>`${E}:\u27E8${B}\u27E9`)).join(", "):m.map(E=>`${E}:\u27E8${g}\u27E9`).join(", "):m.join(", ")})(),ue=o?`WHERE ${pe(ye(o,c,t))}`:"",K=D.length>0?`SET ${D.join(", ")}`:"",I=`VALUE (CREATE ONLY Delta SET input = ${y}, meta = {${R}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,q="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return l?"":`LET ${C} = (SELECT VALUE id FROM ${J} ${ue});`;if(a.$op==="create"){if(isArray(g))throw new Error("Cannot create multiple things at once");let E=ee(c);return `LET ${C} = (CREATE ONLY ${E}:\u27E8${g}\u27E9 ${K} RETURN ${I});`}if(a.$op==="update")return `LET ${C} = IF (${_}) THEN (UPDATE ${J} ${K} ${ue} RETURN ${I}) END;`;if(a.$op==="delete")return `LET ${C} = IF (${_}) THEN (DELETE ${J} ${ue} RETURN ${q}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:o,$bzId:c,$op:p,$tempId:u}=a,d=v(t,o),{usedRoleFields:l}=de(d,a),f=`$\u27E8${u||c}\u27E9`,h="roles"in d?l.flatMap(m=>{let F=d.roles[m];if(!F)throw new Error(`Role field schema not found for ${m}`);let{cardinality:b}=F,y=isArray(a[m])?a[m].map(R=>`$\u27E8${R}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(b==="ONE"){if(y.length>1)throw new Error(`${p==="link"?"Linking":"Replacing"} multiple values to a ONE field ${m}`);switch(p){case"link":case"replace":return `${m} = ((type::is::array(${y[0]}) && array::len(${y[0]})==1) && ${y[0]}[0]) || ${y[0]}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${p} for ONE cardinality`)}}else if(b==="MANY"){let R=`array::flatten([${y}])`;switch(p){case"link":return `${m} += ${R}`;case"unlink":return `${m} -= ${R}`;case"replace":return `${m} = ${R}`;default:throw new Error(`Unsupported operation ${p} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${b}`)}):[],$=h.length>0?`${h.join(", ")}`:"",g=$?`SET ${$}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`},s=a=>{let{$thing:o,$op:c}=a,p=v(t,o),u=ee(o),{usedRoleFields:d}=de(p,a);if(!["create","delete"].includes(c))throw new Error("Arcs can only be created or deleted");let[l,f]=d,h=isArray(a[l])?a[l]:[a[l]],$=isArray(a[f])?a[f]:[a[f]];if(c==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let g=ce(a,C=>!C.startsWith("$")),F=`(CREATE ONLY Delta SET input = ${JSON.stringify(g)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,y=p.roles[l].cardinality==="MANY",L=p.roles[f].cardinality==="MANY";return h.flatMap(C=>$.flatMap(_=>`FOR $node1 IN fn::as_array($\u27E8${C}\u27E9) { FOR $node2 IN fn::as_array($\u27E8${_}\u27E9) { CREATE ONLY ${u} SET ${l} = ${y?"fn::as_array($node1)":"$node1"}, ${f} = ${L?"fn::as_array($node2)":"$node2"} RETURN ${F}; } }`))}if(c==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${l}) CONTAINSANY $\u27E8${h}\u27E9 AND fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 RETURN BEFORE`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(s)]};var Jn=async(e,t,r)=>{let n=`
|
|
113
113
|
BEGIN TRANSACTION;
|
|
114
114
|
${t.join(";")};
|
|
@@ -119,10 +119,10 @@ limit ${p};`),d.join(`
|
|
|
119
119
|
LET $LOGS = SELECT * FROM LOG;
|
|
120
120
|
RETURN $LOGS;
|
|
121
121
|
COMMIT TRANSACTION;
|
|
122
|
-
`;r.mutation?.debugger&&console.log(`batchedMutation[${De}]`,n);try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Zn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Gn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Gn(s,r)})},Gn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(s,i=>!i.startsWith("$")):s};var bs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ts=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},ws=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},lr=j("error","error",x((e,t)=>({...e,error:t.error}))),Ms=me("buildMutation",{buildMutation:z(async e=>vn(e.bql.flat,e.schema),j("done","runMutation",x(Ts)),lr),runMutation:z(async e=>Jn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config),j("done","parseMutation",x(ws)),lr),parseMutation:z(async e=>Zn({res:e.surql.res,config:e.config,schema:e.schema}),j("done","success",x(bs)),lr),success:se(),error:se()},e=>e),Ss=async e=>new Promise((t,r)=>{fe(Ms,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ti=async(e,t,r,n,s,i)=>Ss({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ni=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=de(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...ce(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[rt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=ce(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(b=>n(b,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let F=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([b,y])=>{let R=F.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:b});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(b=>n(b,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(b=>b.path===g),F=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([b,y])=>{F.filter(L=>y.includes(L.$op)).forEach(L=>{let D=ce(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:b});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{F.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ii=se,He=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ls=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Qs=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Rs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ds=async e=>Object.keys(e.bql.enriched).length?kt(e.bql.enriched,e.schema,e.config):kt(e.bql.raw,e.schema,e.config),Cs=async e=>An(e.bql.enriched,e.schema,e.config,e.handles),Is=async e=>Nn(e.bql.enriched,e.schema,e.config,e.handles),As=async e=>Jr(e.bql.enriched,e.schema),Os=async e=>ni(e.bql.enriched,e.schema),Ps=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},ks=e=>_e(e.bql.enriched),ke=j("error","error",x((e,t)=>({...e,error:t.error}))),qs=me("stringify",{stringify:z(async e=>(e.config.mutation?.debugger&&console.log(`originalBQLMutation[${De}]`,e.bql.raw),On(e.bql.raw,e.schema)),j("done","enrich",x(He)),ke),enrich:z(Ds,j("done","preQuery",qt(Ps),x(He)),j("done","parseBQL",x(He)),ke),preQuery:z(Cs,j("done","preHookDependencies",qt(ks),x(He)),j("done","parseBQL",x(He)),ke),preHookDependencies:z(Is,j("done","enrich",x(He)),ke),parseBQL:z(As,j("done","flattenBQL",x(Ls)),ke),flattenBQL:z(Os,j("done","adapter",x(Qs)),ke),adapter:z(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Kn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ti(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(Rs)),ke),success:ii(),error:ii()},e=>e),Ns=async e=>new Promise((t,r)=>{fe(qs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),oi=async(e,t,r,n)=>Ns({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var xs=5e3,js=18e4,_s=2e3,Us=1e3,Ws=6e4,cr=class{db;url;username;password;namespace;database;isConnecting;reconnectInterval;constructor(t){this.db=new si,this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database,this.isConnecting=!1,this.reconnectInterval=null;}async _connect(){if(this.isConnecting||this.db.status===ConnectionStatus.Connecting||this.db.status===ConnectionStatus.Connected)return;this.isConnecting=!0,this.db=new si;let t=Math.max(Us,1);for(;;){let r=!1;try{await this.db.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1});break}catch{if(r=!0,await this.close(),this.isClosed)break}r&&(await Vs((1+Math.random()*.1)*t),t=Math.min(2*t,Ws),await this._connect());}this.isConnecting=!1;}async connect(){return this.isClosed&&(this.reconnectInterval=setInterval(()=>this._connect(),_s)),this._connect()}async close(){if(this.reconnectInterval!==null){clearInterval(this.reconnectInterval),this.reconnectInterval=null;try{await this.db.close();}catch(t){console.error("Trying to close an already closed connection:",t);}}}get isClosed(){return this.reconnectInterval===null}async run(t){return new Promise((r,n)=>{let s=setTimeout(()=>{this.close(),this.connect(),n(new Error("Timeout"));},js);this.connect().then(()=>{t(this.db).then(r).catch(n).finally(()=>{clearTimeout(s);});}).catch(n);})}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}},Vs=async e=>new Promise(t=>{setTimeout(t,e);}),Ft=class{queue;connections;constructor(t){let{totalConnections:r,...n}=t;this.queue=[],this.connections=new Array(r).fill(0).map(()=>{let s=new cr(n);return s.connect(),s});}async dequeue(){if(this.queue.length===0||this.connections.length===0)return;let t=this.queue[0];if(this.queue=this.queue.slice(1),t.timeout()){t.cb(new Error("Timeout"),void 0),this.dequeue();return}let r=this.connections.pop();try{t.cb(void 0,r);}catch(n){t.cb(n,void 0);}finally{this.connections.push(r),this.dequeue();}}async run(t){return new Promise((r,n)=>{let s=!1,i=setTimeout(()=>{s=!0,n(new Error("Timeout"));},xs);this.queue.push({cb:(a,o)=>{clearTimeout(i),t(a,o).then(c=>r(c)).catch(c=>n(c));},timeout:()=>s}),this.dequeue();})}async query(...t){return this.run((r,n)=>{if(n)return n.query(...t);throw r})}async query_raw(...t){return this.run((r,n)=>{if(n)return n.query_raw(...t);throw r})}};var De=process.env.npm_package_version;enableMapSet();var dr=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let s=new Ft({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName,totalConnections:8});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Sr(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await gr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...Tt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(oi)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Xu=dr;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
122
|
+
`;r.mutation?.debugger&&console.log(`batchedMutation[${De}]`,n);try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Zn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Gn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Gn(s,r)})},Gn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(s,i=>!i.startsWith("$")):s};var bs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ts=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},ws=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},lr=j("error","error",x((e,t)=>({...e,error:t.error}))),Ms=me("buildMutation",{buildMutation:z(async e=>vn(e.bql.flat,e.schema),j("done","runMutation",x(Ts)),lr),runMutation:z(async e=>Jn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config),j("done","parseMutation",x(ws)),lr),parseMutation:z(async e=>Zn({res:e.surql.res,config:e.config,schema:e.schema}),j("done","success",x(bs)),lr),success:se(),error:se()},e=>e),Ss=async e=>new Promise((t,r)=>{fe(Ms,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ti=async(e,t,r,n,s,i)=>Ss({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ni=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=de(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...ce(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[rt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=ce(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(b=>n(b,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let F=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([b,y])=>{let R=F.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:b});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(b=>n(b,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(b=>b.path===g),F=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([b,y])=>{F.filter(L=>y.includes(L.$op)).forEach(L=>{let D=ce(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:b});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{F.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ii=se,He=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ls=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Qs=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Rs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ds=async e=>Object.keys(e.bql.enriched).length?kt(e.bql.enriched,e.schema,e.config):kt(e.bql.raw,e.schema,e.config),Cs=async e=>An(e.bql.enriched,e.schema,e.config,e.handles),Is=async e=>Nn(e.bql.enriched,e.schema,e.config,e.handles),As=async e=>Jr(e.bql.enriched,e.schema),Os=async e=>ni(e.bql.enriched,e.schema),Ps=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},ks=e=>_e(e.bql.enriched),ke=j("error","error",x((e,t)=>({...e,error:t.error}))),qs=me("stringify",{stringify:z(async e=>(e.config.mutation?.debugger&&console.log(`originalBQLMutation[${De}]`,JSON.stringify(e.bql.raw,null,2)),On(e.bql.raw,e.schema)),j("done","enrich",x(He)),ke),enrich:z(Ds,j("done","preQuery",qt(Ps),x(He)),j("done","parseBQL",x(He)),ke),preQuery:z(Cs,j("done","preHookDependencies",qt(ks),x(He)),j("done","parseBQL",x(He)),ke),preHookDependencies:z(Is,j("done","enrich",x(He)),ke),parseBQL:z(As,j("done","flattenBQL",x(Ls)),ke),flattenBQL:z(Os,j("done","adapter",x(Qs)),ke),adapter:z(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Kn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ti(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(Rs)),ke),success:ii(),error:ii()},e=>e),Ns=async e=>new Promise((t,r)=>{fe(qs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),oi=async(e,t,r,n)=>Ns({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var xs=5e3,js=18e4,_s=2e3,Us=1e3,Ws=6e4,cr=class{db;url;username;password;namespace;database;isConnecting;reconnectInterval;constructor(t){this.db=new si,this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database,this.isConnecting=!1,this.reconnectInterval=null;}async _connect(){if(this.isConnecting||this.db.status===ConnectionStatus.Connecting||this.db.status===ConnectionStatus.Connected)return;this.isConnecting=!0,this.db=new si;let t=Math.max(Us,1);for(;;){let r=!1;try{await this.db.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1});break}catch{if(r=!0,await this.close(),this.isClosed)break}r&&(await Vs((1+Math.random()*.1)*t),t=Math.min(2*t,Ws),await this._connect());}this.isConnecting=!1;}async connect(){return this.isClosed&&(this.reconnectInterval=setInterval(()=>this._connect(),_s)),this._connect()}async close(){if(this.reconnectInterval!==null){clearInterval(this.reconnectInterval),this.reconnectInterval=null;try{await this.db.close();}catch(t){console.error("Trying to close an already closed connection:",t);}}}get isClosed(){return this.reconnectInterval===null}async run(t){return new Promise((r,n)=>{let s=setTimeout(()=>{this.close(),this.connect(),n(new Error("Timeout"));},js);this.connect().then(()=>{t(this.db).then(r).catch(n).finally(()=>{clearTimeout(s);});}).catch(n);})}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}},Vs=async e=>new Promise(t=>{setTimeout(t,e);}),Ft=class{queue;connections;constructor(t){let{totalConnections:r,...n}=t;this.queue=[],this.connections=new Array(r).fill(0).map(()=>{let s=new cr(n);return s.connect(),s});}async dequeue(){if(this.queue.length===0||this.connections.length===0)return;let t=this.queue[0];if(this.queue=this.queue.slice(1),t.timeout()){t.cb(new Error("Timeout"),void 0),this.dequeue();return}let r=this.connections.pop();try{t.cb(void 0,r);}catch(n){t.cb(n,void 0);}finally{this.connections.push(r),this.dequeue();}}async run(t){return new Promise((r,n)=>{let s=!1,i=setTimeout(()=>{s=!0,n(new Error("Timeout"));},xs);this.queue.push({cb:(a,o)=>{clearTimeout(i),t(a,o).then(c=>r(c)).catch(c=>n(c));},timeout:()=>s}),this.dequeue();})}async query(...t){return this.run((r,n)=>{if(n)return n.query(...t);throw r})}async query_raw(...t){return this.run((r,n)=>{if(n)return n.query_raw(...t);throw r})}};enableMapSet();var dr=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let s=new Ft({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName,totalConnections:8});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Sr(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await gr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...Tt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(oi)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Zu=dr;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
123
123
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
124
124
|
//! Todo: Sandbox the function in computeFunction()
|
|
125
125
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
126
126
|
//!old
|
|
127
|
-
export{
|
|
127
|
+
export{Zu as default};//# sourceMappingURL=index.mjs.map
|
|
128
128
|
//# sourceMappingURL=index.mjs.map
|