@elyx-code/project-logic-tree 0.0.6374 → 0.0.6375
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.ts +2 -1
- package/dist/index.js +20 -26
- package/dist/index.umd.cjs +3 -3
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -99,7 +99,7 @@ ${Fy(a)}`,issue:null})):p.push(new ee({id:`${i.id}--${q.ReferencedEntityNotFound
|
|
|
99
99
|
${Fy(a)}`,issue:null})):p.push(new ee({id:`${i.id}--${ae.InvalidObjectStructure}`,code:ae.InvalidObjectStructure,severity:Z.Error,message:`Entity of type '${i.type}' with id '${i.id}' is missing the 'declaration' property. This property is required for a '${i.type}' entity and must point to one of the built-in action descriptors reserved for '${f.Condition}' entities.
|
|
100
100
|
${Fy(a)}`,issue:null})),{errors:p,modifiedData:l}}static fromReturnDeclarationToBodyArgumentDeclarationName(i){return`Previous iteration results of '${ie(i,i.project)}'`}static fromBodyArgumentDeclarationToReturnDeclarationName(i){const a=i.name.replace("Previous iteration results of '","");return a.slice(0,a.length-1)}static fromReturnDeclarationToLoopOutputDeclarationName(i){return`Result list of '${ie(i,i.project)}'`}static fromLoopOutputDeclarationToReturnDeclarationName(i){const a=i.name.replace("Result list of '","");return a.slice(0,a.length-1)}static fromLoopOutputDeclarationToBodyArgumentDeclarationName(i){return i.name.replace("Result list of '","Previous iteration results of '")}static fromBodyArgumentDeclarationToLoopOutputDeclarationName(i){return i.name.replace("Previous iteration results of '","Result list of '")}get currentIterationNumberArgumentDeclaration(){var l;const i=(l=ve[f.Loop][this.declaration.id].body.inputs.iterationNumber)==null?void 0:l.id;return this.body.inputs.find(p=>{var t;return!!p.implements&&i===((t=p.implements)==null?void 0:t.id)||p.name===ze.CURRENT_ITERATION_NUMBER_ARG_NAME})}get currentValueArgumentDeclaration(){var l;if(this.declaration.id===Ge.ManualFlow||this.declaration.id===Ge.Counted)return null;const i=(l=ve[f.Loop][this.declaration.id].body.inputs.currentValue)==null?void 0:l.id;return this.body.inputs.find(p=>{var t;return!!p.implements&&i===((t=p.implements)==null?void 0:t.id)||p.name===ze.CURRENT_VALUE_ARG_NAME})||null}get continueStatements(){return pt(this.body).filter(l=>l.type===f.ContinueStatement&&l.parent.id===this.id)}get breakStatements(){return pt(this.body).filter(l=>l.type===f.BreakStatement&&l.parent.id===this.id)}validateGeneratedUpdate(i){const a=[];return i.parent&&a.push(new ee({id:`${this.id}--${q.InvalidParentUpdate}`,code:q.InvalidParentUpdate,severity:Z.Error,message:`Entity of type '${this.type}' with id '${this.id}' cannot have the 'parent' property updated. The 'parent' on a callable entity, is its scope. It scope is auto-calculated implicitly by the its caller.
|
|
101
101
|
If an entity is called by another, they must be in the same scope, which means they have the same parent.
|
|
102
|
-
You shouldn't have to manually update a 'parent' property. The equivalent result is to change its callers, the value writters of its inputs, or the value readers of its outputs.`,issue:null})),{errors:a,modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];if(a==="parent"){const{updated:T,added:w,removed:A}=this.remove({ignoreUpstream:!1},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];if(a==="parent"){const{updated:T,added:w,removed:A}=this.restore({},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){var i;return(i=this.parent)==null||i.unsubscribeDependents([{entity:this,field:"parent"}]),this}subscribeToDependencies(){var i;return(i=this.parent)==null||i.subscribeDependents([{entity:this,field:"parent"}]),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new ze(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.inputs=[...this.inputs],i.outputs=[...this.outputs],i.error=this.error,i.successCalls=[...this.successCalls],i.errorCalls=[...this.errorCalls],i.declaration=this.declaration,i.outputsDeclarations=[...this.outputsDeclarations],i.body=this.body,i.calledByEntry=[...this.calledByEntry],i.calledBySuccess=[...this.calledBySuccess],i.calledByError=[...this.calledByError],i.process=this.process,i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new ze(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.inputs=y.inputs,this.outputs=y.outputs,this.error=y.error,this.successCalls=y.successCalls,this.errorCalls=y.errorCalls,this.declaration=y.declaration,this.outputsDeclarations=y.outputsDeclarations,this.body=y.body,this.calledByEntry=y.calledByEntry,this.calledBySuccess=y.calledBySuccess,this.calledByError=y.calledByError,this.process=y.process,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&this.removeFromParent(a),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.declaration){const l=J(i.declaration),p=this.project.get(l);p&&this.setDeclaration(p)}return i.calledByEntry.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addEntryCaller(t,a),t.addCall(this,a))}),[...this.calledByEntry].forEach(l=>{i.calledByEntry.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledBySuccess.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addSuccessCaller(t,a),t.addSuccessCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledByError.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addErrorCaller(t,a),t.addErrorCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(this.initialData.declaration){const t=J(this.initialData.declaration),y=this.project.get(t);y&&(this.setDeclaration(y),i.push(y))}return this.initialData.calledByEntry.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addEntryCaller(v,null)}),this.initialData.calledBySuccess.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addSuccessCaller(v,null)}),this.initialData.calledByError.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addErrorCaller(v,null)}),{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];this.initialized=!0;const{updated:y,added:v,removed:T}=this.syncChildren(i);return a.push(...y),l.push(...v),p.push(...T),this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){const a=[this],l=[],p=[],t=[];return this.parent===this.project&&this.project.addLoop(this),this.successCalls.forEach(y=>{y.addSuccessCaller(this,i),a.push(y)}),this.errorCalls.forEach(y=>{y.addErrorCaller(this,i),a.push(y)}),this.calledByEntry.forEach(y=>{y.addCall(this,i),a.push(y)}),this.calledBySuccess.forEach(y=>{y.addSuccessCall(this,i),a.push(y)}),this.calledByError.forEach(y=>{y.addErrorCall(this,i),a.push(y)}),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}get calledBy(){return[...this.calledByEntry,...this.calledBySuccess,...this.calledByError]}removeInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-input"))){const l=this.inputs.findIndex(p=>p.id===i.id);return l>-1&&(this.inputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-input",this.id),this}addInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-input"))){return this.inputs.includes(i)?(a==null||a.attemptAutoclose("add-input",this.id),this):(this.inputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-input",this.id),this)}addOutputDeclaration(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-output-declaration"))){return this.outputsDeclarations.includes(i)?(a==null||a.attemptAutoclose("add-output-declaration",this.id),this):(this.outputsDeclarations.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-output-declaration",this.id),this)}removeOutputDeclaration(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-output-declaration"))){const l=this.outputsDeclarations.findIndex(p=>p.id===i.id);return l>-1&&(this.outputsDeclarations.splice(l,1),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("remove-output-declaration",this.id),this}addOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-output"))){return this.outputs.includes(i)?(a==null||a.attemptAutoclose("add-output",this.id),this):(this.outputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-output",this.id),this)}removeOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-output"))){const l=this.outputs.findIndex(p=>p.id===i.id);return l>-1&&(this.outputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-output",this.id),this}setBody(i){return this.body=i,this}detachBody(){return this.body=null,this}addSuccessCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-caller")),l=!1){return this.calledBySuccess.find(p=>p.id===i.id)||(this.calledBySuccess.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-success-caller",this.id),this}addErrorCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-caller")),l=!1){return this.calledByError.find(p=>p.id===i.id)||(this.calledByError.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-error-caller",this.id),this}addEntryCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-entry-caller")),l=!1){return this.calledByEntry.find(p=>p.id===i.id)||(this.calledByEntry.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-entry-caller",this.id),this}addErrorCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-call")),l=!1){return this.errorCalls.find(p=>p.id===i.id)||(this.errorCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-error-call",this.id),this}addSuccessCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-call")),l=!1){return this.successCalls.find(p=>p.id===i.id)||(this.successCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-success-call",this.id),this}removeCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-call")),l=!1){const p=this.successCalls.findIndex(y=>y.id===i.id);p>-1&&(this.successCalls.splice(p,1),a==null||a.add(this,K.Affected));const t=this.errorCalls.findIndex(y=>y.id===i.id);return t>-1&&(this.errorCalls.splice(t,1),a==null||a.add(this,K.Affected)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-call",this.id),this}removeCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-caller")),l=!1){return this.calledBySuccess=this.calledBySuccess.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByError=this.calledByError.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByEntry=this.calledByEntry.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-caller",this.id),this}replaceDetachedChild(i,a){const l=this.detachedChildren.indexOf(i);return l!==-1&&(this.detachedChildren[l]=a),this}subscribeDetachedChild(i){return this.detachedChildren.includes(i)||this.detachedChildren.push(i),this}unsubscribeDetachedChild(i){const a=this.detachedChildren.indexOf(i);return a!==-1&&this.detachedChildren.splice(a,1),this}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}setDeclaration(i){return this.declaration=i,this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.declaration=te(this.initialData.declaration,this.project),this.successCalls=this.initialData.successCalls.map(a=>{const l=te(a,this.project);if(l.addSuccessCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.errorCalls=this.initialData.errorCalls.map(a=>{const l=te(a,this.project);if(l.addErrorCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.inputs=this.initialData.inputs.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.outputs=this.initialData.outputs.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.initialData.process&&(this.process=te(this.initialData.process,this.project),this.process.setParent(this,null),this.process.initChildren(i)),this.initialData.body&&(this.body=te(this.initialData.body,this.project),this.body.setParent(this,null),this.body.initChildren(i)),this.initialData.error&&(this.error=te(this.initialData.error,this.project),this.error.setParent(this,null),this.error.initChildren(i)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.x=i.x||p.x,this.y=i.y||p.y,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await ze.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await ze.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await ze.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await ze.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await ze.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await ze.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){const a=[],l=[],p=[],t=[];return this.parent.type===f.Project?(this.parent.removeLoop(this),t.push(this.parent)):this.parent.detachedChildren.includes(this)&&this.parent.unsubscribeDetachedChild(this),i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){const l=[],p=[],t=[],y=[];if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(v=>{const{updated:T,removed:w,added:A}=v.entity.onDetachedDependencyRemoved(this,v.field,a);l.push(...T),p.push(...w),t.push(...A)}),this.inputs.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.outputs.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.body.remove({ignoreUpstream:!0},a),this.error){const{updated:v,removed:T}=this.error.remove({ignoreUpstream:!0},a);l.push(...v),p.push(...T)}if(this.successCalls.forEach(v=>{l.push(v),v.removeCaller(this,a)}),this.errorCalls.forEach(v=>{l.push(v),v.removeCaller(this,a)}),!i){const v=this.removeFromParent(a);t.push(...v.added),l.push(...v.updated),p.push(...v.removed),y.push(...v.affected),this.calledBy.forEach(T=>{l.push(T),T.removeCall(this,a)})}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){const a=[],l=[],p=[],t=[];return i!=null&&i.hasAdded(this.id)?(i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),this.inputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.outputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.body.restore({},i),this.successCalls.forEach(y=>{l.push(y),y.addSuccessCaller(this,i)}),this.errorCalls.forEach(y=>{l.push(y),y.addErrorCaller(this,i)}),this.calledBySuccess.forEach(y=>{l.push(y),y.addSuccessCall(this,i)}),this.calledByError.forEach(y=>{l.push(y),y.addErrorCall(this,i)}),this.calledByEntry.forEach(y=>{l.push(y),y.addCall(this,i)}),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this})}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.inputs.flatMap(l=>l.toFlat(i)),...this.outputs.flatMap(l=>l.toFlat(i)),...this.outputsDeclarations.flatMap(l=>l.toFlat(i)),...this.process?this.process.toFlat(i):[],...this.successCalls.flatMap(l=>l.toFlat(i)),...this.errorCalls.flatMap(l=>l.toFlat(i)),...this.error?this.error.toFlat(i):[],...this.body?this.body.toFlat(i):[],...this.continueStatements.flatMap(l=>l.toFlat(i)),...this.breakStatements.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.inputs.flatMap(l=>l.toFlatIds(i)),...this.outputs.flatMap(l=>l.toFlatIds(i)),...this.process?this.process.toFlatIds(i):[],...this.successCalls.flatMap(l=>l.toFlatIds(i)),...this.errorCalls.flatMap(l=>l.toFlatIds(i)),...this.error?this.error.toFlatIds(i):[],...this.body?this.body.toFlatIds(i):[],...this.continueStatements.flatMap(l=>l.toFlatIds(i)),...this.breakStatements.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,x:this.x,y:this.y,type:this.type}}toJSON(i=new Set){var a,l;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,calledBySuccess:this.calledBySuccess.map(p=>p.toReference()),calledByError:this.calledByError.map(p=>p.toReference()),calledByEntry:this.calledByEntry.map(p=>p.toReference()),process:((a=this.process)==null?void 0:a.toJSON(i))||null,declaration:this.declaration.toJSON(i),inputs:this.inputs.map(p=>p.toJSON(i)),outputs:this.outputs.map(p=>p.toJSON(i)),outputsDeclarations:this.outputsDeclarations.map(p=>p.toJSON(i)),successCalls:this.successCalls.map(p=>p.toJSON(i)),errorCalls:this.errorCalls.map(p=>p.toJSON(i)),error:((l=this.error)==null?void 0:l.toJSON(i))||null,body:this.body.toJSON(i),parent:this.parent.toReference()})}toJSONClone(i=Le){var l,p,t,y,v,T,w;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),previousVersion:null,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,calledBySuccess:this.calledBySuccess.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByError:this.calledByError.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByEntry:this.calledByEntry.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),process:((T=this.process)==null?void 0:T.toJSONClone({...i,newId:null}))||null,declaration:this.declaration.toJSON(),inputs:this.inputs.map(A=>A.toJSONClone({...i,newId:null})),outputs:this.outputs.map(A=>A.toJSONClone({...i,newId:null})),outputsDeclarations:this.outputsDeclarations.map(A=>A.toJSONClone({...i,newId:null})),successCalls:this.successCalls.map(A=>A.toJSONClone({...i,newId:null})),errorCalls:this.errorCalls.map(A=>A.toJSONClone({...i,newId:null})),error:((w=this.error)==null?void 0:w.toJSONClone({...i,newId:null}))||null,body:this.body.toJSONClone({...i,newId:null}),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l,p,t,y,v;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,declaration:((p=this.declaration)==null?void 0:p.toReference(i))||null,body:((t=this.body)==null?void 0:t.toReference(i))||null,inputs:this.inputs.map(T=>T.toReference(i)),outputs:this.outputs.map(T=>T.toReference(i)),outputsDeclarations:this.outputsDeclarations.map(T=>T.toReference(i)),successCalls:this.successCalls.map(T=>T.toReference(i)),errorCalls:this.errorCalls.map(T=>T.toReference(i)),process:((y=this.process)==null?void 0:y.toReference(i))||null,calledBySuccess:this.calledBySuccess.map(T=>T.toReference(i)),calledByError:this.calledByError.map(T=>T.toReference(i)),calledByEntry:this.calledByEntry.map(T=>T.toReference(i)),error:((v=this.error)==null?void 0:v.toReference(i))||null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...((l=this.body)==null?void 0:l.toFlatJSON(i))||[],...this.successCalls.flatMap(p=>p.toFlatJSON(i)),...this.errorCalls.flatMap(p=>p.toFlatJSON(i)),...this.inputs.flatMap(p=>p.toFlatJSON(i)),...this.outputs.flatMap(p=>p.toFlatJSON(i)),...this.continueStatements.flatMap(p=>p.toFlatJSON(i)),...this.breakStatements.flatMap(p=>p.toFlatJSON(i)),...this.error?this.error.toFlatJSON(i):[],...this.process?this.process.toFlatJSON(i):[]])}toGenerationTarget(){const i=this.parent.type===f.Project?void 0:this.parent.id;return{id:this.id,type:this.type,calledByEntry:this.calledByEntry.map(a=>a.id),calledBySuccess:this.calledBySuccess.map(a=>a.id),calledByError:this.calledByError.map(a=>a.id),declaration:this.declaration.id,parent:i}}toFlatGenerationTarget(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...((l=this.body)==null?void 0:l.toFlatGenerationTarget(i))||[],...this.successCalls.flatMap(p=>p.toFlatGenerationTarget(i)),...this.errorCalls.flatMap(p=>p.toFlatGenerationTarget(i)),...this.inputs.flatMap(p=>p.toFlatGenerationTarget(i)),...this.outputs.flatMap(p=>p.toFlatGenerationTarget(i)),...this.continueStatements.flatMap(p=>p.toFlatGenerationTarget(i)),...this.breakStatements.flatMap(p=>p.toFlatGenerationTarget(i)),...this.error?this.error.toFlatGenerationTarget(i):[],...this.process?this.process.toFlatGenerationTarget(i):[]])}clearErrors(){var i,a;return this.errors=[],this.inputs.forEach(l=>l.clearErrors()),this.outputs.forEach(l=>l.clearErrors()),this.successCalls.forEach(l=>l.clearErrors()),this.errorCalls.forEach(l=>l.clearErrors()),this.continueStatements.forEach(l=>l.clearErrors()),this.breakStatements.forEach(l=>l.clearErrors()),(i=this.process)==null||i.clearErrors(),(a=this.error)==null||a.clearErrors(),this}validate(){const i=Rb(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.inputs.flatMap(a=>a.getErrors()),...this.outputs.flatMap(a=>a.getErrors()),...this.body?this.body.getErrors():[],...this.error?this.error.getErrors():[],...this.process?this.process.getErrors():[]]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var j,k;let t=gr(a,this);const y=this.toJSON(),v=l||P.UUID.uuid();y.inputs=[];const T=v.split("-id"),w=T[T.length-1||0]||v;y.id=v,y.version=P.UUID.uuid(),y.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),y.author=(i==null?void 0:i.author)||"1",y.previousVersion=null,y.deleted=!1;const A=St(y,t);a?A.setParent(a,null):A.setParent(this.parent,null),p&&A.subscribe(),A.initChildren(i),i==null||i.add(A,K.Added);const V=(j=this.inputs)==null?void 0:j.map((S,W)=>S.clone(i,A,w+"-input-map-"+W+"-id",p));A.inputs=V;const N=(k=this.outputs)==null?void 0:k.map((S,W)=>S.clone(i,A,w+"-output-map-"+W+"-id",p));return A.outputs=N,this.body&&(A.body=this.body.clone(i,A,w+"-body-id",p,!0)),this.error&&(A.error=this.error.clone(i,A,w+"-error-map-id",p)),this.process&&(A.process=this.process.clone(i,A,w+"-process-id",p)),i==null||i.attemptAutoclose("clone-entity",this.id),A}getVariableInstances(){return this.body?Xt(this.body).filter(l=>l.type===f.VariableInstance):[]}addReturnStatement(i){return Ht.includes(this.parent.type)&&this.parent.addReturnStatement(i),this}removeReturnStatement(i){return Ht.includes(this.parent.type)&&this.parent.removeReturnStatement(i),this}addBreakStatement(i){return this.breakStatements.includes(i)||this.breakStatements.push(i),this}removeBreakStatement(i){const a=this.breakStatements.indexOf(i);return a!==-1&&this.breakStatements.splice(a,1),this}addContinueStatement(i){return this.continueStatements.includes(i)||this.continueStatements.push(i),this}removeContinueStatement(i){const a=this.continueStatements.indexOf(i);return a!==-1&&this.continueStatements.splice(a,1),this}getUniqueReturnDeclarations(){const i=[];return[...this.breakStatements,...this.continueStatements].forEach(l=>{l.outputs.forEach(t=>{i.find(v=>v===t||ie(v,this.project)===ie(t,this.project)&&Cs(v.dataType,t.dataType))||i.push(t)})}),R(i)}syncTerminationStatements(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-termination-statements"))){const a=[],l=[],p=[],t=[],y=this.getUniqueReturnDeclarations();return[...this.breakStatements,...this.continueStatements].forEach(T=>{const w=T.outputs,A=y.filter(V=>!w.find(N=>ie(V,this.project)===ie(N,this.project)&&Cs(V.dataType,N.dataType)));A.length&&(a.push(T),i==null||i.add(T,K.Updated)),A.forEach(V=>{const N=V.clone(i,T);i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N)})}),i==null||i.attemptAutoclose("sync-termination-statements",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncBodyInputIndexes(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-body-input-indexes"))){const a=[],l=[],p=[],t=[];return this.body.inputs.sort((v,T)=>v.index-T.index),this.body.inputs.forEach((v,T)=>{v.index!==T&&(v.metaSync({index:T},i),a.push(v))}),i==null||i.attemptAutoclose("sync-body-input-indexes",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncBodyArgumentsDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-body-arguments-declarations"))){const a=[],l=[],p=[],t=[],{updated:y,added:v,removed:T}=this.syncFixedBodyArgumentDeclarations(i);a.push(...y),l.push(...v),p.push(...T);const w=this.getUniqueReturnDeclarations(),A=this.body.inputs;w.sort((k,S)=>k.index-S.index),w.forEach(k=>{const S=k.getDataType(i);let ne=A.find(z=>ie(z,this.project)===ze.fromReturnDeclarationToBodyArgumentDeclarationName(k)&&Cs(z.dataType,k.dataType));if(!ne){const z=ze.fromReturnDeclarationToBodyArgumentDeclarationName(k),ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:z,codeName:null,description:`Aggretated list of all previously outputted values from each iteration by the output '${ie(k,this.project)}'`,defaultValue:null,constant:!0,dataType:null,implements:null,index:k.index,required:k.required,parent:this.body.toReference(),writesValues:[]},H=te(ce,this.project);H.setParent(this.body,i),H.initChildren(i),i==null||i.add(H,K.Added),H.addSelfToProject(i),l.push(H),ne=H}const re=this.body.inputs.find(z=>z.index===ne.index&&z!==ne),pe=this.body.inputs.filter(z=>z!==ne);let se=ne.index;re&&(se=Math.max(...pe.map(z=>z.index))+1),ne.index!==se&&(ne.metaSync({index:se},i),a.push(ne));const he=ne.getDataType(i);let X=he;if(S)if(!he||!Cs(he,S)){if(!X){const z=S.clone(i,ne);i==null||i.add(z,K.Added),z.addSelfToProject(i),X=z,l.push(z),a.push(ne)}X.merge(S,i),X.metaSync({isList:!0},i)}else X.isList||(X.metaSync({isList:!0},i),a.push(X));if(!S&&!X){const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!0,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:ne.toReference()},ce=te(z,this.project);ce.metaSync({isList:!0},i),ce.setParent(ne,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),l.push(ce)}});const{updated:V,added:N,removed:j}=this.removeExtraBodyArgumentDeclarations(i);return a.push(...V),l.push(...N),p.push(...j),i==null||i.attemptAutoclose("sync-body-arguments-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncOutputsDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-outputs-declarations"))){const a=[],l=[],p=[],t=[],y=this.getUniqueReturnDeclarations(),v=this.outputsDeclarations;return y.forEach((w,A)=>{w.index!==A&&(w.metaSync({index:A},i),a.push(w))}),y.forEach(w=>{const A=w.getDataType(i);let N=v.find(S=>ie(S,this.project)===ze.fromReturnDeclarationToLoopOutputDeclarationName(w)&&Cs(S.dataType,w.dataType));if(!N){const S=ze.fromReturnDeclarationToLoopOutputDeclarationName(w),W={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ValueDescriptor,name:S,codeName:null,description:`Aggretated list of all previously outputted values from each iteration by the output '${ie(w,this.project)}'`,defaultValue:null,dataType:null,index:w.index,required:w.required,parentRelationType:le.FixedReturns,parent:this.toReference()},ne=te(W,this.project);ne.setParent(this,i),ne.initChildren(i),i==null||i.add(ne,K.Added),ne.addSelfToProject(i),l.push(ne),N=ne}N.index!==w.index&&(N.metaSync({index:w.index},i),a.push(N));let k=N.getDataType(i);if(A)if(!k||!Cs(k,A)){if(!k){const S=A.clone(i,N);i==null||i.add(S,K.Added),S.addSelfToProject(i),k=S,l.push(S),a.push(N)}k.merge(A,i),k.metaSync({isList:!0},i)}else k.isList||(k.metaSync({isList:!0},i),a.push(k));if(!A&&!k){const S={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,parentRelationType:null,isList:!0,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:N.toReference()},W=te(S,this.project);W.metaSync({isList:!0},i),W.setParent(N,i),W.initChildren(i),i==null||i.add(W,K.Added),W.addSelfToProject(i),l.push(W)}}),v.filter(w=>!y.find(V=>ie(w,this.project)===ze.fromReturnDeclarationToLoopOutputDeclarationName(V))).forEach(w=>{if(!(i!=null&&i.hasRemoved(w.id))&&!w.deleted){const{updated:A,removed:V}=w.remove({ignoreUpstream:!1},i);a.push(...A),p.push(...V)}}),i==null||i.attemptAutoclose("sync-outputs-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncOutputMaps(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-extended-properties"))){const a=[],l=[],p=[],t=[],y=this.outputsDeclarations,v=this.outputs;return y.forEach(w=>{var N;let V=v.find(j=>{var k,S;return((k=j.declaration)==null?void 0:k.id)===w.id&&Cs((S=j.declaration)==null?void 0:S.dataType,w.dataType)});if(V)((N=V.declaration)==null?void 0:N.id)!==w.id&&(V.setDeclaration(w),a.push(V));else{const j={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.OutputMap,defaultValue:null,index:w.index,declaration:w.toJSON(),writesValues:[],parent:this.toReference()},k=te(j,this.project);k.setParent(this,i),k.initChildren(i),i==null||i.add(k,K.Added),k.addSelfToProject(i),l.push(k),V=k}V.index!==w.index&&(V.metaSync({index:w.index},i),a.push(V))}),v.filter(w=>!y.find(V=>{var N;return((N=w.declaration)==null?void 0:N.id)===V.id})).forEach(w=>{const{updated:A,removed:V}=w.remove({ignoreUpstream:!1},i);a.push(...A),p.push(...V)}),i==null||i.attemptAutoclose("add-extended-properties",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}createCurrentIterationNumberArgumentDeclaration(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"create-current-iteration-number-argument-declaration"))){const a=[],l=[],p=[],t=[];let v=this.body.inputs.find(V=>{var N;return V.name===ze.CURRENT_ITERATION_NUMBER_ARG_NAME||V.id===((N=this.currentIterationNumberArgumentDeclaration)==null?void 0:N.id)});const T=this.getCurrentIterationNumberBuiltInValueDescriptor();if(!v){const V={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_ITERATION_NUMBER_ARG_NAME,codeName:null,description:"The number of the current iteration",defaultValue:null,constant:!0,dataType:null,implements:T==null?void 0:T.toJSON(),index:this.body.inputs.length,required:!0,parent:this.body.toReference(),writesValues:[]},N=te(V,this.project);N.setParent(this.body,i),N.initChildren(i),i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N),v=N}!v.index&&v.index!==0&&(v.metaSync({index:0},i),a.push(v)),(!v.implements||v.implements.id!==T.id)&&(v.setImplements(T,i),a.push(v));let A=v.getDataType(i);if(!A){const V={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,parentRelationType:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:v.toReference()},N=te(V,this.project);N.setParent(v,i),N.initChildren(i),i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N),A=N}if(!A.entity||A.entity.type!==f.PrimitiveEntity||A.entity.name!==Q.Number||A.entity.id!==ve["primitive-entity"].number.id){const V=this.project.getBuiltIn(ve["primitive-entity"].number.id);A.setEntity(V,i),a.push(A)}return i==null||i.attemptAutoclose("create-current-iteration-number-argument-declaration",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}removeExtraBodyArgumentDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-extra-body-argument-declarations"))){const a=[],l=[],p=[],t=[],y=this.body.inputs,v=this.getUniqueReturnDeclarations();return y.filter(w=>w===this.currentIterationNumberArgumentDeclaration||w===this.currentValueArgumentDeclaration?!1:!v.find(V=>ie(w,this.project)===ze.fromReturnDeclarationToBodyArgumentDeclarationName(V))).forEach(w=>{const{updated:A,removed:V}=w.remove({ignoreUpstream:!1},i);a.push(...A),p.push(...V)}),i==null||i.attemptAutoclose("remove-extra-body-argument-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}createCurrentValueInputBasedOnInputMap(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"create-current-value-input-based-on-input-map"))){var w,A,V,N,j,k,S,W,ne;const a=[],l=[],p=[],t=[];switch(this.declaration.id){case Ge.List:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.List].body.inputs.currentValue.id}),pe=this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.List].inputs.list.id});if(!pe)break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se,i),a.push(re));let X=re.getDataType(i);if(!X){const ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:(w=this.currentValueArgumentDeclaration)==null?void 0:w.toReference()},H=te(ce,this.project);H.setParent(this.currentValueArgumentDeclaration,i),H.initChildren(i),i==null||i.add(H,K.Added),H.addSelfToProject(i),l.push(H),X=H}const z=pe.getDataType(i);X.merge(z,i),X.metaSync({isList:!1},i)}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,defaultValue:null,index:this.body.inputs.length,constant:!0,required:!0,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}case Ge.ManualFlow:break;case Ge.Counted:break;case Ge.ObjectKeys:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectKeys].body.inputs.currentValue.id});if(!this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectKeys].inputs.object.id}))break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se),a.push(re));let X=re.getDataType(i);if(X){const z=this.project.getBuiltIn(ve["primitive-entity"].string.id);((V=X.entity)==null?void 0:V.id)!==z.id&&(X.setEntity(z,i),a.push(X))}else{const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:(A=this.currentValueArgumentDeclaration)==null?void 0:A.toReference()},ce=te(z,this.project);ce.setParent(this.currentValueArgumentDeclaration,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),X=ce}}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,defaultValue:null,index:this.body.inputs.length,constant:!0,required:!0,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}case Ge.ObjectValues:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectValues].body.inputs.currentValue.id}),pe=this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectValues].inputs.object.id});if(!pe)break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se,i),a.push(re));let X=re.getDataType(i);if(X){const z=pe.getDataType(i),ce=((k=z==null?void 0:z.entity)==null?void 0:k.properties)||[];(S=X.orChildrenGroup)==null||S.forEach(H=>{const{updated:de,removed:Te}=H.remove({ignoreUpstream:!1},i);a.push(...de),p.push(...Te)}),ce.forEach(H=>{if(!H.getDataType(i)){const Te={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parentRelationType:Yr.OrDataTypeGroup,parent:X.toReference()},Ne=te(Te,this.project);Ne.setParent(X,i),Ne.initChildren(i),i==null||i.add(Ne,K.Added),Ne.addSelfToProject(i),l.push(Ne)}})}else{const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:(N=this.currentValueArgumentDeclaration)==null?void 0:N.toReference()},ce=te(z,this.project);ce.setParent(this.currentValueArgumentDeclaration,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),X=ce;const H=pe.getDataType(i);(((j=H==null?void 0:H.entity)==null?void 0:j.properties)||[]).forEach(Te=>{if(!Te.getDataType(i)){const we={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parentRelationType:Yr.OrDataTypeGroup,parent:ce.toReference()},Re=te(we,this.project);Re.setParent(ce,i),Re.initChildren(i),i==null||i.add(Re,K.Added),Re.addSelfToProject(i),l.push(Re)}})}}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,constant:!0,defaultValue:null,index:this.body.inputs.length,required:!0,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}case Ge.String:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.String].body.inputs.currentValue.id});if(!this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.String].inputs.string.id}))break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se,i),a.push(re));let X=re.getDataType(i);if(X){const z=this.project.getBuiltIn(ve["primitive-entity"].string.id);((ne=X.entity)==null?void 0:ne.id)!==z.id&&(X.setEntity(z,i),a.push(X))}else{const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:[],orChildrenGroup:[],parent:(W=this.currentValueArgumentDeclaration)==null?void 0:W.toReference()},ce=te(z,this.project);ce.setParent(this.currentValueArgumentDeclaration,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),l.push(ce),X=ce}}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,index:this.body.inputs.length,required:!0,constant:!0,defaultValue:null,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}}const{updated:y,added:v,removed:T}=this.removeExtraBodyArgumentDeclarations(i);return a.push(...y),l.push(...v),p.push(...T),i==null||i.attemptAutoclose("create-current-value-input-based-on-input-map",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncFixedBodyArgumentDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-fixed-body-argument-declarations"))){const a=[],l=[],p=[],t=[],{updated:y,added:v,removed:T}=this.createCurrentIterationNumberArgumentDeclaration(i);a.push(...y),l.push(...v),p.push(...T);const{updated:w,added:A,removed:V}=this.createCurrentValueInputBasedOnInputMap(i);return a.push(...w),l.push(...A),p.push(...V),i==null||i.attemptAutoclose("sync-fixed-body-argument-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncInputMaps(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-input-maps"))){const a=[],l=[],p=[],t=[];switch(this.declaration.id){case Ge.List:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["list-loop"].inputs.list.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["list-loop"].inputs.list.id){const v=this.project.get(ve[f.Loop]["list-loop"].inputs.list.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["list-loop"].inputs.list.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.ManualFlow:{this.inputs.forEach(y=>{y.remove({ignoreUpstream:!1},i),p.push(y)});break}case Ge.Counted:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["counted-loop"].inputs.number.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["counted-loop"].inputs.number.id){const v=this.project.get(ve[f.Loop]["counted-loop"].inputs.number.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["counted-loop"].inputs.number.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.ObjectKeys:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["object-keys-loop"].inputs.object.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["object-keys-loop"].inputs.object.id){const v=this.project.get(ve[f.Loop]["object-keys-loop"].inputs.object.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["object-keys-loop"].inputs.object.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.ObjectValues:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["object-values-loop"].inputs.object.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["object-values-loop"].inputs.object.id){const v=this.project.get(ve[f.Loop]["object-values-loop"].inputs.object.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["object-values-loop"].inputs.object.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.String:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["string-loop"].inputs.string.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["string-loop"].inputs.string.id){const v=this.project.get(ve[f.Loop]["string-loop"].inputs.string.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["string-loop"].inputs.string.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}}return i==null||i.attemptAutoclose("sync-input-maps",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}getCurrentValueBuiltInValueDescriptor(){var a;if(this.declaration.id===Ge.ManualFlow||this.declaration.id===Ge.Counted)return null;const i=(a=ve[f.Loop][this.declaration.id].body.inputs.currentValue)==null?void 0:a.id;return i?this.project.get(i):null}getCurrentIterationNumberBuiltInValueDescriptor(){const i=ve[f.Loop][this.declaration.id].body.inputs.iterationNumber.id;return this.project.get(i)}syncBody(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-body"))){var T;const a=[],l=[],p=[],t=[],y=ve[f.Loop][this.declaration.id].body.id,v=this.project.getBuiltIn(y);if(this.body)((T=this.body.implements)==null?void 0:T.id)!==v.id&&(this.body.setImplements(v,i),this.body.setParent(this,i),a.push(this.body));else{const w={extends:null,id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.FunctionDeclaration,name:v.name,codeName:null,description:null,inputs:[],index:null,calls:[],collapsed:!1,private:!1,implements:v.toJSON(),x:0,y:0,parent:this.toReference()},A=te(w,this.project);A.setParent(this,i),A.initChildren(i),i==null||i.add(A,K.Added),A.addSelfToProject(i),l.push(A)}return i==null||i.attemptAutoclose("sync-body",this.id),{self:this,updated:R(a),added:R(l),removed:R(p),affected:R(t)}}syncChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-children"))){const a=[],l=[],p=[],t=[],{updated:y,added:v,removed:T}=this.syncBody(i);a.push(...y),l.push(...v),p.push(...T);const{updated:w,added:A,removed:V}=this.syncInputMaps(i);a.push(...w),l.push(...A),p.push(...V);const{updated:N,added:j,removed:k}=this.syncTerminationStatements(i);a.push(...N),l.push(...j),p.push(...k);const{updated:S,added:W,removed:ne}=this.syncBodyArgumentsDeclarations(i);a.push(...S),l.push(...W),p.push(...ne);const{updated:re,added:pe,removed:se}=this.syncBodyInputIndexes(i);a.push(...re),l.push(...pe),p.push(...se);const{updated:he,added:X,removed:z}=this.syncOutputsDeclarations(i);a.push(...he),l.push(...X),p.push(...z);const{updated:ce,added:H,removed:de}=this.syncOutputMaps(i);return a.push(...ce),l.push(...H),p.push(...de),i==null||i.attemptAutoclose("sync-children",this.id),{self:this,updated:R(a),added:R(l),removed:R(p),affected:R(t)}}getUnusedInputs(){return this.inputs.filter(i=>i.suggestion||!i.readsValue&&!i.defaultValue)}getUnusedOutputs(){return this.outputs.filter(i=>i.suggestion||!i.writesValues.length)}getUsedInputs(){return this.inputs.filter(i=>!i.suggestion&&(i.readsValue||i.defaultValue))}getUsedOutputs(){return this.outputs.filter(i=>!i.suggestion&&i.writesValues.length)}};D(ze,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(ze,"type",f.Loop),D(ze,"USER_MANAGED_PARENT_TYPES",[...wr,f.Project]),D(ze,"PARENT_TYPES",[...dt.USER_MANAGED_PARENT_TYPES]),D(ze,"CURRENT_ITERATION_NUMBER_ARG_NAME","Current iteration number"),D(ze,"CURRENT_VALUE_ARG_NAME","Current value"),D(ze,"MUTABLE_BASE_PROPERTIES",[]),D(ze,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),D(ze,"BASE_PROPERTIES",[...ze.MUTABLE_BASE_PROPERTIES,...ze.INMUTABLE_BASE_PROPERTIES]),D(ze,"MUTABLE_META_PROPERTIES",[...ze.MUTABLE_BASE_PROPERTIES,"x","y"]),D(ze,"INMUTABLE_META_PROPERTIES",[...ze.INMUTABLE_BASE_PROPERTIES]),D(ze,"META_PROPERTIES",[...ze.MUTABLE_META_PROPERTIES,...ze.INMUTABLE_META_PROPERTIES]),D(ze,"MUTABLE_UPSTREAM_PROPERTIES",["calledBySuccess","calledByError","calledByEntry"]),D(ze,"INMUTABLE_UPSTREAM_PROPERTIES",["parent","declaration"]),D(ze,"UPSTREAM_PROPERTIES",[...ze.MUTABLE_UPSTREAM_PROPERTIES,...ze.INMUTABLE_UPSTREAM_PROPERTIES]),D(ze,"MUTABLE_DOWNSTREAM_PROPERTIES",["body","inputs","outputs","outputsDeclarations","successCalls","errorCalls","error","breakStatements","continueStatements"]),D(ze,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(ze,"DOWNSTREAM_PROPERTIES",[...ze.MUTABLE_DOWNSTREAM_PROPERTIES,...ze.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(ze,"PROPERTIES",[...ze.META_PROPERTIES,...ze.UPSTREAM_PROPERTIES,...ze.DOWNSTREAM_PROPERTIES]);let bi=ze;function s3(d){const u=_ue(),i=d.toJSON();u.safeParse(i).success,d.inputs.forEach(t=>t.validate());const p=[...ya(d)];return Qt(d.errors,p)}const Dhe=Object.freeze(Object.defineProperty({__proto__:null,validate:s3},Symbol.toStringTag,{value:"Module"}));var n3=(d=>(d.Parent="parent",d))(n3||{});const Mt=class Mt extends mr{constructor(i,a){super(i);D(this,"initialData");D(this,"id");D(this,"x");D(this,"y");D(this,"type",f.Condition);D(this,"successCalls",[]);D(this,"errorCalls",[]);D(this,"declaration");D(this,"inputs",[]);D(this,"calledBySuccess",[]);D(this,"calledByError",[]);D(this,"calledByEntry",[]);D(this,"project");D(this,"errors",[]);D(this,"parent");D(this,"detachedDependents",{});D(this,"knownVersions",null);D(this,"activeVersion",!1);D(this,"initialized",!1);D(this,"startedInitialization",!1);this.initialData=i,this.project=a,this.id=i.id,this.x=i.x,this.y=i.y}static new(i=null){return{id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:(i==null?void 0:i.author)||P.sessionAuthor,previousVersion:null,deleted:!1,type:f.Condition,declaration:null,inputs:[],parent:null,calledByEntry:[],calledBySuccess:[],calledByError:[],errorCalls:[],successCalls:[],x:0,y:0}}static fromGenerationTarget(i,a){let l=a;if(i.parent){const A=J(i.parent);l=a.get(A)}const p=i.calledByEntry.map(A=>{const V=J(A);return a.get(V)}),t=i.calledBySuccess.map(A=>{const V=J(A);return a.get(V)}),y=i.calledByError.map(A=>{const V=J(A);return a.get(V)});let v;if(i.declaration){const A=J(i.declaration);v=a.get(A)}const T={id:i.id,version:P.UUID.uuid(),createdAt:L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.Condition,declaration:v,calledByEntry:p,calledBySuccess:t,calledByError:y,errorCalls:[],successCalls:[],inputs:[],x:0,y:0,parent:l},w=te(T,a);return w.setParent(l,null),w}static validateGenerationTarget(i,a){let l=JSON.parse(JSON.stringify(i));const p=[],t=Gr(l,{parent:{list:!1,types:[...wr,f.Project],optional:!0}},a);return l=t.modifiedData,p.push(...t.errors,...br(l)),i.declaration?a.get(i.declaration)?a.conditionDeclarations.find(T=>T.id===i.declaration)||p.push(new ee({id:`${i.id}--${q.InvalidImplementsReference}`,code:q.InvalidImplementsReference,severity:Z.Error,message:`Entity of type '${i.type}' with id '${i.id}' has an 'declaration' property that isn't pointing to an action descriptor reserved for '${f.Condition}' entities.
|
|
102
|
+
You shouldn't have to manually update a 'parent' property. The equivalent result is to change its callers, the value writters of its inputs, or the value readers of its outputs.`,issue:null})),{errors:a,modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];if(a==="parent"){const{updated:T,added:w,removed:A}=this.remove({ignoreUpstream:!1},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];if(a==="parent"){const{updated:T,added:w,removed:A}=this.restore({},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){var i;return(i=this.parent)==null||i.unsubscribeDependents([{entity:this,field:"parent"}]),this}subscribeToDependencies(){var i;return(i=this.parent)==null||i.subscribeDependents([{entity:this,field:"parent"}]),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new ze(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.inputs=[...this.inputs],i.outputs=[...this.outputs],i.error=this.error,i.successCalls=[...this.successCalls],i.errorCalls=[...this.errorCalls],i.declaration=this.declaration,i.outputsDeclarations=[...this.outputsDeclarations],i.body=this.body,i.calledByEntry=[...this.calledByEntry],i.calledBySuccess=[...this.calledBySuccess],i.calledByError=[...this.calledByError],i.process=this.process,i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new ze(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.inputs=y.inputs,this.outputs=y.outputs,this.error=y.error,this.successCalls=y.successCalls,this.errorCalls=y.errorCalls,this.declaration=y.declaration,this.outputsDeclarations=y.outputsDeclarations,this.body=y.body,this.calledByEntry=y.calledByEntry,this.calledBySuccess=y.calledBySuccess,this.calledByError=y.calledByError,this.process=y.process,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&this.removeFromParent(a),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.declaration){const l=J(i.declaration),p=this.project.get(l);p&&this.setDeclaration(p)}return i.calledByEntry.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addEntryCaller(t,a),t.addCall(this,a))}),[...this.calledByEntry].forEach(l=>{i.calledByEntry.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledBySuccess.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addSuccessCaller(t,a),t.addSuccessCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledByError.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addErrorCaller(t,a),t.addErrorCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(this.initialData.declaration){const t=J(this.initialData.declaration),y=this.project.get(t);y&&(this.setDeclaration(y),i.push(y))}return this.initialData.calledByEntry.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addEntryCaller(v,null)}),this.initialData.calledBySuccess.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addSuccessCaller(v,null)}),this.initialData.calledByError.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addErrorCaller(v,null)}),{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];this.initialized=!0;const{updated:y,added:v,removed:T}=this.syncChildren(i);return a.push(...y),l.push(...v),p.push(...T),this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){const a=[this],l=[],p=[],t=[];return this.parent===this.project&&this.project.addLoop(this),this.successCalls.forEach(y=>{y.addSuccessCaller(this,i),a.push(y)}),this.errorCalls.forEach(y=>{y.addErrorCaller(this,i),a.push(y)}),this.calledByEntry.forEach(y=>{y.addCall(this,i),a.push(y)}),this.calledBySuccess.forEach(y=>{y.addSuccessCall(this,i),a.push(y)}),this.calledByError.forEach(y=>{y.addErrorCall(this,i),a.push(y)}),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}get calledBy(){return[...this.calledByEntry,...this.calledBySuccess,...this.calledByError]}removeInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-input"))){const l=this.inputs.findIndex(p=>p.id===i.id);return l>-1&&(this.inputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-input",this.id),this}addInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-input"))){return this.inputs.includes(i)?(a==null||a.attemptAutoclose("add-input",this.id),this):(this.inputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-input",this.id),this)}addOutputDeclaration(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-output-declaration"))){return this.outputsDeclarations.includes(i)?(a==null||a.attemptAutoclose("add-output-declaration",this.id),this):(this.outputsDeclarations.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-output-declaration",this.id),this)}removeOutputDeclaration(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-output-declaration"))){const l=this.outputsDeclarations.findIndex(p=>p.id===i.id);return l>-1&&(this.outputsDeclarations.splice(l,1),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("remove-output-declaration",this.id),this}addOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-output"))){return this.outputs.includes(i)?(a==null||a.attemptAutoclose("add-output",this.id),this):(this.outputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-output",this.id),this)}removeOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-output"))){const l=this.outputs.findIndex(p=>p.id===i.id);return l>-1&&(this.outputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-output",this.id),this}setBody(i){return this.body=i,this}detachBody(){return this.body=null,this}addSuccessCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-caller")),l=!1){return this.calledBySuccess.find(p=>p.id===i.id)||(this.calledBySuccess.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-success-caller",this.id),this}addErrorCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-caller")),l=!1){return this.calledByError.find(p=>p.id===i.id)||(this.calledByError.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-error-caller",this.id),this}addEntryCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-entry-caller")),l=!1){return this.calledByEntry.find(p=>p.id===i.id)||(this.calledByEntry.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-entry-caller",this.id),this}addErrorCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-call")),l=!1){return this.errorCalls.find(p=>p.id===i.id)||(this.errorCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-error-call",this.id),this}addSuccessCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-call")),l=!1){return this.successCalls.find(p=>p.id===i.id)||(this.successCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-success-call",this.id),this}removeCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-call")),l=!1){const p=this.successCalls.findIndex(y=>y.id===i.id);p>-1&&(this.successCalls.splice(p,1),a==null||a.add(this,K.Affected));const t=this.errorCalls.findIndex(y=>y.id===i.id);return t>-1&&(this.errorCalls.splice(t,1),a==null||a.add(this,K.Affected)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-call",this.id),this}removeCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-caller")),l=!1){return this.calledBySuccess=this.calledBySuccess.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByError=this.calledByError.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByEntry=this.calledByEntry.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-caller",this.id),this}replaceDetachedChild(i,a){const l=this.detachedChildren.indexOf(i);return l!==-1&&(this.detachedChildren[l]=a),this}subscribeDetachedChild(i){return this.detachedChildren.includes(i)||this.detachedChildren.push(i),this}unsubscribeDetachedChild(i){const a=this.detachedChildren.indexOf(i);return a!==-1&&this.detachedChildren.splice(a,1),this}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}setDeclaration(i){return this.declaration=i,this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.declaration=te(this.initialData.declaration,this.project),this.successCalls=this.initialData.successCalls.map(a=>{const l=te(a,this.project);if(l.addSuccessCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.errorCalls=this.initialData.errorCalls.map(a=>{const l=te(a,this.project);if(l.addErrorCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.inputs=this.initialData.inputs.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.outputs=this.initialData.outputs.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.initialData.process&&(this.process=te(this.initialData.process,this.project),this.process.setParent(this,null),this.process.initChildren(i)),this.initialData.body&&(this.body=te(this.initialData.body,this.project),this.body.setParent(this,null),this.body.initChildren(i)),this.initialData.error&&(this.error=te(this.initialData.error,this.project),this.error.setParent(this,null),this.error.initChildren(i)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.x=i.x||p.x,this.y=i.y||p.y,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await ze.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await ze.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await ze.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await ze.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await ze.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await ze.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){const a=[],l=[],p=[],t=[];return this.parent.type===f.Project?(this.parent.removeLoop(this),t.push(this.parent)):this.parent.detachedChildren.includes(this)&&this.parent.unsubscribeDetachedChild(this),i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){const l=[],p=[],t=[],y=[];if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(v=>{const{updated:T,removed:w,added:A}=v.entity.onDetachedDependencyRemoved(this,v.field,a);l.push(...T),p.push(...w),t.push(...A)}),this.inputs.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.outputs.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.body.remove({ignoreUpstream:!0},a),this.error){const{updated:v,removed:T}=this.error.remove({ignoreUpstream:!0},a);l.push(...v),p.push(...T)}if(this.successCalls.forEach(v=>{l.push(v),v.removeCaller(this,a)}),this.errorCalls.forEach(v=>{l.push(v),v.removeCaller(this,a)}),!i){const v=this.removeFromParent(a);t.push(...v.added),l.push(...v.updated),p.push(...v.removed),y.push(...v.affected),this.calledBy.forEach(T=>{l.push(T),T.removeCall(this,a)})}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){const a=[],l=[],p=[],t=[];return i!=null&&i.hasAdded(this.id)?(i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),this.inputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.outputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.body.restore({},i),this.successCalls.forEach(y=>{l.push(y),y.addSuccessCaller(this,i)}),this.errorCalls.forEach(y=>{l.push(y),y.addErrorCaller(this,i)}),this.calledBySuccess.forEach(y=>{l.push(y),y.addSuccessCall(this,i)}),this.calledByError.forEach(y=>{l.push(y),y.addErrorCall(this,i)}),this.calledByEntry.forEach(y=>{l.push(y),y.addCall(this,i)}),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this})}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.inputs.flatMap(l=>l.toFlat(i)),...this.outputs.flatMap(l=>l.toFlat(i)),...this.outputsDeclarations.flatMap(l=>l.toFlat(i)),...this.process?this.process.toFlat(i):[],...this.successCalls.flatMap(l=>l.toFlat(i)),...this.errorCalls.flatMap(l=>l.toFlat(i)),...this.error?this.error.toFlat(i):[],...this.body?this.body.toFlat(i):[],...this.continueStatements.flatMap(l=>l.toFlat(i)),...this.breakStatements.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.inputs.flatMap(l=>l.toFlatIds(i)),...this.outputs.flatMap(l=>l.toFlatIds(i)),...this.process?this.process.toFlatIds(i):[],...this.successCalls.flatMap(l=>l.toFlatIds(i)),...this.errorCalls.flatMap(l=>l.toFlatIds(i)),...this.error?this.error.toFlatIds(i):[],...this.body?this.body.toFlatIds(i):[],...this.continueStatements.flatMap(l=>l.toFlatIds(i)),...this.breakStatements.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,x:this.x,y:this.y,type:this.type}}toJSON(i=new Set){var a,l;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,calledBySuccess:this.calledBySuccess.map(p=>p.toReference()),calledByError:this.calledByError.map(p=>p.toReference()),calledByEntry:this.calledByEntry.map(p=>p.toReference()),process:((a=this.process)==null?void 0:a.toJSON(i))||null,declaration:this.declaration.toJSON(i),inputs:this.inputs.map(p=>p.toJSON(i)),outputs:this.outputs.map(p=>p.toJSON(i)),outputsDeclarations:this.outputsDeclarations.map(p=>p.toJSON(i)),successCalls:this.successCalls.map(p=>p.toJSON(i)),errorCalls:this.errorCalls.map(p=>p.toJSON(i)),error:((l=this.error)==null?void 0:l.toJSON(i))||null,body:this.body.toJSON(i),parent:this.parent.toReference()})}toJSONClone(i=Le){var l,p,t,y,v,T,w;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),previousVersion:null,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,calledBySuccess:this.calledBySuccess.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByError:this.calledByError.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByEntry:this.calledByEntry.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),process:((T=this.process)==null?void 0:T.toJSONClone({...i,newId:null}))||null,declaration:this.declaration.toJSON(),inputs:this.inputs.map(A=>A.toJSONClone({...i,newId:null})),outputs:this.outputs.map(A=>A.toJSONClone({...i,newId:null})),outputsDeclarations:this.outputsDeclarations.map(A=>A.toJSONClone({...i,newId:null})),successCalls:this.successCalls.map(A=>A.toJSONClone({...i,newId:null})),errorCalls:this.errorCalls.map(A=>A.toJSONClone({...i,newId:null})),error:((w=this.error)==null?void 0:w.toJSONClone({...i,newId:null}))||null,body:this.body.toJSONClone({...i,newId:null}),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l,p,t,y,v;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,declaration:((p=this.declaration)==null?void 0:p.toReference(i))||null,body:((t=this.body)==null?void 0:t.toReference(i))||null,inputs:this.inputs.map(T=>T.toReference(i)),outputs:this.outputs.map(T=>T.toReference(i)),outputsDeclarations:this.outputsDeclarations.map(T=>T.toReference(i)),successCalls:this.successCalls.map(T=>T.toReference(i)),errorCalls:this.errorCalls.map(T=>T.toReference(i)),process:((y=this.process)==null?void 0:y.toReference(i))||null,calledBySuccess:this.calledBySuccess.map(T=>T.toReference(i)),calledByError:this.calledByError.map(T=>T.toReference(i)),calledByEntry:this.calledByEntry.map(T=>T.toReference(i)),error:((v=this.error)==null?void 0:v.toReference(i))||null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...((l=this.body)==null?void 0:l.toFlatJSON(i))||[],...this.successCalls.flatMap(p=>p.toFlatJSON(i)),...this.errorCalls.flatMap(p=>p.toFlatJSON(i)),...this.inputs.flatMap(p=>p.toFlatJSON(i)),...this.outputs.flatMap(p=>p.toFlatJSON(i)),...this.continueStatements.flatMap(p=>p.toFlatJSON(i)),...this.breakStatements.flatMap(p=>p.toFlatJSON(i)),...this.error?this.error.toFlatJSON(i):[],...this.process?this.process.toFlatJSON(i):[]])}toGenerationTarget(){const i=this.parent.type===f.Project?void 0:this.parent.id;return{id:this.id,type:this.type,calledByEntry:this.calledByEntry.map(a=>a.id),calledBySuccess:this.calledBySuccess.map(a=>a.id),calledByError:this.calledByError.map(a=>a.id),declaration:this.declaration.id,parent:i}}toFlatGenerationTarget(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...((l=this.body)==null?void 0:l.toFlatGenerationTarget(i))||[],...this.successCalls.flatMap(p=>p.toFlatGenerationTarget(i)),...this.errorCalls.flatMap(p=>p.toFlatGenerationTarget(i)),...this.inputs.flatMap(p=>p.toFlatGenerationTarget(i)),...this.outputs.flatMap(p=>p.toFlatGenerationTarget(i)),...this.continueStatements.flatMap(p=>p.toFlatGenerationTarget(i)),...this.breakStatements.flatMap(p=>p.toFlatGenerationTarget(i)),...this.error?this.error.toFlatGenerationTarget(i):[],...this.process?this.process.toFlatGenerationTarget(i):[]])}clearErrors(){var i,a;return this.errors=[],this.inputs.forEach(l=>l.clearErrors()),this.outputs.forEach(l=>l.clearErrors()),this.successCalls.forEach(l=>l.clearErrors()),this.errorCalls.forEach(l=>l.clearErrors()),this.continueStatements.forEach(l=>l.clearErrors()),this.breakStatements.forEach(l=>l.clearErrors()),(i=this.process)==null||i.clearErrors(),(a=this.error)==null||a.clearErrors(),this}validate(){const i=Rb(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.inputs.flatMap(a=>a.getErrors()),...this.outputs.flatMap(a=>a.getErrors()),...this.body?this.body.getErrors():[],...this.error?this.error.getErrors():[],...this.process?this.process.getErrors():[]]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var j,k;let t=gr(a,this);const y=this.toJSON(),v=l||P.UUID.uuid();y.inputs=[];const T=v.split("-id"),w=T[T.length-1||0]||v;y.id=v,y.version=P.UUID.uuid(),y.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),y.author=(i==null?void 0:i.author)||"1",y.previousVersion=null,y.deleted=!1;const A=St(y,t);a?A.setParent(a,null):A.setParent(this.parent,null),p&&A.subscribe(),A.initChildren(i),i==null||i.add(A,K.Added);const V=(j=this.inputs)==null?void 0:j.map((S,W)=>S.clone(i,A,w+"-input-map-"+W+"-id",p));A.inputs=V;const N=(k=this.outputs)==null?void 0:k.map((S,W)=>S.clone(i,A,w+"-output-map-"+W+"-id",p));return A.outputs=N,this.body&&(A.body=this.body.clone(i,A,w+"-body-id",p,!0)),this.error&&(A.error=this.error.clone(i,A,w+"-error-map-id",p)),this.process&&(A.process=this.process.clone(i,A,w+"-process-id",p)),i==null||i.attemptAutoclose("clone-entity",this.id),A}getVariableInstances(){return this.body?Xt(this.body).filter(l=>l.type===f.VariableInstance):[]}addReturnStatement(i){return Ht.includes(this.parent.type)&&this.parent.addReturnStatement(i),this}removeReturnStatement(i){return Ht.includes(this.parent.type)&&this.parent.removeReturnStatement(i),this}addBreakStatement(i){return this.breakStatements.includes(i)||this.breakStatements.push(i),this}removeBreakStatement(i){const a=this.breakStatements.indexOf(i);return a!==-1&&this.breakStatements.splice(a,1),this}addContinueStatement(i){return this.continueStatements.includes(i)||this.continueStatements.push(i),this}removeContinueStatement(i){const a=this.continueStatements.indexOf(i);return a!==-1&&this.continueStatements.splice(a,1),this}getUniqueReturnDeclarations(){const i=[];return[...this.breakStatements,...this.continueStatements].forEach(l=>{l.outputs.forEach(t=>{i.find(v=>v===t||ie(v,this.project)===ie(t,this.project)&&Cs(v.dataType,t.dataType))||i.push(t)})}),R(i)}syncTerminationStatements(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-termination-statements"))){const a=[],l=[],p=[],t=[],y=this.getUniqueReturnDeclarations();return[...this.breakStatements,...this.continueStatements].forEach(T=>{const w=T.outputs,A=y.filter(V=>!w.find(N=>ie(V,this.project)===ie(N,this.project)&&Cs(V.dataType,N.dataType)));A.length&&(a.push(T),i==null||i.add(T,K.Updated)),A.forEach(V=>{const N=V.clone(i,T);i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N)})}),i==null||i.attemptAutoclose("sync-termination-statements",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncBodyInputIndexes(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-body-input-indexes"))){const a=[],l=[],p=[],t=[];return this.body.inputs.sort((v,T)=>v.index-T.index),this.body.inputs.forEach((v,T)=>{v.index!==T&&(v.metaSync({index:T},i),a.push(v))}),i==null||i.attemptAutoclose("sync-body-input-indexes",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncBodyArgumentsDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-body-arguments-declarations"))){const a=[],l=[],p=[],t=[],{updated:y,added:v,removed:T}=this.syncFixedBodyArgumentDeclarations(i);a.push(...y),l.push(...v),p.push(...T);const w=this.getUniqueReturnDeclarations(),A=this.body.inputs;w.sort((k,S)=>k.index-S.index),w.forEach(k=>{const S=k.getDataType(i);let ne=A.find(z=>ie(z,this.project)===ze.fromReturnDeclarationToBodyArgumentDeclarationName(k)&&Cs(z.dataType,k.dataType));if(!ne){const z=ze.fromReturnDeclarationToBodyArgumentDeclarationName(k),ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:z,codeName:null,description:`Aggretated list of all previously outputted values from each iteration by the output '${ie(k,this.project)}'`,defaultValue:null,constant:!0,dataType:null,implements:null,index:k.index,required:k.required,parent:this.body.toReference(),writesValues:[]},H=te(ce,this.project);H.setParent(this.body,i),H.initChildren(i),i==null||i.add(H,K.Added),H.addSelfToProject(i),l.push(H),ne=H}const re=this.body.inputs.find(z=>z.index===ne.index&&z!==ne),pe=this.body.inputs.filter(z=>z!==ne);let se=ne.index;re&&(se=Math.max(...pe.map(z=>z.index))+1),ne.index!==se&&(ne.metaSync({index:se},i),a.push(ne));const he=ne.getDataType(i);let X=he;if(S)if(!he||!Cs(he,S)){if(!X){const z=S.clone(i,ne);i==null||i.add(z,K.Added),z.addSelfToProject(i),X=z,l.push(z),a.push(ne)}X.merge(S,i),X.metaSync({isList:!0},i)}else X.isList||(X.metaSync({isList:!0},i),a.push(X));if(!S&&!X){const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!0,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:ne.toReference()},ce=te(z,this.project);ce.metaSync({isList:!0},i),ce.setParent(ne,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),l.push(ce)}});const{updated:V,added:N,removed:j}=this.removeExtraBodyArgumentDeclarations(i);return a.push(...V),l.push(...N),p.push(...j),i==null||i.attemptAutoclose("sync-body-arguments-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncOutputsDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-outputs-declarations"))){const a=[],l=[],p=[],t=[],y=this.getUniqueReturnDeclarations(),v=this.outputsDeclarations;return y.forEach((w,A)=>{w.index!==A&&(w.metaSync({index:A},i),a.push(w))}),y.forEach(w=>{const A=w.getDataType(i);let N=v.find(S=>ie(S,this.project)===ze.fromReturnDeclarationToLoopOutputDeclarationName(w)&&Cs(S.dataType,w.dataType));if(!N){const S=ze.fromReturnDeclarationToLoopOutputDeclarationName(w),W={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ValueDescriptor,name:S,codeName:null,description:`Aggretated list of all previously outputted values from each iteration by the output '${ie(w,this.project)}'`,defaultValue:null,dataType:null,index:w.index,required:w.required,parentRelationType:le.FixedReturns,parent:this.toReference()},ne=te(W,this.project);ne.setParent(this,i),ne.initChildren(i),i==null||i.add(ne,K.Added),ne.addSelfToProject(i),l.push(ne),N=ne}N.index!==w.index&&(N.metaSync({index:w.index},i),a.push(N));let k=N.getDataType(i);if(A)if(!k||!Cs(k,A)){if(!k){const S=A.clone(i,N);i==null||i.add(S,K.Added),S.addSelfToProject(i),k=S,l.push(S),a.push(N)}k.merge(A,i),k.metaSync({isList:!0},i)}else k.isList||(k.metaSync({isList:!0},i),a.push(k));if(!A&&!k){const S={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,parentRelationType:null,isList:!0,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:N.toReference()},W=te(S,this.project);W.metaSync({isList:!0},i),W.setParent(N,i),W.initChildren(i),i==null||i.add(W,K.Added),W.addSelfToProject(i),l.push(W)}}),v.filter(w=>!y.find(V=>ie(w,this.project)===ze.fromReturnDeclarationToLoopOutputDeclarationName(V))).forEach(w=>{if(!(i!=null&&i.hasRemoved(w.id))&&!w.deleted){const{updated:A,removed:V}=w.remove({ignoreUpstream:!1},i);a.push(...A),p.push(...V)}}),i==null||i.attemptAutoclose("sync-outputs-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncOutputMaps(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-extended-properties"))){const a=[],l=[],p=[],t=[],y=this.outputsDeclarations,v=this.outputs;return y.forEach(w=>{var N;let V=v.find(j=>{var k,S;return((k=j.declaration)==null?void 0:k.id)===w.id&&Cs((S=j.declaration)==null?void 0:S.dataType,w.dataType)});if(V)((N=V.declaration)==null?void 0:N.id)!==w.id&&(V.setDeclaration(w),a.push(V));else{const j={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.OutputMap,defaultValue:null,index:w.index,declaration:w.toJSON(),writesValues:[],parent:this.toReference()},k=te(j,this.project);k.setParent(this,i),k.initChildren(i),i==null||i.add(k,K.Added),k.addSelfToProject(i),l.push(k),V=k}V.index!==w.index&&(V.metaSync({index:w.index},i),a.push(V))}),v.filter(w=>!y.find(V=>{var N;return((N=w.declaration)==null?void 0:N.id)===V.id})).forEach(w=>{const{updated:A,removed:V}=w.remove({ignoreUpstream:!1},i);a.push(...A),p.push(...V)}),i==null||i.attemptAutoclose("add-extended-properties",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}createCurrentIterationNumberArgumentDeclaration(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"create-current-iteration-number-argument-declaration"))){const a=[],l=[],p=[],t=[];let v=this.body.inputs.find(V=>{var N;return V.name===ze.CURRENT_ITERATION_NUMBER_ARG_NAME||V.id===((N=this.currentIterationNumberArgumentDeclaration)==null?void 0:N.id)});const T=this.getCurrentIterationNumberBuiltInValueDescriptor();if(!v){const V={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_ITERATION_NUMBER_ARG_NAME,codeName:null,description:"The number of the current iteration",defaultValue:null,constant:!0,dataType:null,implements:T==null?void 0:T.toJSON(),index:this.body.inputs.length,required:!0,parent:this.body.toReference(),writesValues:[]},N=te(V,this.project);N.setParent(this.body,i),N.initChildren(i),i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N),v=N}!v.index&&v.index!==0&&(v.metaSync({index:0},i),a.push(v)),(!v.implements||v.implements.id!==T.id)&&(v.setImplements(T,i),a.push(v));let A=v.getDataType(i);if(!A){const V={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,parentRelationType:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:v.toReference()},N=te(V,this.project);N.setParent(v,i),N.initChildren(i),i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N),A=N}if(!A.entity||A.entity.type!==f.PrimitiveEntity||A.entity.name!==Q.Number||A.entity.id!==ve["primitive-entity"].number.id){const V=this.project.getBuiltIn(ve["primitive-entity"].number.id);A.setEntity(V,i),a.push(A)}return i==null||i.attemptAutoclose("create-current-iteration-number-argument-declaration",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}removeExtraBodyArgumentDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-extra-body-argument-declarations"))){const a=[],l=[],p=[],t=[],y=this.body.inputs,v=this.getUniqueReturnDeclarations();return y.filter(w=>w===this.currentIterationNumberArgumentDeclaration||w===this.currentValueArgumentDeclaration?!1:!v.find(V=>ie(w,this.project)===ze.fromReturnDeclarationToBodyArgumentDeclarationName(V))).forEach(w=>{const{updated:A,removed:V}=w.remove({ignoreUpstream:!1},i);a.push(...A),p.push(...V)}),i==null||i.attemptAutoclose("remove-extra-body-argument-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}createCurrentValueInputBasedOnInputMap(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"create-current-value-input-based-on-input-map"))){var w,A,V,N,j,k,S,W,ne;const a=[],l=[],p=[],t=[];switch(this.declaration.id){case Ge.List:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.List].body.inputs.currentValue.id}),pe=this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.List].inputs.list.id});if(!pe)break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se,i),a.push(re));let X=re.getDataType(i);if(!X){const ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:(w=this.currentValueArgumentDeclaration)==null?void 0:w.toReference()},H=te(ce,this.project);H.setParent(this.currentValueArgumentDeclaration,i),H.initChildren(i),i==null||i.add(H,K.Added),H.addSelfToProject(i),l.push(H),X=H}const z=pe.getDataType(i);X.merge(z,i),X.metaSync({isList:!1},i)}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,defaultValue:null,index:this.body.inputs.length,constant:!0,required:!0,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}case Ge.ManualFlow:break;case Ge.Counted:break;case Ge.ObjectKeys:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectKeys].body.inputs.currentValue.id});if(!this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectKeys].inputs.object.id}))break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se),a.push(re));let X=re.getDataType(i);if(X){const z=this.project.getBuiltIn(ve["primitive-entity"].string.id);((V=X.entity)==null?void 0:V.id)!==z.id&&(X.setEntity(z,i),a.push(X))}else{const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:(A=this.currentValueArgumentDeclaration)==null?void 0:A.toReference()},ce=te(z,this.project);ce.setParent(this.currentValueArgumentDeclaration,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),X=ce}}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,defaultValue:null,index:this.body.inputs.length,constant:!0,required:!0,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}case Ge.ObjectValues:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectValues].body.inputs.currentValue.id}),pe=this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.ObjectValues].inputs.object.id});if(!pe)break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se,i),a.push(re));let X=re.getDataType(i);if(X){const z=pe.getDataType(i),ce=((k=z==null?void 0:z.entity)==null?void 0:k.properties)||[];(S=X.orChildrenGroup)==null||S.forEach(H=>{const{updated:de,removed:Te}=H.remove({ignoreUpstream:!1},i);a.push(...de),p.push(...Te)}),ce.forEach(H=>{if(!H.getDataType(i)){const Te={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parentRelationType:Yr.OrDataTypeGroup,parent:X.toReference()},Ne=te(Te,this.project);Ne.setParent(X,i),Ne.initChildren(i),i==null||i.add(Ne,K.Added),Ne.addSelfToProject(i),l.push(Ne)}})}else{const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:(N=this.currentValueArgumentDeclaration)==null?void 0:N.toReference()},ce=te(z,this.project);ce.setParent(this.currentValueArgumentDeclaration,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),X=ce;const H=pe.getDataType(i);(((j=H==null?void 0:H.entity)==null?void 0:j.properties)||[]).forEach(Te=>{if(!Te.getDataType(i)){const we={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parentRelationType:Yr.OrDataTypeGroup,parent:ce.toReference()},Re=te(we,this.project);Re.setParent(ce,i),Re.initChildren(i),i==null||i.add(Re,K.Added),Re.addSelfToProject(i),l.push(Re)}})}}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,constant:!0,defaultValue:null,index:this.body.inputs.length,required:!0,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}case Ge.String:{const re=this.body.inputs.find(he=>{var X;return((X=he.implements)==null?void 0:X.id)===ve[f.Loop][Ge.String].body.inputs.currentValue.id});if(!this.inputs.find(he=>{var X;return((X=he.declaration)==null?void 0:X.id)===ve[f.Loop][Ge.String].inputs.string.id}))break;const se=this.getCurrentValueBuiltInValueDescriptor();if(re){se&&(!re.implements||re.implements.id!==se.id)&&(re.setImplements(se,i),a.push(re));let X=re.getDataType(i);if(X){const z=this.project.getBuiltIn(ve["primitive-entity"].string.id);((ne=X.entity)==null?void 0:ne.id)!==z.id&&(X.setEntity(z,i),a.push(X))}else{const z={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:[],implementationChooseOne:!1,parentRelationType:null,staticEntities:null,interactiveEntities:null,actionEntities:null,isList:!1,entity:null,asType:!1,like:!1,inferred:!1,andChildrenGroup:null,orChildrenGroup:null,parent:(W=this.currentValueArgumentDeclaration)==null?void 0:W.toReference()},ce=te(z,this.project);ce.setParent(this.currentValueArgumentDeclaration,i),ce.initChildren(i),i==null||i.add(ce,K.Added),ce.addSelfToProject(i),l.push(ce),X=ce}}else{const he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.ArgumentDeclaration,name:ze.CURRENT_VALUE_ARG_NAME,codeName:null,description:null,index:this.body.inputs.length,required:!0,constant:!0,defaultValue:null,implements:se,writesValues:[],dataType:null,parent:this.body.toReference()},X=te(he,this.project);X.setParent(this.body,i),X.initChildren(i),i==null||i.add(X,K.Added),X.addSelfToProject(i),se&&(!X.implements||X.implements.id!==se.id)&&(X.setImplements(se,i),a.push(X)),l.push(X)}break}}const{updated:y,added:v,removed:T}=this.removeExtraBodyArgumentDeclarations(i);return a.push(...y),l.push(...v),p.push(...T),i==null||i.attemptAutoclose("create-current-value-input-based-on-input-map",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncFixedBodyArgumentDeclarations(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-fixed-body-argument-declarations"))){const a=[],l=[],p=[],t=[],{updated:y,added:v,removed:T}=this.createCurrentIterationNumberArgumentDeclaration(i);a.push(...y),l.push(...v),p.push(...T);const{updated:w,added:A,removed:V}=this.createCurrentValueInputBasedOnInputMap(i);return a.push(...w),l.push(...A),p.push(...V),i==null||i.attemptAutoclose("sync-fixed-body-argument-declarations",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncInputMaps(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-input-maps"))){const a=[],l=[],p=[],t=[];switch(this.declaration.id){case Ge.List:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["list-loop"].inputs.list.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["list-loop"].inputs.list.id){const v=this.project.get(ve[f.Loop]["list-loop"].inputs.list.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["list-loop"].inputs.list.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.ManualFlow:{this.inputs.forEach(y=>{y.remove({ignoreUpstream:!1},i),p.push(y)});break}case Ge.Counted:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["counted-loop"].inputs.number.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["counted-loop"].inputs.number.id){const v=this.project.get(ve[f.Loop]["counted-loop"].inputs.number.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["counted-loop"].inputs.number.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.ObjectKeys:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["object-keys-loop"].inputs.object.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["object-keys-loop"].inputs.object.id){const v=this.project.get(ve[f.Loop]["object-keys-loop"].inputs.object.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["object-keys-loop"].inputs.object.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.ObjectValues:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["object-values-loop"].inputs.object.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["object-values-loop"].inputs.object.id){const v=this.project.get(ve[f.Loop]["object-values-loop"].inputs.object.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["object-values-loop"].inputs.object.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}case Ge.String:{let y=null;if(this.inputs.forEach(v=>{var T;((T=v.declaration)==null?void 0:T.id)===ve[f.Loop]["string-loop"].inputs.string.id?y=v:(v.remove({ignoreUpstream:!1},i),p.push(v))}),y){if(y.declaration.id!==ve[f.Loop]["string-loop"].inputs.string.id){const v=this.project.get(ve[f.Loop]["string-loop"].inputs.string.id);y.setDeclaration(v),a.push(y)}}else{const v=this.project.get(ve[f.Loop]["string-loop"].inputs.string.id),T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,name:null,codeName:null,description:null,index:0,declaration:v.toJSON(),readsValue:null,defaultValue:null,parent:this.toReference()},w=te(T,this.project);w.setParent(this,i),w.initChildren(i),i==null||i.add(w,K.Added),w.addSelfToProject(i),l.push(w)}break}}return i==null||i.attemptAutoclose("sync-input-maps",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}getCurrentValueBuiltInValueDescriptor(){var a;if(this.declaration.id===Ge.ManualFlow||this.declaration.id===Ge.Counted)return null;const i=(a=ve[f.Loop][this.declaration.id].body.inputs.currentValue)==null?void 0:a.id;return i?this.project.get(i):null}getCurrentIterationNumberBuiltInValueDescriptor(){const i=ve[f.Loop][this.declaration.id].body.inputs.iterationNumber.id;return this.project.get(i)}syncBody(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-body"))){var T;const a=[],l=[],p=[],t=[],y=ve[f.Loop][this.declaration.id].body.id,v=this.project.getBuiltIn(y);if(this.body)((T=this.body.implements)==null?void 0:T.id)!==v.id&&(this.body.setImplements(v,i),this.body.setParent(this,i),a.push(this.body));else{const w={extends:null,id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.FunctionDeclaration,name:v.name,codeName:null,description:null,inputs:[],index:null,calls:[],collapsed:!1,private:!1,implements:v.toJSON(),x:0,y:0,parent:this.toReference()},A=te(w,this.project);A.setParent(this,i),A.initChildren(i),i==null||i.add(A,K.Added),A.addSelfToProject(i),l.push(A)}return i==null||i.attemptAutoclose("sync-body",this.id),{self:this,updated:R(a),added:R(l),removed:R(p),affected:R(t)}}syncChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-children"))){const a=[],l=[],p=[],t=[],{updated:y,added:v,removed:T}=this.syncBody(i);a.push(...y),l.push(...v),p.push(...T);const{updated:w,added:A,removed:V}=this.syncInputMaps(i);a.push(...w),l.push(...A),p.push(...V);const{updated:N,added:j,removed:k}=this.syncTerminationStatements(i);a.push(...N),l.push(...j),p.push(...k);const{updated:S,added:W,removed:ne}=this.syncBodyArgumentsDeclarations(i);a.push(...S),l.push(...W),p.push(...ne);const{updated:re,added:pe,removed:se}=this.syncBodyInputIndexes(i);a.push(...re),l.push(...pe),p.push(...se);const{updated:he,added:X,removed:z}=this.syncOutputsDeclarations(i);a.push(...he),l.push(...X),p.push(...z);const{updated:ce,added:H,removed:de}=this.syncOutputMaps(i);return a.push(...ce),l.push(...H),p.push(...de),i==null||i.attemptAutoclose("sync-children",this.id),{self:this,updated:R(a),added:R(l),removed:R(p),affected:R(t)}}getUnusedInputs(){return this.inputs.filter(i=>i.suggestion||!i.readsValue&&!i.defaultValue)}getUnusedOutputs(){return this.outputs.filter(i=>i.suggestion||!i.writesValues.length)}getUsedInputs(){return this.inputs.filter(i=>!i.suggestion&&(i.readsValue||i.defaultValue))}getUsedOutputs(){return this.outputs.filter(i=>!i.suggestion&&i.writesValues.length)}};D(ze,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(ze,"type",f.Loop),D(ze,"USER_MANAGED_PARENT_TYPES",[...wr,f.Project]),D(ze,"PARENT_TYPES",[...dt.USER_MANAGED_PARENT_TYPES]),D(ze,"CURRENT_ITERATION_NUMBER_ARG_NAME","Current iteration number"),D(ze,"CURRENT_VALUE_ARG_NAME","Current value"),D(ze,"MUTABLE_BASE_PROPERTIES",[]),D(ze,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),D(ze,"BASE_PROPERTIES",[...ze.MUTABLE_BASE_PROPERTIES,...ze.INMUTABLE_BASE_PROPERTIES]),D(ze,"MUTABLE_META_PROPERTIES",[...ze.MUTABLE_BASE_PROPERTIES,"x","y"]),D(ze,"INMUTABLE_META_PROPERTIES",[...ze.INMUTABLE_BASE_PROPERTIES]),D(ze,"META_PROPERTIES",[...ze.MUTABLE_META_PROPERTIES,...ze.INMUTABLE_META_PROPERTIES]),D(ze,"MUTABLE_UPSTREAM_PROPERTIES",["calledBySuccess","calledByError","calledByEntry"]),D(ze,"INMUTABLE_UPSTREAM_PROPERTIES",["parent","declaration"]),D(ze,"UPSTREAM_PROPERTIES",[...ze.MUTABLE_UPSTREAM_PROPERTIES,...ze.INMUTABLE_UPSTREAM_PROPERTIES]),D(ze,"MUTABLE_DOWNSTREAM_PROPERTIES",["body","inputs","outputs","outputsDeclarations","successCalls","errorCalls","error","breakStatements","continueStatements"]),D(ze,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(ze,"DOWNSTREAM_PROPERTIES",[...ze.MUTABLE_DOWNSTREAM_PROPERTIES,...ze.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(ze,"PROPERTIES",[...ze.META_PROPERTIES,...ze.UPSTREAM_PROPERTIES,...ze.DOWNSTREAM_PROPERTIES]);let bi=ze;function s3(d){const u=_ue(),i=d.toJSON();u.safeParse(i).success,d.inputs.forEach(t=>t.validate());const p=[...ya(d)];return Qt(d.errors,p)}const Dhe=Object.freeze(Object.defineProperty({__proto__:null,validate:s3},Symbol.toStringTag,{value:"Module"}));var n3=(d=>(d.Parent="parent",d))(n3||{});const Mt=class Mt extends mr{constructor(i,a){super(i);D(this,"initialData");D(this,"id");D(this,"x");D(this,"y");D(this,"type",f.Condition);D(this,"successCalls",[]);D(this,"errorCalls",[]);D(this,"declaration");D(this,"inputs",[]);D(this,"calledBySuccess",[]);D(this,"calledByError",[]);D(this,"calledByEntry",[]);D(this,"project");D(this,"errors",[]);D(this,"parent");D(this,"detachedDependents",{});D(this,"knownVersions",null);D(this,"activeVersion",!1);D(this,"initialized",!1);D(this,"startedInitialization",!1);this.initialData=i,this.project=a,this.id=i.id,this.x=i.x,this.y=i.y}static new(i=null){return{id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:(i==null?void 0:i.author)||P.sessionAuthor,previousVersion:null,deleted:!1,type:f.Condition,declaration:null,inputs:[],parent:null,calledByEntry:[],calledBySuccess:[],calledByError:[],errorCalls:[],successCalls:[],x:0,y:0}}static fromGenerationTarget(i,a){let l=a;if(i.parent){const A=J(i.parent);l=a.get(A)}const p=i.calledByEntry.map(A=>{const V=J(A);return a.get(V)}),t=i.calledBySuccess.map(A=>{const V=J(A);return a.get(V)}),y=i.calledByError.map(A=>{const V=J(A);return a.get(V)});let v;if(i.declaration){const A=J(i.declaration);v=a.get(A)}const T={id:i.id,version:P.UUID.uuid(),createdAt:L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.Condition,declaration:v,calledByEntry:p,calledBySuccess:t,calledByError:y,errorCalls:[],successCalls:[],inputs:[],x:0,y:0,parent:l},w=te(T,a);return w.setParent(l,null),w}static validateGenerationTarget(i,a){let l=JSON.parse(JSON.stringify(i));const p=[],t=Gr(l,{parent:{list:!1,types:[...wr,f.Project],optional:!0}},a);return l=t.modifiedData,p.push(...t.errors,...br(l)),i.declaration?a.get(i.declaration)?a.conditionDeclarations.find(T=>T.id===i.declaration)||p.push(new ee({id:`${i.id}--${q.InvalidImplementsReference}`,code:q.InvalidImplementsReference,severity:Z.Error,message:`Entity of type '${i.type}' with id '${i.id}' has an 'declaration' property that isn't pointing to an action descriptor reserved for '${f.Condition}' entities.
|
|
103
103
|
${Gy(a)}`,issue:null})):p.push(new ee({id:`${i.id}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type '${i.type}' with id '${i.id}' has an 'declaration' property that isn't found in the project. The 'declaration' property must point to one of the built-in action descriptors reserved for '${f.Condition}' entities.
|
|
104
104
|
${Gy(a)}`,issue:null})):p.push(new ee({id:`${i.id}--${ae.InvalidObjectStructure}`,code:ae.InvalidObjectStructure,severity:Z.Error,message:`Entity of type '${i.type}' with id '${i.id}' is missing the 'declaration' property. This property is required for a '${i.type}' entity and must point to one of the built-in action descriptors reserved for '${f.Condition}' entities.
|
|
105
105
|
${Gy(a)}`,issue:null})),{errors:p,modifiedData:l}}validateGeneratedUpdate(i){const a=[];return i.parent&&a.push(new ee({id:`${this.id}--${q.InvalidParentUpdate}`,code:q.InvalidParentUpdate,severity:Z.Error,message:`Entity of type '${this.type}' with id '${this.id}' cannot have the 'parent' property updated. The 'parent' on a callable entity, is its scope. It scope is auto-calculated implicitly by the its caller.
|
|
@@ -200,7 +200,7 @@ You can't modify system entities that are built-in.`,issue:null})),y&&y.type===f
|
|
|
200
200
|
An action descriptor can only have one error value descriptor child.
|
|
201
201
|
Either remove the existing error value descriptor or update it with the 'update' action.
|
|
202
202
|
You can use the 'describe_entity' action to get more information about the existing error value descriptor like so:
|
|
203
|
-
${On({describe_entity:y.error.id})}`,issue:null}))),{errors:p,modifiedData:l}}validateGeneratedUpdate(i){return{errors:[],modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){var i,a,l;return(l=(a=(i=this.dataType)==null?void 0:i.entity)==null?void 0:a.unsubscribeDependents)==null||l.call(a,[{entity:this,field:"data-type-entity"}]),this}subscribeToDependencies(){var i,a,l;return(l=(a=(i=this.dataType)==null?void 0:i.entity)==null?void 0:a.subscribeDependents)==null||l.call(a,[{entity:this,field:"data-type-entity"}]),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new Pt(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.defaultValue=this.defaultValue,i.dataType=this.dataType,i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new Pt(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.defaultValue=y.defaultValue,this.dataType=y.dataType,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&(this.removeFromParent(a),this.parent=null),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);return this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);return{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];return this.initialized=!0,this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){var y,v,T,w,A,V,N,j;const a=[this],l=[],p=[],t=[];return this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument?((y=this.parent)==null?void 0:y.type)===f.Search||((v=this.parent)==null?void 0:v.type)===f.Loop?(this.parent.addInputDeclaration(this,i),t.push(this.parent)):((w=(T=this.parent)==null?void 0:T.addInput)==null||w.call(T,this,i),a.push(this.parent)):this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((A=this.parent)==null?void 0:A.type)===f.Search||((V=this.parent)==null?void 0:V.type)===f.Loop?(this.parent.addOutputDeclaration(this,i),t.push(this.parent)):((j=(N=this.parent)==null?void 0:N.addOutput)==null||j.call(N,this,i),a.push(this.parent)):this.parentRelationType===le.ReturnedError&&this.parent&&(this.parent.error=this,t.push(this.parent)),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.initialData.defaultValue&&(this.defaultValue=te(this.initialData.defaultValue,this.project),this.defaultValue.setParent(this,null),this.defaultValue.initChildren(i)),this.initialData.dataType&&(this.dataType=te(this.initialData.dataType,this.project),this.dataType.setParent(this,null),this.dataType.initChildren(i)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.name=i.name!==void 0?i.name:p.name,this.codeName=i.codeName!==void 0?i.codeName:p.codeName,this.description=i.description!==void 0?i.description:p.description,this.index=i.index||(i.index!==0?p.index:0),this.required=i.required!==void 0?i.required:this.required,this.parentRelationType=i.parentRelationType!==void 0?i.parentRelationType:this.parentRelationType,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await Pt.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await Pt.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await Pt.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await Pt.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await Pt.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await Pt.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){var y,v,T,w,A,V,N;const a=[],l=[],p=[],t=[];return this.parent&&(((y=this.parent)==null?void 0:y.type)===f.Search?this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((v=this.parent)==null||v.removeOutputDeclaration(this,i),t.push(this.parent)):this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument?((T=this.parent)==null||T.removeInputDeclaration(this,i),t.push(this.parent)):this.parentRelationType===le.ReturnedError&&(this.parent.error=null,t.push(this.parent)):((w=this.parent)==null?void 0:w.type)===f.Loop?this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((A=this.parent)==null||A.removeOutputDeclaration(this,i),t.push(this.parent)):this.parentRelationType===le.ReturnedError&&(this.parent.error=null,t.push(this.parent)):this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((V=this.parent)==null||V.removeOutput(this,i),t.push(this.parent)):(this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument)&&((N=this.parent)==null||N.removeInput(this,i),t.push(this.parent))),i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){const l=[],p=[],t=[],y=[];if(Array.from(new Set([...Vs(),...this.project.getAllBuiltInIds()])).includes(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(T=>{const{updated:w,removed:A,added:V}=T.entity.onDetachedDependencyRemoved(this,T.field,a);l.push(...w),p.push(...A),t.push(...V)}),this.defaultValue){const{updated:T,removed:w}=this.defaultValue.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(this.dataType){const{updated:T,removed:w}=this.dataType.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(!i){const T=this.removeFromParent(a);t.push(...T.added),l.push(...T.updated),p.push(...T.removed),y.push(...T.affected)}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){var y,v,T,w,A,V,N;const a=[],l=[],p=[],t=[];if(i!=null&&i.hasAdded(this.id))return i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(j=>{const{updated:k,removed:S,added:W}=j.entity.onDetachedDependencyRestored(this,j.field,i);l.push(...k),p.push(...S),a.push(...W)}),this.defaultValue){const{updated:j}=this.defaultValue.restore({},i);l.push(...j)}if(this.dataType){const{updated:j}=this.dataType.restore({},i);l.push(...j)}return((y=this.parent)==null?void 0:y.type)===f.Search?this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?(v=this.parent)==null||v.addOutputDeclaration(this,i):(this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument)&&((T=this.parent)==null||T.addInputDeclaration(this,i)):((w=this.parent)==null?void 0:w.type)===f.Loop?(this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn)&&((A=this.parent)==null||A.addOutputDeclaration(this,i)):this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?(V=this.parent)==null||V.addOutput(this,i):(this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument)&&((N=this.parent)==null||N.addInput(this,i)),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this}}toFlat(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this,...((l=this.defaultValue)==null?void 0:l.toFlat(i))||[],...this.dataType?this.dataType.toFlat(i):[]])}toFlatIds(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.id,...((l=this.defaultValue)==null?void 0:l.toFlatIds(i))||[],...this.dataType?this.dataType.toFlatIds(i):[]])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,codeName:this.codeName,description:this.description,index:this.index,required:this.required,parentRelationType:this.parentRelationType,type:this.type,name:this.name}}toJSON(i=new Set){var a,l,p;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,codeName:this.codeName,description:this.description,index:this.index,required:this.required,defaultValue:((a=this.defaultValue)==null?void 0:a.toJSON(i))||null,parentRelationType:this.parentRelationType,dataType:((l=this.dataType)==null?void 0:l.toJSON(i))||null,parent:((p=this.parent)==null?void 0:p.toReference())||null})}toJSONClone(i=Le){var l,p,t,y,v,T,w,A;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:this.type,name:this.name,codeName:this.codeName,description:this.description,index:this.index,required:this.required,defaultValue:((T=this.defaultValue)==null?void 0:T.toJSONClone({...i,newId:null}))||null,parentRelationType:this.parentRelationType,dataType:((w=this.dataType)==null?void 0:w.toJSONClone({...i,newId:null}))||null,parent:((A=this.parent)==null?void 0:A.toReference({seenEntityMaps:i.seenEntityMaps}))||null})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l,p,t,y;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,codeName:this.codeName,description:this.description,index:this.index,required:this.required,parentRelationType:this.parentRelationType,defaultValue:((p=this.defaultValue)==null?void 0:p.toReference(i))||null,dataType:((t=this.dataType)==null?void 0:t.toReference(i))||null,parent:((y=this.parent)==null?void 0:y.toReference(i))||null}}toFlatJSON(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...((l=this.defaultValue)==null?void 0:l.toFlatJSON(i))||[],...this.dataType?this.dataType.toFlatJSON(i):[]])}toGenerationTarget(){var i;return{id:this.id,name:this.name,codeName:this.codeName,description:this.description,type:this.type,required:this.required,parentRelationType:this.parentRelationType,parent:(i=this.parent)==null?void 0:i.id}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.defaultValue?this.defaultValue.toFlatGenerationTarget(i):[],...this.dataType?this.dataType.toFlatGenerationTarget(i):[]])}clearErrors(){var i,a;return this.errors=[],(i=this.defaultValue)==null||i.clearErrors(),(a=this.dataType)==null||a.clearErrors(),this}validate(){const i=Lx(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.dataType?this.dataType.getErrors():[]]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var N,j;if(Array.from(new Set([...Vs(),...this.project.getAllBuiltInIds()])).includes(this.id))return this;let y=gr(a,this);const v=l||P.UUID.uuid(),T=this.toJSON();T.id=v,T.version=P.UUID.uuid(),T.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),T.author=(i==null?void 0:i.author)||"1",T.previousVersion=null,T.deleted=!1;const w=St(T,y);a&&w.setParent(a,null),i==null||i.add(w,K.Added),p&&w.subscribe();const A=((N=this.dataType)==null?void 0:N.clone(i,w,P.UUID.uuid(),p))||null;A&&w.setDataType(A,i);const V=(j=this.defaultValue)==null?void 0:j.clone(i,w,P.UUID.uuid(),p);return w.defaultValue=V||null,i==null||i.attemptAutoclose("clone-entity",this.id),w}getDataType(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"get-data-type"))){return i==null||i.attemptAutoclose("get-data-type",this.id),this.dataType||null}setDataType(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-data-type"))){const l=this.dataType;return(l==null?void 0:l.id)!==(i==null?void 0:i.id)&&(l==null||l.remove({ignoreUpstream:!0},a),this.dataType=i,this.subscribeToDependencies(),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("set-data-type",this.id),this}getDefaultValue(){return this.defaultValue||null}setDefaultValue(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-default-value"))){const l=this.defaultValue;return(l==null?void 0:l.id)!==(i==null?void 0:i.id)&&(l==null||l.remove({ignoreUpstream:!0},a),this.defaultValue=i,a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("set-default-value",this.id),this}removeDataType(){return this.dataType=null,this}implementAsReturnDeclaration(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"implement-as-return-declaration")),a,l){const p=Ni.new(i);p.id=l||p.id,p.name=this.name,p.description=this.description,p.parent=a.toReference(),p.implements=this.toJSON(),p.isError=this.parentRelationType===le.ReturnedError;const t=St(p,this.project);if(t.hydrateAncestors(),t.addSelfToProject(i),i==null||i.add(t,K.Added),t.initChildren(i),this.dataType){const y=this.dataType.clone(i,t);t.setDataType(y,i)}if(this.defaultValue){const y=this.defaultValue.clone(i,t);t.setDefaultValue(y,i)}return i==null||i.attemptAutoclose("implement-as-return-declaration",this.id),t}implementAsArgumentDeclaration(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"implement-as-return-declaration")),a,l){const p=fa.new(i);p.id=l||p.id,p.name=this.name,p.description=this.description,p.parent=a.toReference(),p.implements=this.toJSON();const t=St(p,this.project);if(t.hydrateAncestors(),t.addSelfToProject(i),i==null||i.add(t,K.Added),t.initChildren(i),this.dataType){const y=this.dataType.clone(i,t);t.setDataType(y,i)}if(this.defaultValue){const y=this.defaultValue.clone(i,t);t.setDefaultValue(y,i)}return i==null||i.attemptAutoclose("implement-as-return-declaration",this.id),t}};D(Pt,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(Pt,"type",f.ValueDescriptor),D(Pt,"USER_MANAGED_PARENT_TYPES",[f.ActionDescriptor,f.Loop,f.Search]),D(Pt,"PARENT_TYPES",[...Pt.USER_MANAGED_PARENT_TYPES]),D(Pt,"MUTABLE_BASE_PROPERTIES",["name","codeName","description","required"]),D(Pt,"INMUTABLE_BASE_PROPERTIES",["id","version","type","parentRelationType","createdAt","author","previousVersion"]),D(Pt,"BASE_PROPERTIES",[...Pt.MUTABLE_BASE_PROPERTIES,...Pt.INMUTABLE_BASE_PROPERTIES]),D(Pt,"MUTABLE_META_PROPERTIES",[...Pt.MUTABLE_BASE_PROPERTIES,"index"]),D(Pt,"INMUTABLE_META_PROPERTIES",[...Pt.INMUTABLE_BASE_PROPERTIES]),D(Pt,"META_PROPERTIES",[...Pt.MUTABLE_META_PROPERTIES,...Pt.INMUTABLE_META_PROPERTIES]),D(Pt,"MUTABLE_UPSTREAM_PROPERTIES",[]),D(Pt,"INMUTABLE_UPSTREAM_PROPERTIES",["parent"]),D(Pt,"UPSTREAM_PROPERTIES",[...Pt.MUTABLE_UPSTREAM_PROPERTIES,...Pt.INMUTABLE_UPSTREAM_PROPERTIES]),D(Pt,"MUTABLE_DOWNSTREAM_PROPERTIES",["dataType","defaultValue"]),D(Pt,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(Pt,"DOWNSTREAM_PROPERTIES",[...Pt.MUTABLE_DOWNSTREAM_PROPERTIES,...Pt.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(Pt,"PROPERTIES",[...Pt.META_PROPERTIES,...Pt.UPSTREAM_PROPERTIES,...Pt.DOWNSTREAM_PROPERTIES]);let Qs=Pt;var be=(d=>(d.Inherited="inherited",d.DefaultValue="default-value",d.Missing="missing",d.Empty="empty",d.AutoCalculated="auto-calculated",d.QueuedAutocalculation="queued-autocalculation",d.External="external",d.Testing="testing",d.ExecutionResult="execution-result",d))(be||{});const Mx={initialized:!1,id:"",project:null,values:{},onWriteCallback:()=>{},onRemoveCallback:()=>{},onWrite:()=>{},onRemove:()=>{},init:()=>{},toJSON:()=>({}),writeValue:()=>{},readValue:()=>null,removeValue:()=>{},clear:()=>{}};function Vme(d,u){return{...Mx,id:d,project:u}}class Ap{constructor(u,i){D(this,"initialized",!1);D(this,"id");D(this,"project");D(this,"values",{});D(this,"onWriteCallback",()=>{});D(this,"onRemoveCallback",()=>{});this.id=u,this.project=i,this.init()}onWrite(u){this.onWriteCallback=u}onRemove(u){this.onRemoveCallback=u}init(){if(!this.project.id||this.initialized)return;const u={},i={};Object.keys(u).forEach(a=>{const l=u[a],p=new Ti(l,this.project);try{if(l.parent){const v=this.project.findSubscribedInstanceFromReference(l.parent);if(!v)return;p.setParent(v,null),p.hydrateAncestors(),p.initChildren(null)}else if(l.standaloneParent){const v=this.project.findSubscribedInstanceFromReference(l.standaloneParent);if(!v)return;p.standalone=!0,p.setStandaloneParent(v),p.hydrateAncestors(),p.initChildren(null)}i[a]=p;const t=p.parent||p.standaloneParent,y=jx(p,t,this.project);y?i[a]=y:delete u[a]}catch(t){console.error("Error hydrating ancestors: ",t),delete u[a]}}),this.values={...this.values,...i},this.initialized=!0}toJSON(){const u={};return Object.keys(this.values).forEach(i=>{u[i]=this.values[i].toJSON()}),u}writeValue(u,i){if(!u)throw new Error("The value owner entity is required when writing a value to a value store");let l=this.values[u.id];if(!l)if(i instanceof Ti)l=i;else if(i)l=St(i,this.project);else{const p={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:null,type:f.LiteralValue,standaloneParent:u.toReference(),parent:null,valueAsTypeSingle:null,valueAsTypeList:null,autogeneration:null,name:Ho(u.getDataType(null))};l=St(p,this.project)}l.standalone=!0,l.initialData.standaloneParent||console.warn("instance.initialData: ",l.initialData),l.setStandaloneParent(u),l.hydrateAncestors(),l.initChildren(null),i&&(l.metaSync({...i},null),l.setValueAsType(i.valueAsType,null)),this.values[u.id]=l,this.onWriteCallback(u,l)}readValue(u){return this.values[u]||null}removeValue(u){if(!this.values[u])return;delete this.values[u];const i=this.project.get(u);i&&this.onRemoveCallback(i)}clear(){this.values={}}}function zo(d){var u;return!!(d.required||(u=d.declaration)!=null&&u.required)}function Ux(d){return IM(d)||d===void 0||d===""}function Sb(d){return d?d.valueAsType?!1:Ux(d.value):!0}function en(d,u,i,a){var y;let l;if(((y=d==null?void 0:d.entity)==null?void 0:y.type)===f.PrimitiveEntity)switch(d.entity.name){case Q.EntityTemplate:l=Q.EntityTemplate;break;case Q.String:l=Q.String;break;case Q.Number:l=Q.Number;break;case Q.Boolean:l=Q.Boolean;break;case Q.Null:l=Q.Null;break;case Q.Enum:l=Q.Enum;break;case Q.KeyValue:l=Q.KeyValue;break;case Q.Untyped:l=Q.Untyped;break;case Q.KeyValue:l=Q.KeyValue;break;case Q.Date:l=Q.Date;break;case Q.UUID:l=Q.UUID;break;case Q.File:l=Q.File;break;default:throw new Error(`Primitive type ${ie(d.entity,i)} is not supported`)}else l=Q.Untyped;const p=Ti.new();p.name=l,p.parent=u.toReference();const t=te(p,i);return t.hydrateAncestors(),a==null||a.add(t,K.Added),t.addSelfToProject(a),t.initChildren(a),t}function tn(d,u,i=new Set){var a,l;if(i.has(d.id))return[];if(i.add(d.id),d.type===f.ReturnDeclaration){const p=[d,...d.getCounterparts()];return console.log("Resolved counterparts for return declaration: ",`${d.name} ${d.id}`),console.log("equivalentReturnDeclarations: ",p.map(t=>`${t.name} ${t.id}`)),R([...p,...p.flatMap(t=>tn(t,u,i))])}else if(st.includes(d.type)){const p=di(d);return R([p,...[p].flatMap(t=>tn(t,u,i))])}else if(d.type===f.OutputMap){if(st.includes(d.parent.type)&&d.declaration.type===f.Property&&d.declaration.static)return R([d,d.declaration,...[d,d.declaration].flatMap(p=>tn(p,u,i))])}else if(d.type===f.InputMap&&st.includes(d.parent.type)&&((a=d.declaration)==null?void 0:a.type)===f.Property&&(l=d.declaration)!=null&&l.static)return R([d.declaration,...[d.declaration].flatMap(p=>tn(p,u,i))]);return[d]}function jx(d,u,i){return d}function Dd(d,u){const i=d.readsValue;let a=null;if((i==null?void 0:i.type)===f.VariableDeclaration){const p=wp(i,u);if(p&&p.value){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}else if((i==null?void 0:i.type)===f.VariableInstance){const p=Dy(i,u);if(p&&p.value){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}else if((i==null?void 0:i.type)===f.OutputMap){const p=Wb(i,u);if(p&&p.value){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}else if((i==null?void 0:i.type)===f.ArgumentDeclaration){const p=Zb(i,u);if(p){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}return a}function We(d,u,i){var y;if(!u)return null;let a;if(((y=d==null?void 0:d.entity)==null?void 0:y.type)===f.PrimitiveEntity)switch(d.entity.name){case Q.EntityTemplate:a=Q.EntityTemplate;break;case Q.String:a=Q.String;break;case Q.Number:a=Q.Number;break;case Q.Boolean:a=Q.Boolean;break;case Q.Null:a=Q.Null;break;case Q.Enum:a=Q.Enum;break;case Q.KeyValue:a=Q.KeyValue;break;case Q.Untyped:a=Q.Untyped;break;case Q.KeyValue:a=Q.KeyValue;break;case Q.Date:a=Q.Date;break;case Q.UUID:a=Q.UUID;break;case Q.File:a=Q.File;break;default:throw new Error(`Primitive type ${ie(d.entity,i)} is not supported`)}else a=Q.Untyped;if(!i.get(u.id))return null;const p=Ti.new();p.name=a,p.standaloneParent=u.toReference();let t=new Ti(p,i);return t.hydrateAncestors(),t.standalone=!0,t.setStandaloneParent(u),t.initChildren(null),t}function _y(d,u,i){var p;const a={...d},l=u.inputs;if(!l)return a;for(const t of l){if(!xp(t))continue;const y=Yb(t,i);if(y&&y.value){const v=ie(t,i.project),T=Tr(v);a[T]=(p=y==null?void 0:y.value)==null?void 0:p.value}}return a}function Ip(d,u,i){var p;const a={...d},l=u.inputs;if(!l)return a;for(const t of l){if(!xp(t))continue;const y=Hb(t,i);if(y&&y.value){const v=ie(t,i.project),T=Tr(v);a[T]=(p=y==null?void 0:y.value)==null?void 0:p.value}}return a}function xx(d,u){var y,v,T,w,A,V,N;let i={};if(((v=(y=d.dataType)==null?void 0:y.entity)==null?void 0:v.type)===f.DefinitionEntity&&(i={...i,...d.dataType.entity.getActiveRawDefaultValue()},d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("initialDefaultValue",i)),u.execution&&u.execution.hasEntity(d)){const j=(T=u.lastExecutionResults)==null?void 0:T.readValue(d.id);if(j){if(ar(j.value)){const S={...i,...j.value},W={...Ip(S,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("1- newRawValue",W),j.metaSync({value:W},null)}return{value:j,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}}const a=!!((w=u.execution)!=null&&w.entities.length),l=(A=u.execution)==null?void 0:A.hasEntity(d),p=d.readsValue;let t=null;if(p){const j=(V=u.execution)==null?void 0:V.hasEntity(p);if((!a||a&&j&&l||a&&!j&&!l)&&(t=Dd(d,u),t&&t.value&&ar(t.value.value))){const S={...i,...t.value.value},W={...Ip(S,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("2- newRawValue",W),t.value.metaSync({value:W},null)}}if(!t&&d.defaultValue){const j=d.defaultValue;if(j.value===null&&j.autogeneration){const k=bh(j);if(j.metaSync({value:k},null),ar(k)){const S={...Ip(k,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("3- newRawValue",S),j.metaSync({value:S},null)}}t={value:j,valueOwner:d,type:j.value===null?be.Empty:be.DefaultValue,inheritanceLink:null}}if(!t||t.type===be.DefaultValue){const j=(N=u.localTestValues)==null?void 0:N.readValue(d.id);if(j){if(ar(j.value)){const k={...i,...j.value},S={...Ip(k,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("4- newRawValue",S),j.metaSync({value:S},null)}return{value:j,valueOwner:d,type:be.Testing,inheritanceLink:null}}}return t||{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}}function Fx(d,u){var l,p,t,y,v;let i={};if(((p=(l=d.dataType)==null?void 0:l.entity)==null?void 0:p.type)===f.DefinitionEntity&&(i={...i,...d.dataType.entity.getActiveRawDefaultValue()},d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("initialDefaultValue",i)),u.execution&&u.execution.hasEntity(d)){const T=(t=u.lastExecutionResults)==null?void 0:t.readValue(d.id);if(T){if(ar(T.value)){const A={...i,...T.value};T==null||T.metaSync({value:{..._y(A,d,u)}},null)}return{value:T,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}}const a=(y=u.localTestValues)==null?void 0:y.readValue(d.id);if(d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("testValue",a),a){if(ar(a.value)){const w={...i,...a.value};a.metaSync({value:{..._y(w,d,u)}},null)}return{value:a,valueOwner:d,type:be.Testing,inheritanceLink:null}}if((v=d.dataType)!=null&&v.entity&&d.dataType.entity.type===f.DefinitionEntity&&d.dataType.isObject()){const T=We(d.dataType,d,u.project);return T==null||T.metaSync({value:_y(i,d,u)},null),{value:T,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}}return null}function wp(d,u){var y,v,T,w,A,V;if((y=d.dataType)!=null&&y.isObject())return d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("Is object: ",d),xx(d,u);const i=rr(d),a=!!((v=u.execution)!=null&&v.entities.length),l=(T=u.execution)==null?void 0:T.hasEntity(i),p=d.readsValue;let t=null;if(p){const N=(w=u.execution)==null?void 0:w.hasEntity(p);(!a||a&&N&&l||a&&!N&&!l)&&(t=Dd(d,u))}if(!t&&d.defaultValue){const N=d.defaultValue;if(N.value===null&&N.autogeneration){const j=bh(N);N.metaSync({value:j},null)}t={value:N,valueOwner:d,type:N.value===null?be.Empty:be.DefaultValue,inheritanceLink:null}}return(!t||t.type===be.DefaultValue)&&(A=u.localTestValues)!=null&&A.values[d.id]?{value:(V=u.localTestValues)==null?void 0:V.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null}:t||{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}}function qb(d,u){var a,l,p,t;if(d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("resolveVarDeclarationValue",d),(a=d.dataType)!=null&&a.isObject())return d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("current value is object"),Fx(d,u);if(u.execution&&u.execution.hasEntity(d)){const y=(l=u.lastExecutionResults)==null?void 0:l.readValue(d.id);if(y)return{value:y,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=(p=u.localTestValues)==null?void 0:p.readValue(d.id);if(i)return{value:i,valueOwner:d,type:be.Testing,inheritanceLink:null};if((t=d.dataType)!=null&&t.entity&&d.dataType.entity.type===f.DefinitionEntity&&d.dataType.isObject()){const y=We(d.dataType,d,u.project),v=d.dataType.entity.getActiveRawDefaultValue();return d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("resolvedRawValue",v),y==null||y.metaSync({value:v},null),{value:y,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}}return null}function Dy(d,u){var T,w,A,V,N;d.id==="e749df9b-6b68-4baf-a3c5-59ca15c2492f"&&console.log("resolveVarInstanceNextValue");const i=!!((T=u.execution)!=null&&T.entities.length),a=(w=u.execution)==null?void 0:w.hasEntity(d);let l=null;const p=d.readsValue;if(p){const j=(A=u.execution)==null?void 0:A.hasEntity(p);(!i||i&&j&&a||i&&!j&&!a)&&(l=Dd(d,u))}const t=d.declaration;if(!l&&t){d.id==="e749df9b-6b68-4baf-a3c5-59ca15c2492f"&&console.log("resolveVarInstanceNextValue resolveVarDeclarationNextValue");const j=wp(t,u);j&&j.value&&(l=j)}if((!l||l.type===be.DefaultValue)&&(V=u.localTestValues)!=null&&V.values[d.id])return{value:(N=u.localTestValues)==null?void 0:N.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const y=zo(d);return y&&a&&!l?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:a&&!y&&!l?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:l||{value:null,valueOwner:d,type:be.External,inheritanceLink:null}}function Gx(d,u){return qb(d.declaration,u)}function Zb(d,u){var v,T,w,A,V;if(u.execution&&u.execution.hasEntity(d)){const N=(v=u.lastExecutionResults)==null?void 0:v.readValue(d.id);if(N)return{value:N,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=rr(d),a=d.parent.type===f.FunctionDeclaration&&d.parent.parent.type===f.Loop?d.parent:null,l=!!((T=u.execution)!=null&&T.hasEntity(i))||!!a&&!!((w=u.execution)!=null&&w.hasEntity(a));let p=null;if(d.defaultValue){const N=d.defaultValue;if(N.value===null&&N.autogeneration){const j=bh(N);N.metaSync({value:j},null)}p={value:N,valueOwner:d,type:N.value===null?be.Empty:be.DefaultValue,inheritanceLink:null}}if((!p||p.type===be.DefaultValue)&&(A=u.localTestValues)!=null&&A.values[d.id])return{value:(V=u.localTestValues)==null?void 0:V.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const t=zo(d);let y=t&&l&&!p;return i.type===f.Loop&&l&&(y=!1),y?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:l&&!t&&!p?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:p||{value:null,valueOwner:d,type:be.External,inheritanceLink:null}}function Jb(d,u){var T,w,A,V,N,j;if(u.execution&&u.execution.hasEntity(d)){const k=(T=u.lastExecutionResults)==null?void 0:T.readValue(d.id);if(k)return{value:k,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=rr(d),a=!!((w=u.execution)!=null&&w.entities.length),l=(A=u.execution)==null?void 0:A.hasEntity(i),p=d.readsValue;let t=null;if(p){const k=(V=u.execution)==null?void 0:V.hasEntity(p);(!a||a&&k&&l||a&&!k&&!l)&&(t=Dd(d,u))}if(!t&&d.defaultValue&&(t={value:d.defaultValue,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}),(!t||t.type===be.DefaultValue)&&(N=u.localTestValues)!=null&&N.values[d.id])return{value:(j=u.localTestValues)==null?void 0:j.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const y=zo(d);return y&&!t?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:!y&&!t?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:t}function Wb(d,u){var y,v,T,w,A;if(u.execution&&u.execution.hasEntity(d)){const V=(y=u.lastExecutionResults)==null?void 0:y.readValue(d.id);if(V)return{value:V,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=rr(d);if(st.includes(i.type)){const V=Xo(i,u),N=Tr(ie(d,u.project));if(V!=null&&V.value&&ar(V.value.value)){const j=V.value.value[N],k=We(d.getDataType(null),d,u.project);return k==null||k.metaSync({value:j},null),{value:k,valueOwner:d,type:V.type,inheritanceLink:{sources:[V],target:d}}}return null}const a=(v=u.execution)==null?void 0:v.hasEntity(i),l=((T=u.execution)==null?void 0:T.state)===Xb.Running;if((w=u.persistedExecutionResults)!=null&&w.values[d.id]&&!a&&!l){const V=(A=u.persistedExecutionResults)==null?void 0:A.readValue(d.id);if((V==null?void 0:V.value)!==null||(V==null?void 0:V.valueAsType)!==null)return{value:V,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const p=d.getDefaultValue();if(p&&(p.value!==null||p.valueAsType!==null))return{value:p,valueOwner:d,type:be.DefaultValue,inheritanceLink:null};const t=d.parent;if(!t)throw new Error(`Couldn't find the parent that generates the output ${d.id}`);switch(t.type){case f.VariableInstance:{const N=Dy(t,u);if(N&&N.value){const k=d.declaration;if(ar(N.value.value)){const S=N.value.value[k.name],W=We(d.declaration.dataType,d,u.project);return W==null||W.metaSync({value:S},null),{value:W,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:[N],target:d}}}}const j=We(d.declaration.dataType,d,u.project);return j==null||j.metaSync({value:null},null),{value:j,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:N?[N]:[],target:d}}}case f.VariableDeclaration:{const N=wp(t,u);if(N&&N.value){const k=d.declaration;if(ar(N.value.value)){const S=N.value.value[k.name],W=We(d.declaration.dataType,d,u.project);return W==null||W.metaSync({value:S},null),{value:W,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:[N],target:d}}}}const j=We(d.declaration.dataType,d,u.project);return j==null||j.metaSync({value:null},null),{value:j,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:N?[N]:[],target:d}}}case f.Operation:{const V=t.outputs.map(j=>{var S,W;if((S=u.persistedExecutionResults)!=null&&S.values[j.id]){const ne=(W=u.persistedExecutionResults)==null?void 0:W.values[j.id];if(ne.value!==null||ne.valueAsType!==null)return{value:ne,valueOwner:j,type:be.ExecutionResult,inheritanceLink:null}}const k=j.getDefaultValue();if(k&&(k.value!==null||k.valueAsType!==null))return{value:k,valueOwner:j,type:be.DefaultValue,inheritanceLink:null}}).filter(j=>!!j),N=We(d.declaration.dataType,d,u.project);return N==null||N.metaSync({value:null},null),{value:N,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:V.length?{sources:V,target:d}:null}}case f.FunctionCall:{const V=t.inputs.map(j=>Rp(j,u)).filter(j=>!!j),N=We(d.declaration.dataType,d,u.project);return N==null||N.metaSync({value:null},null),{value:N,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:V.length?{sources:V,target:d}:null}}case f.Loop:{const V=t.inputs.map(j=>Rp(j,u)).filter(j=>!!j),N=We(d.declaration.dataType,d,u.project);return N==null||N.metaSync({value:null},null),{value:N,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:V.length?{sources:V,target:d}:null}}case f.Search:return{value:null,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:null}}return null}function Kx(d,u){var y,v;if(!st.includes(d.parent.type)||!xp(d))return null;if(((y=d.declaration)==null?void 0:y.type)===f.Property&&d.declaration.static)return Xo(d.declaration,u);const i=di(d.parent),a=Oy(i,u),l=Tr(ie(d,u.project)),p=We(d.getDataType(null),d,u.project),t=(v=a==null?void 0:a.value)==null?void 0:v.value;return t&&ar(t)?(p==null||p.metaSync({value:t[l]||null},null),{value:p,valueOwner:d,type:a.type,inheritanceLink:{sources:a?[a]:[],target:d}}):null}function kx(d,u){var y,v;if(!st.includes(d.parent.type)||!xp(d))return null;if(((y=d.declaration)==null?void 0:y.type)===f.Property&&d.declaration.static)return Xo(d.declaration,u);const i=di(d.parent),a=Xo(i,u),l=Tr(ie(d,u.project)),p=We(d.getDataType(null),d,u.project),t=(v=a==null?void 0:a.value)==null?void 0:v.value;return t&&ar(t)?(p==null||p.metaSync({value:t[l]||null},null),{value:p,valueOwner:d,type:a.type,inheritanceLink:{sources:[a],target:d}}):null}function Hb(d,u){var T,w,A,V,N;const i=rr(d),a=!!((T=u.execution)!=null&&T.entities.length),l=(w=u.execution)==null?void 0:w.hasEntity(i),p=d.readsValue;let t=null;if(p){const j=(A=u.execution)==null?void 0:A.hasEntity(p);(!a||a&&j&&l||a&&!j&&!l)&&(t=Dd(d,u))}if(!t&&d.defaultValue){const j=d.defaultValue;j&&(t={value:j,valueOwner:d,type:be.DefaultValue,inheritanceLink:null})}if(!t&&d.declaration){const j=Xo(d.declaration,u);j&&j.value&&(t={...j,valueOwner:d,type:be.DefaultValue})}if((!t||t.type===be.DefaultValue||(t==null?void 0:t.type)===be.Empty)&&(V=u.localTestValues)!=null&&V.values[d.id])return{value:(N=u.localTestValues)==null?void 0:N.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const y=zo(d);return y&&!t||(t==null?void 0:t.type)===be.Empty?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:(t==null?void 0:t.inheritanceLink)||null}:!y&&(!t||t.type===be.Inherited)&&!(t!=null&&t.inheritanceLink)?(d.id==="6589602d-30df-4ef8-8161-fb5c228c9254"&&console.log("Here input-map -- resolved as empty","value: ",t,"isDefinitionRequired: ",y,"!value: ",!t,"value.type: ",t==null?void 0:t.type),{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}):t}function Yb(d,u){var a;if(u.execution&&u.execution.hasEntity(d)){const l=(a=u.lastExecutionResults)==null?void 0:a.readValue(d.id);if(l)return{value:l,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}return Rp(d,u)}function Rp(d,u){var i;return d.id==="6589602d-30df-4ef8-8161-fb5c228c9254"&&console.log("resolveInputMapNextValue"),st.includes(d.parent.type)&&(i=di(d.parent).dataType)!=null&&i.isObject()?Kx(d,u):Hb(d,u)}function Sx(d,u){var i;return st.includes(d.parent.type)&&(i=di(d.parent).dataType)!=null&&i.isObject()?kx(d,u):Yb(d,u)}function qx(d,u){var t,y,v;if(!d.static)return null;if(u.execution){const T=(t=u.lastExecutionResults)==null?void 0:t.readValue(d.id);if(T)return{value:T,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}if((y=u.localTestValues)!=null&&y.values[d.id])return{value:(v=u.localTestValues)==null?void 0:v.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const i=d.getDefaultValue();let a=null;return i&&(a={value:i,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}),zo(d)&&Sb(a==null?void 0:a.value)?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:Sb(a==null?void 0:a.value)?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:a}function Zx(d,u){var t,y,v,T,w,A,V;if(u.execution&&u.execution.hasEntity(d)){const N=(t=u.lastExecutionResults)==null?void 0:t.readValue(d.id);if(N)return{value:N,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}if((y=u.localTestValues)!=null&&y.values[d.id])return{value:(v=u.localTestValues)==null?void 0:v.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const i=d.getDefaultValue();let a=null;return i&&(a={value:i,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}),zo(d)&&!((T=a==null?void 0:a.value)!=null&&T.value)&&!((w=a==null?void 0:a.value)!=null&&w.valueAsType)?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:!((A=a==null?void 0:a.value)!=null&&A.value)&&!((V=a==null?void 0:a.value)!=null&&V.valueAsType)?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:a}function Xo(d,u){switch(d.type){case f.ArgumentDeclaration:return Zb(d,u);case f.InputMap:return Sx(d,u);case f.VariableDeclaration:return qb(d,u);case f.VariableInstance:return Gx(d,u);case f.OutputMap:return Wb(d,u);case f.ReturnDeclaration:return Jb(d,u);case f.Property:return qx(d,u);case f.ValueDescriptor:return Zx(d,u);default:return null}}function Oy(d,u){switch(d.type){case f.InputMap:return Rp(d,u);case f.VariableDeclaration:return wp(d,u);case f.VariableInstance:return Dy(d,u);case f.ReturnDeclaration:return Jb(d,u);default:return null}}function Nme(d){var u;if(d&&d.type===be.DefaultValue&&d.value&&d.valueOwner&&((u=d.valueOwner.defaultValue)==null?void 0:u.id)===d.value.id){const i=We(d.valueOwner.getDataType(null),d.valueOwner,d.valueOwner.project);return{type:be.DefaultValue,value:i,valueOwner:d.valueOwner,inheritanceLink:null}}return d}function Qo(d,u,i,a){let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=d.parent;return u.getVariableDeclarations().forEach(T=>{var A,V,N,j;const w=T.getDataType(null);if(((A=w==null?void 0:w.entity)==null?void 0:A.id)===y.id){let k=l?T.defaultValue:t==null?void 0:t.readValue(T.id);k?!l&&k&&k.id===((V=T.defaultValue)==null?void 0:V.id)&&(k=We(T.getDataType(null),T,u)):l?k=en(T.getDataType(null),T,u,p):k=We(T.getDataType(null),T,u);const S=ie(d,u),W=Tr(S);let ne={};((j=(N=T.dataType)==null?void 0:N.entity)==null?void 0:j.type)===f.DefinitionEntity&&(ne={...ne,...T.dataType.entity.getActiveRawDefaultValue()}),ar(k==null?void 0:k.value)&&(ne={...ne,...k.value}),ne[W]=i,k==null||k.metaSync({value:ne},p),l||t==null||t.writeValue(T,k);return}}),p}function gp(d,u,i,a){var N,j,k;let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=di(d.parent),v=y.getDataType(null);if(!(v!=null&&v.isObject()))return p;let T=l?y.defaultValue:t==null?void 0:t.readValue(y.id);T?!l&&T&&T.id===((N=y.defaultValue)==null?void 0:N.id)&&(T=We(y.getDataType(null),y,u)):l?T=en(y.getDataType(null),y,u,p):T=We(y.getDataType(null),y,u);const w=ie(d,u),A=Tr(w);let V={};if(((k=(j=y.dataType)==null?void 0:j.entity)==null?void 0:k.type)===f.DefinitionEntity&&(V={...V,...y.dataType.entity.getActiveRawDefaultValue()}),ar(T==null?void 0:T.value)&&(V={...V,...T.value}),V[A]=i,T==null||T.metaSync({value:V},p),l||t==null||t.writeValue(y,T),(i===""||i===null||i===void 0)&&d.type===f.OutputMap){const S=y.inputs.find(W=>{var ne;return((ne=W.declaration)==null?void 0:ne.id)===d.declaration.id||ie(W,u)===w});if(S){let W=l?S.defaultValue:t==null?void 0:t.readValue(S.id);W&&W.metaSync({value:null},p),l||t==null||t.removeValue(S.id)}}return p}function Jx(d,u,i){var t,y,v,T;let a=!1,l=null,p=null;if(i instanceof G?(a=!0,l=i,p=null):(l=null,p=i),st.includes(d.type)){const w=di(d);(t=w.dataType)!=null&&t.isObject()&&w.inputs.forEach(A=>{var V,N,j,k;if(((V=A.declaration)==null?void 0:V.type)===f.Property&&A.declaration.static){let S=a?d.defaultValue:p==null?void 0:p.readValue(A.declaration.id);S?!a&&S&&S.id===((N=A.declaration.defaultValue)==null?void 0:N.id)&&(S=We(A.declaration.getDataType(null),A.declaration,u)):a?S=en(A.declaration.getDataType(null),A.declaration,u,l):S=We(A.declaration.getDataType(null),A.declaration,u),S==null||S.metaSync({value:null},l),a||p==null||p.removeValue((j=A.declaration)==null?void 0:j.id)}else if(((k=A.declaration)==null?void 0:k.type)===f.Property){let S=a?d.defaultValue:p==null?void 0:p.readValue(A.id);S&&S.metaSync({value:null},l),a||p==null||p.removeValue(A.id)}})}else d.type===f.InputMap?((y=d.declaration)==null?void 0:y.type)===f.Property&&d.declaration.static?Qo(d.declaration,u,null,i):st.includes(d.parent.type)&&((v=d.declaration)==null?void 0:v.type)===f.Property&&gp(d,u,null,i):d.type===f.OutputMap?((T=d.declaration)==null?void 0:T.type)===f.Property&&d.declaration.static?Qo(d.declaration,u,null,i):st.includes(d.parent.type)&&d.declaration.type===f.Property&&gp(d,u,null,i):d.type===f.Property&&d.static&&Qo(d,u,null,i);return l}function Wx(d,u,i,a){var y,v,T,w,A,V;let l=!1,p=null,t=null;if(a instanceof G?(l=!0,p=a,t=null):(p=null,t=a),st.includes(u.type)){const N=di(u);if((y=N.dataType)!=null&&y.isObject()){let j={};((T=(v=N.dataType)==null?void 0:v.entity)==null?void 0:T.type)===f.DefinitionEntity&&(j={...j,...N.dataType.entity.getActiveRawDefaultValue()});const k=ar(d)?d:j;N.inputs.forEach(S=>{var W,ne,re;if(((W=S.declaration)==null?void 0:W.type)===f.Property&&S.declaration.static){let pe=l?u.defaultValue:t==null?void 0:t.readValue(S.declaration.id);pe?!l&&pe&&pe.id===((ne=S.declaration.defaultValue)==null?void 0:ne.id)&&(pe=We(S.declaration.getDataType(null),S.declaration,i)):l?pe=en(S.declaration.getDataType(null),S.declaration,i,p):pe=We(S.declaration.getDataType(null),S.declaration,i);const se=ie(S,i),he=Tr(se),X=k[he];pe==null||pe.metaSync({value:X},p),l||t==null||t.writeValue(S.declaration,pe)}else if(((re=S.declaration)==null?void 0:re.type)===f.Property){let pe=l?u.defaultValue:t==null?void 0:t.readValue(S.id);pe&&pe.metaSync({value:null},p),l||t==null||t.removeValue(S.id)}})}}else u.type===f.InputMap?((w=u.declaration)==null?void 0:w.type)===f.Property&&u.declaration.static?Qo(u.declaration,i,d,a):st.includes(u.parent.type)&&((A=u.declaration)==null?void 0:A.type)===f.Property&&gp(u,i,d,a):u.type===f.OutputMap?((V=u.declaration)==null?void 0:V.type)===f.Property&&u.declaration.static?Qo(u.declaration,i,null,a):st.includes(u.parent.type)&&u.declaration.type===f.Property&&gp(u,i,null,a):u.type===f.Property&&u.static&&Qo(u,i,d,a);return p}function Hx(d,u,i){const a=tn(d,u);let l=!1,p=null,t=null;return i instanceof G?(l=!0,p=i,t=null):(p=null,t=i),a.forEach(y=>{var T;let v=l?y.defaultValue:t==null?void 0:t.readValue(y.id);v?!l&&v&&v.id===((T=y.defaultValue)==null?void 0:T.id)&&(v=We(d.getDataType(null),d,d.project)):l?v=en(y.getDataType(null),y,u,p):v=We(y.getDataType(null),y,u),v==null||v.metaSync({value:null},p),l||t==null||t.removeValue(y.id),Jx(y,u,i)}),p}function Lme(d,u,i,a){if(d===""||d===null||d===void 0)return Hx(u,i,a);const l=tn(u,i);let p=!1,t=null,y=null;return a instanceof G?(p=!0,t=a,y=null):(t=null,y=a),l.forEach(v=>{var w;let T=p?u.defaultValue:y==null?void 0:y.readValue(u.id);T?!p&&T&&T.id===((w=v.defaultValue)==null?void 0:w.id)&&(T=We(v.getDataType(null),v,i)):p?T=en(v.getDataType(null),v,i,t):T=We(v.getDataType(null),v,i),T==null||T.metaSync({value:d},t),p||y==null||y.writeValue(v,T),Wx(d,v,i,a)}),t}function el(d,u,i,a){let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=d.parent;return u.getVariableDeclarations().forEach(T=>{var A,V,N,j;const w=T.getDataType(null);if(((A=w==null?void 0:w.entity)==null?void 0:A.id)===y.id){let k=l?T.defaultValue:t==null?void 0:t.readValue(T.id);k?!l&&k&&k.id===((V=T.defaultValue)==null?void 0:V.id)&&(k=We(T.getDataType(null),T,u)):l?k=en(T.getDataType(null),T,u,p):k=We(T.getDataType(null),T,u);const S=ie(d,u),W=Tr(S);let ne={};((j=(N=T.dataType)==null?void 0:N.entity)==null?void 0:j.type)===f.DefinitionEntity&&(ne={...ne,...T.dataType.entity.getActiveRawDefaultValue()}),ar(k==null?void 0:k.value)&&(ne={...ne,...k.value}),Array.isArray(i)?ne[W]=(i==null?void 0:i.map(re=>re.toShallowJSON()))||null:ne[W]=(i==null?void 0:i.toShallowJSON())||null,k==null||k.metaSync({value:ne},p),l||t==null||t.writeValue(T,k);return}}),p}function _p(d,u,i,a){var N,j,k;let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=di(d.parent),v=y.getDataType(null);if(!(v!=null&&v.isObject()))return p;let T=l?y.defaultValue:t==null?void 0:t.readValue(y.id);T?!l&&T&&T.id===((N=y.defaultValue)==null?void 0:N.id)&&(T=We(y.getDataType(null),y,u)):l?T=en(y.getDataType(null),y,u,p):T=We(y.getDataType(null),y,u);const w=ie(d,u),A=Tr(w);let V={};if(((k=(j=y.dataType)==null?void 0:j.entity)==null?void 0:k.type)===f.DefinitionEntity&&(V={...V,...y.dataType.entity.getActiveRawDefaultValue()}),ar(T==null?void 0:T.value)&&(V={...V,...T.value}),Array.isArray(i)?V[A]=(i==null?void 0:i.map(S=>S.toShallowJSON()))||null:V[A]=(i==null?void 0:i.toShallowJSON())||null,T==null||T.metaSync({value:V},p),l||t==null||t.writeValue(y,T),i==null&&d.type===f.OutputMap){const S=y.inputs.find(W=>{var ne;return((ne=W.declaration)==null?void 0:ne.id)===d.declaration.id||ie(W,u)===w});if(S){let W=l?S.defaultValue:t==null?void 0:t.readValue(S.id);W&&(Array.isArray(i)?W==null||W.setValueAsTypeList(i,p):W==null||W.setValueAsTypeSingle(i,p)),l||t==null||t.removeValue(S.id)}}return p}function Yx(d,u,i){var a,l,p;return d.type===f.InputMap?((a=d.declaration)==null?void 0:a.type)===f.Property&&d.declaration.static?el(d.declaration,u,null,i):st.includes(d.parent.type)&&((l=d.declaration)==null?void 0:l.type)===f.Property&&_p(d,u,null,i):d.type===f.OutputMap?((p=d.declaration)==null?void 0:p.type)===f.Property&&d.declaration.static?el(d.declaration,u,null,i):st.includes(d.parent.type)&&d.declaration.type===f.Property&&_p(d,u,null,i):d.type===f.Property&&d.static&&el(d,u,null,i),i}function zx(d,u,i,a){var l,p,t;return u.type===f.InputMap?((l=u.declaration)==null?void 0:l.type)===f.Property&&u.declaration.static?el(u.declaration,i,d,a):st.includes(u.parent.type)&&((p=u.declaration)==null?void 0:p.type)===f.Property&&_p(u,i,d,a):u.type===f.OutputMap?((t=u.declaration)==null?void 0:t.type)===f.Property&&u.declaration.static?el(u.declaration,i,null,a):st.includes(u.parent.type)&&u.declaration.type===f.Property&&_p(u,i,null,a):u.type===f.Property&&u.static&&el(u,i,d,a),a}function Xx(d,u,i){const a=tn(d,u);let l=!1,p=null,t=null;return i instanceof G?(l=!0,p=i,t=null):(p=null,t=i),a.forEach(y=>{var T;let v=l?y.defaultValue:t==null?void 0:t.readValue(y.id);v?!l&&v&&v.id===((T=y.defaultValue)==null?void 0:T.id)&&(v=We(y.getDataType(null),y,y.project)):l?v=en(y.getDataType(null),y,u,p):v=We(y.getDataType(null),y,u),v==null||v.setValueAsTypeSingle(null,p),v==null||v.setValueAsTypeList(null,p),l||t==null||t.removeValue(y.id),Yx(y,u,i)}),p}function Bme(d,u,i,a){if(d==null)return Xx(u,i,a);const l=tn(u,i);let p=!1,t=null,y=null;return a instanceof G?(p=!0,t=a,y=null):(t=null,y=a),l.forEach(v=>{var w;let T=p?v.defaultValue:y==null?void 0:y.readValue(v.id);T?!p&&T&&T.id===((w=v.defaultValue)==null?void 0:w.id)&&(T=We(v.getDataType(null),v,v.project)):p?T=en(v.getDataType(null),v,i,t):T=We(v.getDataType(null),v,i),Array.isArray(d)?T==null||T.setValueAsTypeList(d,t):T==null||T.setValueAsTypeSingle(d,t),p||y==null||y.writeValue(v,T),zx(d,v,i,a)}),t}var Mme=Object.defineProperty,Ume=(d,u,i)=>u in d?Mme(d,u,{enumerable:!0,configurable:!0,writable:!0,value:i}):d[u]=i,tl=(d,u,i)=>(Ume(d,typeof u!="symbol"?u+"":u,i),i);let jme=class{constructor(u){tl(this,"eventName"),tl(this,"callbacks",[]),this.eventName=u,this.on=this.on.bind(this),this.off=this.off.bind(this),this.destroy=this.destroy.bind(this)}on(u){if(typeof u!="function")throw new Error("Event callback must be a function");this.callbacks.includes(u)||this.callbacks.push(u)}off(u){if(typeof u!="function")throw new Error("Event callback must be a function");this.callbacks=this.callbacks.filter(i=>i!==u)}destroy(){this.callbacks=[]}},zb=class{constructor(){tl(this,"subscribedEvents",{}),tl(this,"on",this._on),tl(this,"emit",this._emit),tl(this,"off",this._off),tl(this,"destroy",this._destroy),this.getEvent=this.getEvent.bind(this),this._on=this._on.bind(this),this._emit=this._emit.bind(this),this._off=this._off.bind(this),this._destroy=this._destroy.bind(this),this.on=this.on.bind(this),this.emit=this.emit.bind(this),this.off=this.off.bind(this),this.destroy=this.destroy.bind(this)}getEvent(u){return this.subscribedEvents[u]||(this.subscribedEvents[u]=new jme(u)),this.subscribedEvents[u]}_on(u,i){this.getEvent(u).on(i)}_emit(u,...i){const a=this.getEvent(u);a&&a.callbacks.forEach(l=>{l.apply(null,i)})}_off(u,i){const a=this.getEvent(u);a&&(i?a.off(i):(a.destroy(),delete this.subscribedEvents[u]))}_destroy(){Object.keys(this.subscribedEvents).forEach(u=>{this._off(u)}),this.subscribedEvents={}}};const Ja={onBeforeEntityExecution:async()=>{},onEntityExecuted:async()=>{}};var Xb=(d=>(d.FinishedSuccess="finished-success",d.FinishedError="finished-error",d.Running="running",d.Paused="paused",d.Stopped="stopped",d.NotStarted="not-started",d))(Xb||{});const Bi=class Bi extends zb{constructor(i,a,l,p=null){super();D(this,"project");D(this,"entryPoint");D(this,"state","not-started");D(this,"events",new zb);D(this,"entities",[]);D(this,"parentExecution",null);D(this,"executing",[]);D(this,"executed",[]);D(this,"skipped",[]);D(this,"scheduled",[]);D(this,"localTestValues");D(this,"resolvedValues");D(this,"persistedExecutionResults");D(this,"lastExecutionResults");D(this,"onAddToSkippedListCallback",null);D(this,"onRemoveFromSkippedListCallback",null);D(this,"onAddEntityCallback",null);D(this,"onRemoveEntityCallback",null);this.entities=a,this.entryPoint=l,this.project=i,this.parentExecution=p,this.localTestValues=new Ap(P.UUID.uuid(),this.project),this.resolvedValues=new Ap(P.UUID.uuid(),this.project),this.persistedExecutionResults=new Ap(P.UUID.uuid(),this.project),this.lastExecutionResults=new Ap(P.UUID.uuid(),this.project)}get valueResolutionContext(){return{execution:this,project:this.project,localTestValues:this.localTestValues,resolvedValues:this.resolvedValues,persistedExecutionResults:this.persistedExecutionResults,lastExecutionResults:this.lastExecutionResults}}static injectSearchImplementation(i){Bi.searchImplementation=i}skip(i){this.hasEntity(i)&&(this.skipped.includes(i)||(this.skipped.push(i),this.onAddToSkippedListCallback&&this.onAddToSkippedListCallback(i),Rs.includes(i.type)&&[...i.successCalls||[],...i.errorCalls||[],...i.calls||[]].forEach(a=>this.skip(a))))}async schedule(i,a,l){if(this.hasExecuted(i))return null;if(Ht.includes(i.type))return this.executeBranch(i,l,a);if(ws.includes(i.type)){if(i.calledBy.every(t=>this.hasExecuted(t)||!this.hasEntity(t)))return this.executeBranch(i,l,a);this.scheduled.includes(i)||this.scheduled.push(i)}return null}mergeExernalValuesWithInternalInputs(i,a){const l=[];return[...er,...Ht].includes(a.type)?l.push(...a.inputs):nr.includes(a.type)&&l.push(...a.outputs),l.map(t=>{var v;let y=i.find(T=>T.valueOwner.id===t.id);if(y)return y;if(!y&&Ht.includes(a.type)&&(y=i.find(T=>{var w;return((w=T.valueOwner.declaration)==null?void 0:w.id)===t.id})),y){const T=(v=y.value)==null?void 0:v.clone(null);return T==null||T.setStandaloneParent(t),{...y,valueOwner:t,value:T||null,inheritanceLink:{sources:[y],target:t}}}return Wn.includes(t.type)?Oy(t,this.valueResolutionContext):Xo(t,this.valueResolutionContext)}).reduce((t,y)=>{const v=tn(y==null?void 0:y.valueOwner,this.project),T=y?[y]:[];return v.forEach(w=>{var N,j,k;if(w.id===(y==null?void 0:y.valueOwner.id))return;const A=We(w.getDataType(null),w,this.project);A==null||A.metaSync({value:(N=y==null?void 0:y.value)==null?void 0:N.value},null),A==null||A.setValueAsTypeList(((j=y==null?void 0:y.value)==null?void 0:j.valueAsTypeList)||null),A==null||A.setValueAsTypeSingle(((k=y==null?void 0:y.value)==null?void 0:k.valueAsTypeSingle)||null);const V={...y,valueOwner:w,value:A};T.push(V)}),[...t,...T]},[]).sort((t,y)=>t.valueOwner.index-y.valueOwner.index)}inheritValuesFromContext(i){this.localTestValues=i.localTestValues,this.resolvedValues=i.resolvedValues,this.persistedExecutionResults=i.persistedExecutionResults}async executeInternalCall(i,a,l,p={}){var y,v;const t={...Ja,...p};try{let T={value:Ke.Success,error:null,results:[]};if(a.sort((w,A)=>w.valueOwner.index-A.valueOwner.index),Object.values(gi).includes(i.declaration.id)){const w=Bi.builtInFunctionImplementations[i.declaration.id];w?T=await w(i,a):console.warn(`No implementation found for built-in function: ${i.declaration.id}`)}else{console.log("executeFunctionCall",a),T=await this.executeDetachedFullFunctionDeclarationLogic(i.declaration,a,l,t);const w=i.outputs.map(V=>{var W,ne,re,pe;const N=[...V.declaration.getCounterparts(),V.declaration];console.log("declarations",N);const j=T.results.find(se=>N.some(X=>se.valueOwner.id===X.id));console.log("resultValue",j);const k=V==null?void 0:V.getDataType(null),S=We(k,V,l);return k!=null&&k.asType?Array.isArray((W=j==null?void 0:j.value)==null?void 0:W.valueAsType)?S==null||S.setValueAsTypeList((ne=j==null?void 0:j.value)==null?void 0:ne.valueAsTypeList):S==null||S.setValueAsTypeSingle(((re=j==null?void 0:j.value)==null?void 0:re.valueAsType)||null):S==null||S.metaSync({value:(pe=j==null?void 0:j.value)==null?void 0:pe.value},null),{valueOwner:V,type:be.ExecutionResult,inheritanceLink:null,value:S}});let A=null;if(T.error){console.warn("Raw error executing entity: ",T.error);const V=(y=i.error)==null?void 0:y.getDataType(null),N=We(V||null,i.error,l);V!=null&&V.asType?N==null||N.setValueAsTypeSingle(T.error):N==null||N.metaSync({value:T.error},null),A={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:N}}return{value:T.value,entity:i,error:A,results:w}}return{value:Ke.Error,entity:i,error:null,results:[]}}catch(T){console.warn("Operation execution error: ",T);let w=null;if(i.error){const A=(v=i.error)==null?void 0:v.getDataType(null),V=We(A,i.error,l);A!=null&&A.asType?V==null||V.setValueAsTypeSingle(T):V==null||V.metaSync({value:T},null),w={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:V}}return{value:Ke.Error,entity:i,error:w,results:[]}}}static async executeOperation(i,a,l){var p,t;try{let y={value:Ke.Success,error:null,results:[]};a.sort((w,A)=>w.valueOwner.index-A.valueOwner.index),i.declaration.implementation&&(y=await i.declaration.implementation(i,a));const v=i.outputs.map((w,A)=>{const V=w==null?void 0:w.getDataType(null),N=We(V,w,l);return V!=null&&V.asType?N==null||N.setValueAsTypeSingle(y.results[A]):N==null||N.metaSync({value:y.results[A]},null),{valueOwner:w,type:be.ExecutionResult,inheritanceLink:null,value:N}});let T=null;if(y.error&&i.error){console.warn("Raw error executing entity: ",y.error);const w=((p=i.error)==null?void 0:p.getDataType(null))||null,A=We(w,i.error,l);w!=null&&w.asType?A==null||A.setValueAsTypeSingle(y.error):A==null||A.metaSync({value:y.error},null),T={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:A}}return{value:y.value,entity:i,error:T,results:v}}catch(y){console.warn("Operation execution error: ",y);let v=null;if(i.error){const T=(t=i.error)==null?void 0:t.getDataType(null),w=We(T,i.error,l);T!=null&&T.asType?w==null||w.setValueAsTypeSingle(y):w==null||w.metaSync({value:y},null),v={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:w}}return{value:Ke.Error,entity:i,error:v,results:[]}}}async executeSearch(i,a,l){var p;console.log("executeSearch");try{let t={value:Ke.Success,error:null,results:[]};const y=i.outputs[0];if(!y)return{value:Ke.Success,entity:i,error:null,results:[]};let v={value:null,valueOwner:y,type:be.ExecutionResult,inheritanceLink:null};const T=await Bi.searchImplementation(i,a),w=y==null?void 0:y.getDataType(null),A=We(w,y,l);return A==null||A.metaSync({value:T.data},null),v.value=A,{value:t.value,entity:i,error:null,results:[v]}}catch(t){if(console.warn(`Search node execution error: ${t}`),!i.error)return{value:Ke.Error,entity:i,error:null,results:[]};const y=(p=i.error)==null?void 0:p.getDataType(null),v=We(y,i.error,l);return v==null||v.metaSync({value:t},null),{value:Ke.Error,entity:i,error:{valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:v},results:[]}}}async executeLoop(i,a,l,p={}){var y,v;const t={...Ja,...p};try{let T={value:Ke.Success,error:null,results:[]};const w=a.map(S=>{var W,ne;return((W=S==null?void 0:S.value)==null?void 0:W.valueAsType)||((ne=S==null?void 0:S.value)==null?void 0:ne.value)});console.log("Loops' resolved raw input-map values: ",w);let A={};i.getUniqueReturnDeclarations().forEach(S=>{const W=i.body.inputs.find(se=>ie(se,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(S)),ne=S==null?void 0:S.getDataType(null),re=We(ne,W,l);ne!=null&&ne.asType?re==null||re.setValueAsTypeList([]):re==null||re.metaSync({value:[]},null),this.lastExecutionResults.writeValue(W,re);const pe={value:re,valueOwner:W,type:be.ExecutionResult,inheritanceLink:null};A[W.id]=pe});let N={value:Ke.Success,entity:i.body,error:null,results:[]};switch(console.log("aggregateListResults: ",A),i.declaration.id){case ve.loop["counted-loop"].id:{const S=w[0];console.log("maxCount",S);let W=1;for(console.log("currentIteration",W);W<=S&&W<=50;){console.log("iterating",W);const ne=i.body.inputs.map(pe=>{if(pe===i.currentIterationNumberArgumentDeclaration){console.log("Argument is body iteration number");const se=i.currentIterationNumberArgumentDeclaration.getDataType(null),he=Ho(se),X=this.lastExecutionResults.readValue(pe.id);if(X){X.metaSync({value:W},null),console.log("existingValue",W),this.lastExecutionResults.writeValue(pe,X);const de={value:X,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null};return A[pe.id]=de,de}const z={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:W,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:he,standaloneParent:pe.toReference()},ce=St(z,l);this.lastExecutionResults.writeValue(pe,ce);const H={value:ce,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null};return console.log("newDynamicValue",W),A[pe.id]=H,H}else return A[pe.id]}).filter(pe=>!!pe);console.log("Loop executes body with inputs: ",ne);const re=await this.executeFullFunctionDeclarationLogic(i.body,ne,t);if(N=re,N.results.forEach(pe=>{var z,ce,H,de;if(pe.valueOwner.type!==f.ReturnDeclaration)return;const se=i.body.inputs.find(Te=>ie(Te,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(pe.valueOwner)),X=[...((ce=(z=A==null?void 0:A[se.id])==null?void 0:z.value)==null?void 0:ce.value)||[],((H=pe==null?void 0:pe.value)==null?void 0:H.value)||null];(de=A[se.id].value)==null||de.metaSync({value:X},null),this.lastExecutionResults.writeValue(se,A[se.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(re.value))break;console.log("Loop iteration finished"),W++}break}case ve.loop["manual-flow-loop"].id:{let S=1;for(;S<=50;){const W=i.body.inputs.map(re=>{if(re===i.currentIterationNumberArgumentDeclaration){const pe=this.lastExecutionResults.readValue(re.id);if(pe){pe.metaSync({value:S},null),this.lastExecutionResults.writeValue(re,pe);const z={value:pe,valueOwner:re,type:be.ExecutionResult,inheritanceLink:null};return A[re.id]=z,z}const se=i.currentIterationNumberArgumentDeclaration.getDataType(null),he=We(se,re,l);he==null||he.metaSync({value:S},null),this.lastExecutionResults.writeValue(re,he);const X={value:he,valueOwner:re,type:be.ExecutionResult,inheritanceLink:null};return console.log("newDynamicValue",S),X}else return A[re.id]}).filter(re=>!!re);console.log("Loop executes body");const ne=await this.executeFullFunctionDeclarationLogic(i.body,W,t);if(N=ne,N.results.forEach(re=>{var X,z,ce;if(re.valueOwner.type!==f.ReturnDeclaration)return;const pe=i.body.inputs.find(H=>ie(H,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(re.valueOwner)),he=[...(X=A[pe.id].value)==null?void 0:X.value,((z=re.value)==null?void 0:z.value)||null];(ce=A[pe.id].value)==null||ce.metaSync({value:he},null),this.lastExecutionResults.writeValue(pe,A[pe.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(ne.value))break;S++}break}case ve.loop["list-loop"].id:{const S=w[0];let W=1;const ne=S;for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body");const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}case ve.loop["object-keys-loop"].id:{const S=w[0];let W=1;const ne=S?Object.keys(S):[];console.log("iterableListOfValues: ",ne);for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body");const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}case ve.loop["object-values-loop"].id:{const S=w[0];let W=1;const ne=S?Object.values(S):[];for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body"),console.log("HEREEE Object.values() resolvedBodyInputsForCurrentIteration",se);const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}case ve.loop["string-loop"].id:{const S=w[0];let W=1;const ne=S.split("");for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body");const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}}let j=[];i.body.inputs.forEach(S=>{var ne;const W=A[S.id];if(W){const re=(ne=W.value)==null?void 0:ne.clone(null),pe=i.outputs.find(se=>se.declaration&&bi.fromLoopOutputDeclarationToBodyArgumentDeclarationName(se.declaration)===ie(S,l));if(!pe)return;j.push({valueOwner:pe,type:be.ExecutionResult,inheritanceLink:null,value:re})}}),T={value:[Ke.Error,Ke.Return].includes(N.value)?N.value:Ke.Success,error:null,results:j};let k=null;if(T.error&&i.error){console.warn("Raw error executing entity: ",T.error);const S=(y=i.error)==null?void 0:y.getDataType(null),W=We(S||null,i.error,l);S!=null&&S.asType?W==null||W.setValueAsTypeSingle(T.error):W==null||W.metaSync({value:T.error},null),k={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:W}}return{value:T.value,entity:i,error:k,results:T.results}}catch(T){if(console.warn("Error executing loop: ",T),i.error){const w=(v=i.error)==null?void 0:v.getDataType(null),A=We(w,i.error,l);return w!=null&&w.asType?A==null||A.setValueAsTypeSingle(T):A==null||A.metaSync({value:T},null),{value:Ke.Error,entity:i,error:{valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:A},results:[]}}else return{value:Ke.Error,entity:i,error:null,results:[]}}}async executeFunctionCall(i,a,l,p={}){var y,v;const t={...Ja,...p};try{let T={value:Ke.Success,error:null,results:[]};console.log("executeFunctionCall",a),T=await this.executeDetachedFullFunctionDeclarationLogic(i.declaration,a,l,t);const w=i.outputs.map(V=>{var W,ne,re,pe;const N=[...V.declaration.getCounterparts(),V.declaration];console.log("declarations",N);const j=T.results.find(se=>N.some(X=>se.valueOwner.id===X.id));console.log("resultValue",j);const k=V==null?void 0:V.getDataType(null),S=We(k,V,l);return k!=null&&k.asType?Array.isArray((W=j==null?void 0:j.value)==null?void 0:W.valueAsType)?S==null||S.setValueAsTypeList((ne=j==null?void 0:j.value)==null?void 0:ne.valueAsTypeList):S==null||S.setValueAsTypeSingle(((re=j==null?void 0:j.value)==null?void 0:re.valueAsType)||null):S==null||S.metaSync({value:(pe=j==null?void 0:j.value)==null?void 0:pe.value},null),{valueOwner:V,type:be.ExecutionResult,inheritanceLink:null,value:S}});let A=null;if(T.error&&i.error){console.warn("Raw error executing entity: ",T.error);const V=(y=i.error)==null?void 0:y.getDataType(null),N=We(V||null,i.error,l);V!=null&&V.asType?N==null||N.setValueAsTypeSingle(T.error):N==null||N.metaSync({value:T.error},null),A={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:N}}return{value:T.value,entity:i,error:A,results:w}}catch(T){if(console.log("error: ",T),!i.error)return{value:Ke.Error,entity:i,error:null,results:[]};const w=(v=i.error)==null?void 0:v.getDataType(null),A=We(w,i.error,l);return w!=null&&w.asType?A==null||A.setValueAsTypeSingle(T):A==null||A.metaSync({value:T},null),{value:Ke.Error,entity:i,error:{valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:A},results:[]}}}static async executeCondition(i,a){var p,t,y,v,T,w,A,V,N,j,k,S,W,ne,re,pe,se,he,X,z,ce,H,de,Te,Ne,we,Re,ge,Ue,Pe,Je,ut,Jt,or,Ir,jr;let l=!1;switch(i.declaration.id){case Mr.Empty:{l=!((t=(p=a[0])==null?void 0:p.value)!=null&&t.value);break}case Mr.NotEmpty:{l=!!((v=(y=a[0])==null?void 0:y.value)!=null&&v.value);break}case cr.Equal:{if([Q.String,Q.Number,Q.Boolean,Q.Null,Q.Enum,Q.Date,Q.UUID].includes((w=(T=a[0])==null?void 0:T.value)==null?void 0:w.name)){l=((V=(A=a[0])==null?void 0:A.value)==null?void 0:V.value)===((j=(N=a[1])==null?void 0:N.value)==null?void 0:j.value);break}if(((S=(k=a[0])==null?void 0:k.value)==null?void 0:S.name)===Q.KeyValue||((ne=(W=a[0])==null?void 0:W.value)==null?void 0:ne.name)===Q.Untyped){const Kr=(pe=(re=a[0])==null?void 0:re.value)==null?void 0:pe.value,Mi=(he=(se=a[1])==null?void 0:se.value)==null?void 0:he.value;l=JSON.stringify(Kr)===JSON.stringify(Mi);break}break}case cr.NotEqual:{if([Q.String,Q.Number,Q.Boolean,Q.Null,Q.Enum,Q.Date,Q.UUID].includes((z=(X=a[0])==null?void 0:X.value)==null?void 0:z.name)){l=((H=(ce=a[0])==null?void 0:ce.value)==null?void 0:H.value)!==((Te=(de=a[1])==null?void 0:de.value)==null?void 0:Te.value);break}if(((we=(Ne=a[0])==null?void 0:Ne.value)==null?void 0:we.name)===Q.Untyped||((ge=(Re=a[0])==null?void 0:Re.value)==null?void 0:ge.name)===Q.KeyValue){const Kr=(Pe=(Ue=a[0])==null?void 0:Ue.value)==null?void 0:Pe.value,Mi=(ut=(Je=a[1])==null?void 0:Je.value)==null?void 0:ut.value;l=JSON.stringify(Kr)!==JSON.stringify(Mi);break}break}case cr.MoreThanOrEqual:{l=((or=(Jt=a[0])==null?void 0:Jt.value)==null?void 0:or.value)>=((jr=(Ir=a[1])==null?void 0:Ir.value)==null?void 0:jr.value);break}}return{value:l?Ke.Success:Ke.Error,entity:i,error:null,results:[]}}async executeDetachedFullFunctionDeclarationLogic(i,a,l,p={}){const t={...Ja,...p,onBeforeEntityExecution:(T,w,A)=>{var V;return((V=p==null?void 0:p.onBeforeEntityExecution)==null?void 0:V.call(p,T,w,{...A,detached:!0}))||Promise.resolve()},onEntityExecuted:(T,w,A)=>{var V;return((V=p==null?void 0:p.onEntityExecuted)==null?void 0:V.call(p,T,w,{...A,detached:!0}))||Promise.resolve()}},y=new Bi(l,[i,...Hy(i)],i,this);y.inheritValuesFromContext(this),console.log("functionBodyExecution",a);const v=await y.execute(t,a);return console.log("executeDetachedFullFunctionDeclarationLogic result: ",v),v}async executeFullFunctionDeclarationLogic(i,a,l={}){const p={...Ja,...l},t=Hy(i);t.forEach(A=>{this.addEntity(A)}),t.reduce((A,V)=>nr.includes(V.type)?[...A,...V.outputs]:er.includes(V.type)&&V.type!==f.Condition?[...A,...V.outputs,...V.inputs]:V.type===f.Condition?[...A,...V.inputs]:A,[]).forEach(A=>{this.lastExecutionResults.removeValue(A.id)});const v=await this.executeBranch(i,p,a),w=i.getUniqueReturnDeclarations().reduce((A,V)=>{const N=v==null?void 0:v.results.find(j=>j.valueOwner.id===V.id);return N?[...A,N]:A},[]);return{...v||{},value:(v==null?void 0:v.value)||Ke.Success,entity:i,error:(v==null?void 0:v.error)||null,results:w}}static async executeEntryPointEntity(i,a){return{value:Ke.Success,entity:i,error:null,results:a}}static async executeVariable(i,a){return{value:Ke.Success,entity:i,error:null,results:[a]}}static async executeReturnStatement(i,a){return{value:i.throws?Ke.Error:Ke.Return,entity:i,error:null,results:a}}static async executeContinueStatement(i,a){return{value:Ke.Continue,entity:i,error:null,results:a}}static async executeBreakStatement(i,a){return{value:Ke.Break,entity:i,error:null,results:a}}mergeValues(i,a){const l=[];for(let p=0;p<a.length;p++)i!=null&&i[p]?l.push(i[p]):l.push(a[p]);return l}async executeEntity(i,a=[],l={}){var y,v,T,w,A,V,N,j,k,S,W,ne,re,pe,se,he,X;const p={...Ja,...l},t={detached:!1};switch(console.log("Executing entity: ",i),console.log("Exec ent with inputs: ",a),i.type){case f.Condition:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((y=p.onBeforeEntityExecution)==null?void 0:y.call(p,i,z,t)),Bi.executeCondition(i,z)}case f.InternalCall:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((v=p.onBeforeEntityExecution)==null?void 0:v.call(p,i,z,t)),this.executeInternalCall(i,z,this.project)}case f.Operation:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((T=p.onBeforeEntityExecution)==null?void 0:T.call(p,i,z,t)),Bi.executeOperation(i,z,this.project)}case f.VariableInstance:case f.VariableDeclaration:{i.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("Execute variable declaration resolveNextValue");let z=Oy(i,this.valueResolutionContext);const ce=di(i),H=ce.getDataType(null);if(H!=null&&H.isObject()){let Ne={};if(((w=H==null?void 0:H.entity)==null?void 0:w.type)===f.DefinitionEntity&&(Ne={...Ne,...H.entity.getActiveRawDefaultValue()}),z!=null&&z.value)ar((A=z==null?void 0:z.value)==null?void 0:A.value)&&(Ne={...Ne,...(V=z==null?void 0:z.value)==null?void 0:V.value}),z==null||z.value.metaSync({value:Ne},null);else{const we=We(H,i,this.project);we==null||we.metaSync({value:Ne},null),z={valueOwner:ce,type:be.ExecutionResult,inheritanceLink:null,value:we}}this.lastExecutionResults.writeValue(ce,z.value),console.log("Propagating value to inputs: ",ce.inputs.map(we=>ie(we,this.project))),ce.inputs.forEach(we=>{var Re;if(((Re=we.declaration)==null?void 0:Re.type)===f.Property&&we.declaration.static){const ge=this.lastExecutionResults.readValue(we.declaration.id),Ue=ie(we,this.project),Pe=Tr(Ue);if(ge)ge.metaSync({value:Ne[Pe]},null),this.lastExecutionResults.writeValue(we.declaration,ge);else{const Je=We(we.getDataType(null),we,this.project);Je==null||Je.metaSync({value:Ne[Pe]},null),console.log(`Created new value for static property ${Ue}: `,Ne[Pe]),this.lastExecutionResults.writeValue(we.declaration,Je)}}})}else this.lastExecutionResults.writeValue(ce,z==null?void 0:z.value);const de=[],Te=(N=z==null?void 0:z.value)!=null&&N.value&&ar((j=z.value)==null?void 0:j.value)?((k=z.value)==null?void 0:k.value)||{}:{};return i.outputs.map(Ne=>{const we=Tr(ie(Ne,this.project)),Re=Te[we],ge=We(Ne.getDataType(null),Ne,this.project);ge==null||ge.metaSync({value:Re},null);const Ue={value:ge,valueOwner:Ne,type:be.ExecutionResult,inheritanceLink:z?{sources:[z],target:i}:null};de.push(Ue)}),z.type=be.ExecutionResult,{value:Ke.Success,entity:i,error:null,results:[z,...de]}}case f.FunctionCall:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((S=p.onBeforeEntityExecution)==null?void 0:S.call(p,i,z,t)),this.executeFunctionCall(i,z,this.project)}case f.FunctionDeclaration:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((W=p.onBeforeEntityExecution)==null?void 0:W.call(p,i,z,t)),Bi.executeEntryPointEntity(i,z)}case f.Search:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((ne=p.onBeforeEntityExecution)==null?void 0:ne.call(p,i,z,t)),this.executeSearch(i,z,this.project)}case f.Loop:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((re=p.onBeforeEntityExecution)==null?void 0:re.call(p,i,z,t)),this.executeLoop(i,z,this.project,p)}case f.ReturnStatement:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((pe=p.onBeforeEntityExecution)==null?void 0:pe.call(p,i,z,t)),Bi.executeReturnStatement(i,z)}case f.ContinueStatement:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((se=p.onBeforeEntityExecution)==null?void 0:se.call(p,i,z,t)),Bi.executeContinueStatement(i,z)}case f.BreakStatement:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((he=p.onBeforeEntityExecution)==null?void 0:he.call(p,i,z,t)),Bi.executeBreakStatement(i,z)}case f.GlobalEvent:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((X=p.onBeforeEntityExecution)==null?void 0:X.call(p,i,z,t)),Bi.executeEntryPointEntity(i,z)}default:return{value:Ke.Error,entity:i,error:null,results:[]}}}storeLastExecutionValues(i){i.error&&i.error.valueOwner&&this.lastExecutionResults.writeValue(i.error.valueOwner,i.error.value),console.log("result.results: ",i.results),i.results.forEach(a=>{const l=tn(a.valueOwner,this.project);a.value?l.forEach(p=>{this.lastExecutionResults.writeValue(p,a.value)}):l.forEach(p=>{this.lastExecutionResults.removeValue(p.id)})})}async executeBranch(i,a={},l=[]){var T;const p={...Ja,...a},t={detached:!1};if(console.log("executeBranch: ",l),!this.hasEntity(i))return console.log("Skipping entity (not part of test): ",i),null;if(this.hasSkipped(i))return console.log("Skipping entity (already skipped): ",i),null;this.addToExecutingList(i),this.hasScheduled(i)&&this.removeScheduled(i),console.log("Executing branch: ",i),console.log("values: ",l);const v=await this.executeEntity(i,l,p);if(this.removeFromExecutingList(i),this.addToAlreadyExecutedList(i),this.storeLastExecutionValues(v),await((T=p.onEntityExecuted)==null?void 0:T.call(p,i,v,t)),v.value===Ke.Success){const w=(i.successCalls||i.calls||[]).filter(k=>this.hasEntity(k));(i.errorCalls||[]).forEach(k=>{this.skip(k)});let V=[];const N=(await Promise.all(w.map(k=>this.schedule(k,v.results,p)))).filter(k=>!!k),j=N.filter(k=>!!k).find(k=>k.value===Ke.Error||k.value===Ke.Return||k.value===Ke.Break||k.value===Ke.Continue);return j||(V=[...V,...N],v)}else if(v.value===Ke.Error){const w=(i.errorCalls||[]).filter(k=>this.hasEntity(k));(i.successCalls||i.calls||[]).forEach(k=>{this.skip(k)});let V=[];const N=(await Promise.all(w.map(k=>this.schedule(k,v.results,p)))).filter(k=>!!k),j=N.filter(k=>!!k).find(k=>k.value===Ke.Error||k.value===Ke.Return||k.value===Ke.Break||k.value===Ke.Continue);return j||(V=[...V,...N],v)}else{if(v.value===Ke.Return)return v;if(v.value===Ke.Break)return v;if(v.value===Ke.Continue)return v}return v}async execute(i={},a=[]){const l={...Ja,...i};this.state="running";const p=await this.executeBranch(this.entryPoint,l,a);return this.state="finished-success",p}addEntity(i){var a;this.entities.includes(i)||(this.entities.push(i),(a=this.onAddEntityCallback)==null||a.call(this,i))}addEntities(i){i.forEach(a=>this.addEntity(a))}removeEntity(i){var a;if(i!==this.entryPoint){const l=this.entities.indexOf(i);l>-1&&(this.entities.splice(l,1),(a=this.onRemoveEntityCallback)==null||a.call(this,i))}}hasEntity(i){var p,t,y;if(this.entities.includes(i))return!0;if(((p=i.parent)==null?void 0:p.type)===f.FunctionDeclaration&&((y=(t=i.parent)==null?void 0:t.parent)==null?void 0:y.type)===f.DefinitionEntity)return this.entities.includes(i.parent);const a=rr(i);if(!a)return!1;const l=a.type===f.Loop&&i.parent===a.body?a.body:null;return l?this.entities.includes(l)||this.entities.includes(a):this.entities.includes(a)}removeScheduled(i){const a=this.scheduled.indexOf(i);a>-1&&this.scheduled.splice(a,1)}hasScheduled(i){return!!this.scheduled.includes(i)}hasSkipped(i){return!!this.skipped.includes(i)}hasExecuted(i){return!!this.executed.includes(i)}hasEntityWithId(i){const a=this.project.get(i);return a?this.hasEntity(a):!1}onAddToSkippedList(i){this.onAddToSkippedListCallback=i}onAddEntity(i){this.onAddEntityCallback=i}onRemoveFromSkippedList(i){this.onRemoveFromSkippedListCallback=i}onRemoveEntity(i){this.onRemoveEntityCallback=i}addToExecutingList(i){this.executing.includes(i)||this.executing.push(i)}removeFromExecutingList(i){const a=this.executing.indexOf(i);a>-1&&this.executing.splice(a,1)}removeFromAlreadyExecutedList(i){const a=this.executed.indexOf(i);a>-1&&this.executed.splice(a,1)}removeFromSkippedList(i){var l;const a=this.skipped.indexOf(i);a>-1&&(this.skipped.splice(a,1),(l=this.onRemoveFromSkippedListCallback)==null||l.call(this,i))}addToAlreadyExecutedList(i){this.executed.includes(i)||this.executed.push(i)}addToSkippedList(i){var a;this.skipped.includes(i)||(this.skipped.push(i),(a=this.onAddToSkippedListCallback)==null||a.call(this,i))}};D(Bi,"searchImplementation",async()=>({data:null,error:"Search module not implemented"})),D(Bi,"builtInFunctionImplementations",{[gi.AbortExecution]:async(i,a)=>({value:Ke.Error,entity:i,error:null,results:[]}),[gi.SavePersistedEntity]:async(i,a)=>({value:Ke.Error,entity:i,error:null,results:[]}),[gi.DeletePersistedEntity]:async(i,a)=>({value:Ke.Error,entity:i,error:null,results:[]})});let Qb=Bi;function xme(d){var u,i;if(d.isList)return"list";if(((u=d.entity)==null?void 0:u.type)===f.DefinitionEntity)return"definition-entity";switch((i=d.entity)==null?void 0:i.name){case Q.Number:return"number";case Q.String:return"text";case Q.Boolean:return"boolean";case Q.UUID:return"uuid";case Q.Date:return"date-time";default:return"definition-entity"}}const eA={[f.PrimitiveEntity]:{singular:"Primitive",plural:"Primitives",shortSingular:"Primitive",shortPlural:"Primitives"},[f.DefinitionEntity]:{singular:"Definition",plural:"Definitions",shortSingular:"Definition",shortPlural:"Definitions"},[f.BuiltInBaseEntity]:{singular:"Base",plural:"Bases",shortSingular:"Base definition",shortPlural:"Base definitions"},[f.Property]:{singular:"Property",plural:"Properties",shortSingular:"Property",shortPlural:"Properties"},[f.FunctionDeclaration]:{singular:"Custom trigger",plural:"Custom triggers",shortSingular:"Trigger",shortPlural:"Triggers"},[f.FunctionCall]:{singular:"Execute trigger",plural:"Execute trigger",shortSingular:"Execute",shortPlural:"Execute"},[f.GlobalEvent]:{singular:"System trigger",plural:"System triggers",shortSingular:"Trigger",shortPlural:"Triggers"},[f.Project]:{singular:"Project",plural:"Projects",shortSingular:"Project",shortPlural:"Projects"},[f.VariableDeclaration]:{singular:"Variable",plural:"Variables",shortSingular:"Variable",shortPlural:"Variables"},[f.VariableInstance]:{singular:"Variable",plural:"Variables",shortSingular:"Variable",shortPlural:"Variables"},[f.Condition]:{singular:"Condition",plural:"Conditions",shortSingular:"Condition",shortPlural:"Conditions"},[f.Operation]:{singular:"Operation",plural:"Operations",shortSingular:"Operation",shortPlural:"Operations"},[f.ReturnStatement]:{singular:"Termination",plural:"Terminations",shortSingular:"Termination",shortPlural:"Terminations"},[f.InstalledProject]:{singular:"Installed project",plural:"Installed projects",shortSingular:"Project",shortPlural:"Projects"},[f.Search]:{singular:"Search",plural:"Searches",shortSingular:"Search",shortPlural:"Searches"},[f.Loop]:{singular:"Loop",plural:"Loops",shortSingular:"Loop",shortPlural:"Loops"},[f.ActionDescriptor]:{singular:"Action descriptor",plural:"Action descriptors",shortSingular:"Action descriptor",shortPlural:"Action descriptors"},[f.InternalCall]:{singular:"Internal call",plural:"Internal calls",shortSingular:"Internal call",shortPlural:"Internal calls"},[f.BreakStatement]:{singular:"Loop exit",plural:"Loop exists",shortSingular:"Exit",shortPlural:"Exits"},[f.ContinueStatement]:{singular:"Next iteration",plural:"Next iterations",shortSingular:"Next",shortPlural:"Nexts"},[f.ArgumentDeclaration]:{singular:"Input definition",plural:"Input definitions",shortSingular:"Input",shortPlural:"Inputs"},[f.InputMap]:{singular:"Input",plural:"Inputs",shortSingular:"Input",shortPlural:"Inputs"},[f.OutputMap]:{singular:"Output",plural:"Outputs",shortSingular:"Output",shortPlural:"Outputs"},[f.ReturnDeclaration]:{singular:"Output definition",plural:"Output definitions",shortSingular:"Output",shortPlural:"Outputs"},[f.ValueDescriptor]:{singular:"Value descriptor",plural:"Value descriptors",shortSingular:"Value descriptor",shortPlural:"Value descriptors"}};function tA(d){const u=Yy(d);if(!u){const a=Vd(d);if(a.includes(Ce.HTTP_ENDPOINT))return"HTTP endpoint";if(a.includes(Ce.PERSISTED_ENTITY))return"Persisted entity";if(a.includes(Ce.CRON_JOB))return"Scheduled execution";if(a.includes(Ce.RELATIONAL_DATABASE))return"Relational database"}if(u){let a="Extension of "+ie(u,u.project)+" entity",l=vd(a);const p=Vd(d);return p.includes(Ce.HTTP_ENDPOINT)?"HTTP endpoint"+(l?", "+l:""):p.includes(Ce.PERSISTED_ENTITY)?"Persisted entity"+(l?", "+l:""):p.includes(Ce.CRON_JOB)?"Scheduled execution"+(l?", "+l:""):p.includes(Ce.RELATIONAL_DATABASE)?"Relational database"+(l?", "+l:""):a}let i="";return d.abstract&&(i="Template "),d.static&&(i+=i?" single copy ":"Single copy "),i?i+"definition":"Definition"}function Qx(d){return d.parent.type===f.DefinitionEntity||d.parent.type===f.InstalledProject?"Internal action of "+ie(d.parent,d.project):d.parent.type===f.Loop?"Action repeated on every iteration":"Internal action of entity"}function rA(d){return jA(d)?Qx(d):"Custom trigger"}function Fme(d){var u;switch(d.type){case f.DefinitionEntity:return tA(d);case f.FunctionDeclaration:return rA(d)}return(u=eA[d.type])==null?void 0:u.singular}function Gme(d){var u;switch(d.type){case f.DefinitionEntity:return tA(d);case f.FunctionDeclaration:return rA(d)}return(u=eA[d.type])==null?void 0:u.singular}const iA=4e4,eF=280,Kme=300,sA=65,Od=32,Cy=39,tF=26,rF=49,$y=44,kme=35,Py=52,nA=10,ha=nA*2,Vy=38,Ny=90,aA=270,iF=iA/2+120,sF=iA/2+180;function nF(d){let i=Od+$y+Vy+nA;const a=[...d.inputs];return a.length&&(i+=ha,a.forEach(()=>{i+=tF})),{height:i,width:280}}function aF(d){let i=sA;const a=[];if([f.DefinitionEntity].includes(d.type)){const v=[...d.suggestedProperties||[],...d.properties||[]];v.length&&(i+=ha,v.forEach(T=>{i+=T.static?rF:Cy}))}if([f.DefinitionEntity,f.InstalledProject,f.Loop].includes(d.type)){const v=[...(d==null?void 0:d.suggestedMethods)||[],...d.methods||[],...d.functions||[],...d.body?[d.body]:[]];v.length&&(i+=ha,v.forEach(T=>{const w=nF(T);i+=w.height}))}er.includes(d.type)?(st.includes(d.type)?a.push(...(d.usedInputs||[]).flatMap(v=>[v])||[]):a.push(...(d.inputs||[]).flatMap(v=>[v])||[]),d.error&&(i+=Py)):[f.ReturnStatement,f.BreakStatement,f.ContinueStatement].includes(d.type)?(a.push(...d.outputs||[]),d.throws&&(i+=Py)):d.type===f.Condition&&(a.push(d.inputs[0]),d.inputs[1]&&a.push(d.inputs[1]));const l=a.length;l&&(i+=l*Cy,i+=ha);const p=[];if(d.type===f.FunctionDeclaration||d.type===f.GlobalEvent?p.push(...d.inputs||[]):er.includes(d.type)&&(st.includes(d.type)?p.push(...d.usedOutputs||[]):p.push(...d.outputs||[])),st.includes(d.type)){d.readsValue&&(i+=ha,i+=$y),d.writesValues.length&&(i+=ha,i+=$y),d.internalCalls.length&&d.usedInternalCalls.forEach(()=>i+=Py+ha);const v=d.getDataType(null);(!v||v.inferred)&&(i+=Vy)}const t=p.length;return t&&(i+=t*Cy,i+=ha),[f.DefinitionEntity,f.FunctionDeclaration,f.ReturnStatement,f.BreakStatement,f.ContinueStatement].includes(d.type)&&(i+=Vy),{height:i,width:280}}function Dp(d){return`${d.split("-").map((a,l)=>l===0?a.charAt(0).toUpperCase()+a.slice(1):a.toLowerCase()).join(" ")}.`}function Sme(d){switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return"This template entity has non-template actions";case oe.AbstractEntityWithNonAbstractProperties:return"This template entity has non-template properties";case oe.IncorrectEntityImplementation:return"This entity incorrectly implements a template entity";case oe.IncorrectMethodImplementation:return"This action incorrectly implements the template action it's based on";case oe.IncorrectPropertyImplementation:return"This property incorrectly implements the template property it's based on";case oe.AbstractMethodInNonAbstractEntity:return"This action is a template action in a non-template entity";case oe.AbstractPropertyInNonAbstractEntity:return"This property is a template property in a non-template entity";case ae.MethodOverwritesOtherSiblingWithSameName:return"An action in this entity overwrites an action in the template entity with the same name";case ae.PropertyOverwritesOtherSiblingWithSameName:return"A property in this entity overwrites a property in the template entity with the same name";case oe.MissingMethodImplementation:return"This entity is missing an action implementation from the template entity";case oe.MissingPropertyImplementation:return"This entity is missing a property implementation from the template entity";case ae.NameNotUniqueInScope:return"Invalid name. There is another entity with the same name in the same scope";case oe.NoProperties:return"This entity has no properties, so it doesn't do anything";case oe.NonStaticPropertyInStaticEntity:return"This property is not static in a static entity";case oe.StaticEntityWithNonStaticProperties:return"This static entity has non-static properties";case oe.ReadingFromIncompatibleType:return"This entity reads data from a value of a different data type";case oe.WritingToIncompatibleType:return"This entity writes data to a value of a different data type";case oe.ScopeWithoutLogic:return"This action has no logic, so it doesn't do anything";case oe.NonStaticPropertyImplementsStatic:return"This property is static in a non-static entity";case oe.PropertyImplementsIncompatibleType:return"This property implements a property of a different data type";case oe.PropertyImplementsNonAbstact:return"This property implements a non-template property";case oe.StaticPropertyImplementsNonStatic:return"This static property implements a non-static property";case oe.VariableCallsOthersAndHasInternalCall:return"This variable calls other entities while being used to execute internal logic";case oe.VariableHasInputsAndInternalCall:return"This variable has inputs while being used to execute internal logic";case oe.VariableHasOutputsAndInternalCall:return"This variable has outputs while being used to execute internal logic";case oe.VariableIsCalledAndHasInternalCall:return"This variable is called while being used to execute internal logic";case ae.InternalCallDeclarationIsNotFunctionDeclaration:return"This internal call is not an action";case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return"This internal call is not found in the parent entity";case ae.InternalCallParentDeclarationEntityInvalidType:return"This internal call parent entity is not a data type";case ae.InternalCallParentMissingDataType:return"This internal call parent entity has no data type";case ae.UnreachableEntity:return"This entity is unreachable";case oe.DisconnectedCallableEntity:return"This entity is disconnected and won't be executed by anything after publishing";default:return Dp(d.code)}}function qme(d){switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return"Non-template actions";case oe.AbstractEntityWithNonAbstractProperties:return"Non-template properties";case oe.IncorrectEntityImplementation:return"Incorrect implementation";case oe.IncorrectMethodImplementation:return"Incorrect action implementation";case oe.IncorrectPropertyImplementation:return"Incorrect property implementation";case oe.AbstractMethodInNonAbstractEntity:return"Template action in non-template entity";case oe.AbstractPropertyInNonAbstractEntity:return"Template property in non-template entity";case ae.MethodOverwritesOtherSiblingWithSameName:return"Action overwrite";case ae.PropertyOverwritesOtherSiblingWithSameName:return"Property overwrite";case oe.MissingMethodImplementation:return"Missing action";case oe.MissingPropertyImplementation:return"Missing property";case ae.NameNotUniqueInScope:return"Duplicate name";case oe.NoProperties:return"No properties";case oe.NonStaticPropertyInStaticEntity:return"Non-static property";case oe.StaticEntityWithNonStaticProperties:return"Non-static properties";case oe.ReadingFromIncompatibleType:return"Read from different type";case oe.WritingToIncompatibleType:return"Write to different type";case oe.ScopeWithoutLogic:return"No logic";case oe.NonStaticPropertyImplementsStatic:return"Invalid static property";case oe.PropertyImplementsIncompatibleType:return"Incompatible data type";case oe.PropertyImplementsNonAbstact:return"Non-template property";case oe.StaticPropertyImplementsNonStatic:return"Non-static property";case oe.VariableCallsOthersAndHasInternalCall:return"Bad internal call";case oe.VariableHasInputsAndInternalCall:return"Bad internal call";case oe.VariableHasOutputsAndInternalCall:return"Bad internal call";case oe.VariableIsCalledAndHasInternalCall:return"Bad internal call";case ae.InternalCallDeclarationIsNotFunctionDeclaration:return"Declaration not an action";case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return"Declaration not found in parent";case ae.InternalCallParentDeclarationEntityInvalidType:return"Invalid parent declaration type";case ae.InternalCallParentMissingDataType:return"Parent has no data type";case ae.InternalCallDeclarationNotInParentDatatypeEntity:return"Declaration not in parent";case ae.UnreachableEntity:return"Unreachable entity";case oe.DisconnectedCallableEntity:return"Disconnected entity";default:return Dp(d.code)}}function Zme(d){switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return`${ie(d.entity,d.entity.project)} has non-template actions`;case oe.AbstractEntityWithNonAbstractProperties:return`${ie(d.entity,d.entity.project)} has non-template properties`;case oe.IncorrectEntityImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements template`;case oe.IncorrectMethodImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template`;case oe.IncorrectPropertyImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template`;case oe.AbstractMethodInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} can't be a template`;case oe.AbstractPropertyInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} can't be a template`;case ae.MethodOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites action`;case ae.PropertyOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites property`;case oe.MissingMethodImplementation:return`${ie(d.entity,d.entity.project)} is missing action`;case oe.MissingPropertyImplementation:return`${ie(d.entity,d.entity.project)} is missing property`;case ae.NameNotUniqueInScope:return`${ie(d.entity,d.entity.project)} name is not unique`;case oe.NoProperties:return`${ie(d.entity,d.entity.project)} has no properties`;case oe.NonStaticPropertyInStaticEntity:return`${ie(d.entity,d.entity.project)} has non-static property`;case oe.StaticEntityWithNonStaticProperties:return`${ie(d.entity,d.entity.project)} has non-static properties`;case oe.ReadingFromIncompatibleType:return`${ie(d.entity,d.entity.project)} reads from different type`;case oe.WritingToIncompatibleType:return`${ie(d.entity,d.entity.project)} writes to different type`;case oe.ScopeWithoutLogic:return`${ie(d.entity,d.entity.project)} has no logic`;case oe.NonStaticPropertyImplementsStatic:return`${ie(d.entity,d.entity.project)} has invalid static property`;case oe.PropertyImplementsIncompatibleType:return`${ie(d.entity,d.entity.project)} has incompatible data type`;case oe.PropertyImplementsNonAbstact:return`${ie(d.entity,d.entity.project)} has non-template property`;case oe.StaticPropertyImplementsNonStatic:return`${ie(d.entity,d.entity.project)} has non-static property`;case oe.VariableCallsOthersAndHasInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case oe.VariableHasInputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case oe.VariableHasOutputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case oe.VariableIsCalledAndHasInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case ae.InternalCallDeclarationIsNotFunctionDeclaration:return`${ie(d.entity,d.entity.project)} has declaration that is not an action`;case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has declaration that is not found in parent`;case ae.InternalCallParentDeclarationEntityInvalidType:return`${ie(d.entity,d.entity.project)} has invalid parent declaration type`;case ae.InternalCallParentMissingDataType:return`${ie(d.entity,d.entity.project)}'s parent has no data type`;case ae.InternalCallDeclarationNotInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has declaration that is not in parent`;case ae.UnreachableEntity:return`${ie(d.entity,d.entity.project)} is unreachable`;case oe.DisconnectedCallableEntity:return`${ie(d.entity,d.entity.project)} is not executed by any entity`;default:return`${ie(d.entity,d.entity.project)} Error: ${Dp(d.code)}`}}function Jme(d){var u,i,a,l;switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return`${ie(d.entity,d.entity.project)} has non-template actions`;case oe.AbstractEntityWithNonAbstractProperties:return`${ie(d.entity,d.entity.project)} has non-template properties`;case oe.IncorrectEntityImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template entity`;case oe.IncorrectMethodImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template action it's based on`;case oe.IncorrectPropertyImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template property it's based on`;case oe.AbstractMethodInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} is a template action in a non-template entity`;case oe.AbstractPropertyInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} is a template property in a non-template entity`;case ae.MethodOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites an action in the template entity`;case ae.PropertyOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites a property in the template entity`;case oe.MissingMethodImplementation:return`${ie(d.entity,d.entity.project)} is missing an action implementation from the template entity`;case oe.MissingPropertyImplementation:return`${ie(d.entity,d.entity.project)} is missing a property implementation from the template entity`;case ae.NameNotUniqueInScope:return`${ie(d.entity,d.entity.project)} has a duplicate name in the same scope`;case oe.NoProperties:return`${ie(d.entity,d.entity.project)} has no properties, so it doesn't do anything`;case oe.NonStaticPropertyInStaticEntity:return`${ie(d.entity,d.entity.project)} has a non-static property in a static entity`;case oe.StaticEntityWithNonStaticProperties:return`${ie(d.entity,d.entity.project)} has non-static properties in a static entity`;case oe.ReadingFromIncompatibleType:return`${ie(d.entity,d.entity.project)} reads data from a value of a different data type`;case oe.WritingToIncompatibleType:return`${ie(d.entity,d.entity.project)} writes data to a value of a different data type`;case oe.ScopeWithoutLogic:return`${ie(d.entity,d.entity.project)} has no logic`;case oe.NonStaticPropertyImplementsStatic:return`${ie(d.entity,d.entity.project)} has a static property in a non-static entity`;case oe.PropertyImplementsIncompatibleType:return`${ie(d.entity,d.entity.project)} implements a property of a different data type`;case oe.PropertyImplementsNonAbstact:return`${ie(d.entity,d.entity.project)} implements a non-template property`;case oe.StaticPropertyImplementsNonStatic:return`${ie(d.entity,d.entity.project)} has a static property in a non-static entity`;case oe.VariableCallsOthersAndHasInternalCall:return`${ie(d.entity,d.entity.project)} calls other entities while being used to execute internal logic`;case oe.VariableHasInputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has inputs while being used to execute internal logic`;case oe.VariableHasOutputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has outputs while being used to execute internal logic`;case oe.VariableIsCalledAndHasInternalCall:return`${ie(d.entity,d.entity.project)} is called while being used to execute internal logic`;case ae.InternalCallDeclarationIsNotFunctionDeclaration:return`${ie(d.entity,d.entity.project)} has a declaration that is not an action`;case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has a declaration that is not found in ${(u=d.entity.parent.getDataType(null))!=null&&u.entity?ie((i=d.entity.parent.getDataType(null))==null?void 0:i.entity,d.entity.project):"the variable's data-type entity"}`;case ae.InternalCallParentDeclarationEntityInvalidType:return`${ie(d.entity,d.entity.project)} is part of a variable whos data-type entity can't have actions`;case ae.InternalCallParentMissingDataType:return`${ie(d.entity,d.entity.project)} is part of a variable with no data-type entity`;case ae.InternalCallDeclarationNotInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has a declaration doesn't belong to ${(a=d.entity.parent.getDataType(null))!=null&&a.entity?ie((l=d.entity.parent.getDataType(null))==null?void 0:l.entity,d.entity.project):"the variable's data-type entity"}`;case ae.UnreachableEntity:return`${ie(d.entity,d.entity.project)} is unreachable`;case oe.DisconnectedCallableEntity:return`${ie(d.entity,d.entity.project)} is disconnected and won't be executed by anything after publishing`;default:return`${ie(d.entity,d.entity.project)} Error: ${Dp(d.code)}`}}var oA=(d=>(d.ValuesAlreadyConnected="values-already-connected",d.CannotReadMoreThanOneValue="cannot-read-more-than-one-value",d.CannotReadValueFromChildren="cannot-read-value-from-children",d.CannotWriteValueToChildren="cannot-write-value-to-children",d.CannotBeCalledByChildren="cannot-be-called-by-children",d.ExecutionsAlreadyConnected="executions-already-connected",d.DataTypesNotCompatible="data-types-not-compatible",d.CannotCallAncestor="cannot-call-ancestor",d.CannotWriteValueToAncestor="cannot-write-value-to-ancestor",d.NotInScope="not-in-scope",d.IsNotValueWrittingEntity="is-not-value-writting-entity",d.IsNotValueReadingEntity="is-not-value-reading-entity",d.ContinueOrBreakStatementCalledFromOutsideLoop="continue-or-break-statement-called-from-outside-loop",d.ElementInLoopBodyCallingOutsideLoop="element-in-loop-body-calling-outside-loop",d.CallerIsInHigherScope="caller-is-in-higher-scope",d.CallerIsInLowerScope="caller-is-in-lower-scope",d.CallIsInHigherScope="call-is-in-higher-scope",d.CallIsInLowerScope="call-is-in-lower-scope",d.OtherIncompatibleScopeReason="other-incompatible-scope-reason",d))(oA||{});const Wme=Object.values(oA);var lA=(d=>(d.NotPartOfOngoingTest="not-part-of-ongoing-test",d.CannotBeAddedToTest="cannot-be-added-to-test",d))(lA||{});const Hme=Object.values(lA);var dA=(d=>(d.Suggestion="suggestion",d.CanvasGloballyDisabled="canvas-globally-disabled",d.CannotInteractWithInputInVariableWithInternalCalls="cannot-interact-with-input-in-variable-with-internal-calls",d.CannotInteractWithOutputInVariableWithInternalCalls="cannot-interact-with-output-in-variable-with-internal-calls",d))(dA||{});const Yme=Object.values(dA);function zme(d,u){const i=[...d,...u];return Array.from(new Set(i))}function Xme(d,u){const i=[...d,...u],a=Array.from(new Set(i));return{hasChanged:a.length!==d.length,reasons:a}}function Qme(d,u){const i=d.filter(l=>!u.includes(l));return{hasChanged:i.length!==d.length,reasons:i}}function e0e(d,u){return d.find(i=>i.entity.id===u)||null}function oF(d){return d.filter((u,i)=>d.indexOf(u)===i)}class ti{constructor(u,i,a=null,l){D(this,"ids",[]);D(this,"entity");D(this,"entityCardHeight");D(this,"entityCardWidth");D(this,"index");D(this,"childEntities",[]);D(this,"children",[]);D(this,"parents",[]);D(this,"calculationEntryPoint");D(this,"_onlyEntities",null);D(this,"_changeSet",null);if(this.index=i,this.entity=u,this.calculationEntryPoint=a||this,this===this.calculationEntryPoint&&!l)throw new Error("Change set must be provided for the calculation entry point");this.calculateCardSize(),this.getSortedChildren()}static autoGenerateLayout(u,i,a){const l=iF-aA-eF,p=sF-Ny-sA;u.metaSync({x:u.x||l,y:u.y||p},i);const t=new ti(u,0,null,i);t._onlyEntities=a||[],t.ids=["0"];const y=[];t.next(T=>{y.push(...T)}),ti.recursivelyAssembleChildrenAreas(y),t.resolveChildrenOverlaps();const v=t.flattenChildEntities();return t._onlyEntities?v.filter(T=>(t._onlyEntities||[]).includes(T)):v}static recursivelyAssembleChildrenAreas(u){const i=[];u.forEach(a=>{a.next(l=>{i.push(...l)})}),i.length>0&&ti.recursivelyAssembleChildrenAreas(i)}get onlyEntities(){return this.calculationEntryPoint._onlyEntities}get changeSet(){return this.calculationEntryPoint._changeSet}set changeSet(u){this.calculationEntryPoint._changeSet=u}findAreaInChildrenFromEntity(u){if(this.entity===u)return this;const i=this.children.find(l=>l.entity===u);return i||this.children.reduce((l,p)=>l||p.findAreaInChildrenFromEntity(u),null)}findAreaFromEntity(u){if(this.entity===u)return this;const i=this.calculationEntryPoint.children,a=i.find(p=>p.entity===u);return a||i.reduce((p,t)=>p||t.findAreaInChildrenFromEntity(u),null)}addParent(u){if(!this.parents.includes(u)){const i=ti.resolveIds(u,this.index);this.ids.push(...i),this.parents.push(u)}}static resolveIds(u,i){return u?u.ids.map(a=>`${a}-${i}`):[`${i}`]}getSortedChildren(){if(this.entity.collapsed){this.childEntities=[];return}const u=sn(this.entity,!0);if(this.entity.type===f.Project){const i=[],a=[],l=[];u.forEach(t=>{if(f.DefinitionEntity===t.type){a.push(t);return}else if(Ht.includes(t.type)){l.push(t);return}i.push(t)});const p=i.sort((t,y)=>{const v=!!Sy(t,y).length,T=sn(t),w=sn(y);return v?0:T.length&&!w.length?-1:!T.length&&w.length?1:0}).filter(t=>!Qa(t).length);this.childEntities=[...a,...l,...p]}else{const i=[],a=[],l=[],p=[],t=[];Rs.includes(this.entity.type)&&Zy(this.entity).forEach(T=>{if(st.includes(T.type)){l.push(T);return}const w=rr(T);i.push(w)}),wr.includes(this.entity.type)&&a.push(...this.entity.detachedChildren);const y=u.filter(v=>{const T=i.includes(v);return T||l.includes(v)||a.includes(v)?!1:st.includes(v.type)?(l.push(v),!1):ws.includes(v.type)&&!T?(p.push(v),!1):v.type===f.DefinitionEntity?(t.push(v),!1):!0});i.sort((v,T)=>il(v,T)?-1:0),p.sort((v,T)=>il(v,T)?-1:0),l.sort((v,T)=>CA(v,T)?1:CA(T,v)?-1:0),this.childEntities=[...t,...i,...p,...y,...l,...a]}}calculateCardSize(){const u=aF(this.entity);this.entityCardWidth=u.width,this.entityCardHeight=u.height}static getBoundriesOfTwoAreas(u,i){return{top:Math.min(u.top,i.top),left:Math.min(u.left,i.left),bottom:Math.max(u.bottom,i.bottom),right:Math.max(u.right,i.right)}}static getBoundriedOfCombinedAreas(u,i){const a=u.filter(p=>!i.includes(p));return a.reduce((p,t)=>i.includes(t)?p:ti.getBoundriesOfTwoAreas(p,t.fullBranchArea),a[0].fullBranchArea)}getFullAreaUntilAny(u){const i=this.ownEntityPlusBufferArea;return this.children.filter(t=>!u.includes(t)).map(t=>t.getFullAreaUntilAny(u)).reduce((t,y)=>ti.getBoundriesOfTwoAreas(t,y),i)}getFullAreaUntilAreaOrAnyChildren(u){const i=[u,...u.flattenChildren()],a=this.ownEntityPlusBufferArea;return this.children.filter(t=>i.includes(t)).map(t=>t.getFullAreaUntil(u)).reduce((t,y)=>ti.getBoundriesOfTwoAreas(t,y),a)}getFullAreaUntil(u){const i=this.ownEntityPlusBufferArea;return this.children.filter(p=>p!==u).map(p=>p.getFullAreaUntil(u)).reduce((p,t)=>ti.getBoundriesOfTwoAreas(p,t),i)}get fullBranchArea(){const u=this.ownEntityPlusBufferArea;return this.children.map(l=>l.fullBranchArea).reduce((l,p)=>ti.getBoundriesOfTwoAreas(l,p),u)}get ownEntityArea(){return{top:this.entity.y,left:this.entity.x,bottom:this.entity.y+this.entityCardHeight,right:this.entity.x+this.entityCardWidth}}get ownEntityPlusBufferArea(){const u=this.ownEntityArea;return{top:u.top,left:u.left,bottom:u.bottom+Ny,right:u.right+aA}}static filterOutRepeatedAreas(u){return u.filter((i,a)=>u.indexOf(i)===a)}getEarliestId(u,i){const a=u.split("-"),l=i.split("-");return a.length<l.length?u:a.length>l.length?i:a.reduce((t,y,v)=>y<l[v]?u:i,u)}getEarliestLevel(){return this.ids.reduce((a,l)=>this.getEarliestId(a,l),this.ids[0]).split("-").length}countColumns(){let u=0;if(this!==this.calculationEntryPoint)u++;else return u;if(!this.parents.length)return u;const a=this.parents.reduce((l,p)=>p.getEarliestLevel()>l.getEarliestLevel()?p:l,this.parents[0]).countColumns();return u+=a,u}getLatestId(u,i){if(u===i)return u;const a=u.split("-"),l=i.split("-");return a.length<l.length?i:a.length>l.length?u:a.reduce((t,y,v)=>y>l[v]?u:i,u)}getLatestLevel(){return this.ids.length===1?this.ids[0].split("-").length:this.ids.reduce((a,l)=>this.getLatestId(a,l),this.ids[0]).split("-").length}smoothPosition(){const u=this.flattenSiblings();if(!u.length&&this.parents.length<=1&&this.children.length){const i=this.centerHeaderVerticallyOverCombinedAllChildrenHeaderHeight();this.parents.forEach(a=>{a!==this.calculationEntryPoint&&a.shiftDownAlone(i)})}else if([...Ht].includes(this.entity.type)&&this.children.length)this.centerHeaderVerticallyOverCombinedAllChildrenHeaderHeight();else if(!this.children.length&&this.parents.length>1){const i=u.filter(a=>!this.parents.includes(a));i.length?i.every(l=>{const p=this.countColumns(),t=l.countColumns();return p>t})&&this.centerHeaderVerticallyOverCombinedAllParentsHeaderHeight():i.length||this.centerHeaderVerticallyOverCombinedAllParentsHeaderHeight()}}shiftDownUntilAny(u,i){if(u.includes(this))return u;this.move(this.entity,{y:this.entity.y+i});let a=[...u,this];return this.children.forEach(l=>{if(ti.getEarliestParentInChain(l)!==this)return;const t=e0e(a,l.entity.id);a=ti.filterOutRepeatedAreas([...a]),t||(a=a.filter(v=>v!==l));const y=l.shiftDownUntilAny(a,i);a.push(...y)}),a}shiftRightUntilAny(u,i){u.includes(this)||(this.move(this.entity,{x:this.entity.x+i}),this.children.forEach(a=>{const l=ti.filterOutRepeatedAreas([...this.flattenSiblings(),...u]);ti.getEarliestParentInChain(a)===this&&a.shiftRightUntilAny(l,i)}))}shiftRight(u){this.move(this.entity,{x:this.entity.x+u}),this.children.forEach(i=>{const l=i.flattenSiblings().filter(p=>p!==i);i.shiftRightUntilAny(l,u)})}shiftDownAlone(u){this.move(this.entity,{y:this.entity.y+u})}centerHeaderVerticallyOverCombinedAllParentsHeaderHeight(){const u=this.parents.reduce((l,p)=>{const t=p.ownEntityArea,y=t.top+Od,v={top:y,left:t.left,bottom:y,right:t.right};return ti.getBoundriesOfTwoAreas(l,v)},{top:1/0,left:1/0,bottom:-1/0,right:-1/0}),a=(u.bottom-u.top)/2-Od;this.shiftDownAlone(a)}centerHeaderVerticallyOverCombinedAllChildrenHeaderHeight(){const u=this.children.reduce((l,p)=>{const t=p.ownEntityArea,y=t.top+Od,v={top:y,left:t.left,bottom:y,right:t.right};return ti.getBoundriesOfTwoAreas(l,v)},{top:1/0,left:1/0,bottom:-1/0,right:-1/0}),a=(u.bottom-u.top)/2-Od;return this.shiftDownAlone(a),a}resolveChildrenOverlaps(){const u=this.flattenChildren();let i=[];u.forEach(a=>{const l=a.adjustVerticallyToAvoidOverlaps();i.push(...l)}),u.forEach(a=>{a.smoothPosition()})}static getEarliestParentInChain(u){let i=u.parents[0];return u.parents.length&&(i=u.parents.sort((a,l)=>{if(!a.ids.length)return-1;if(!l.ids.length)return 1;const p=a.ids.sort((y,v)=>y.length<v.length?-1:0),t=l.ids.sort((y,v)=>y.length<v.length?-1:0);return p[0].length-t[0].length})[0]),i}flattenEarlierSiblings(u=new Set){return u.add(this.entity.id),this.parents.reduce((a,l)=>{if(u.has(l.entity.id))return a;u.add(l.entity.id);const t=l.children.slice(0,l.children.indexOf(this)).reduce((y,v)=>[...y,v,...v.flattenChildren(u)],[]);return[...a,...t]},[])}flattenSiblings(u=new Set){return u.add(this.entity.id),this.parents.reduce((a,l)=>{if(u.has(l.entity.id))return a;u.add(l.entity.id);const t=l.children.filter(y=>y!==this).reduce((y,v)=>[...y,v,...v.flattenChildren(u)],[]);return[...a,...t]},[])}flattenChildren(u=new Set){return this.children.reduce((i,a)=>u.has(a.entity.id)?i:(u.add(a.entity.id),[...i,a,...a.flattenChildren(u)]),[])}flattenParents(u=new Set){return this.parents.reduce((a,l)=>u.has(l.entity.id)?a:(u.add(l.entity.id),[...a,l,...l.flattenParents(u)]),[])}getAreaIfRendered(u){return this.calculationEntryPoint.flattenChildren().find(l=>l.entity.id===u.id)||null}getLowerSiblings(){const u=this.parents.reduce((i,a)=>{const l=a.children.indexOf(this),p=a.children.slice(l+1);return[...i,...p]},[]);return oF(u)}getLowerAreas(){const u=this.getLowerSiblings(),i=this.parents.reduce((a,l)=>[...a,...l.getLowerAreas()],[]);return oF([...u,...i])}adjustVerticallyToAvoidOverlaps(u=[]){const a=ti.getEarliestParentInChain(this).children[this.index-1];if(!a)return u;const l=this.flattenEarlierSiblings(),p=this.flattenParents(),t=[...l,...p,a],T=R(t.flatMap(N=>Sy(this.entity,N.entity))).filter(N=>N.id!==this.entity.id).map(N=>this.findAreaFromEntity(N)).filter(N=>!!N),w=this.getFullAreaUntilAny(T),A=a.getFullAreaUntilAny(T),V=t.reduce((N,j)=>j===this||j.fullBranchArea.left!==w.left?N:Math.max(N,j.fullBranchArea.bottom),A.bottom);if(w.top<V){const N=V-w.top+Ny;return this.shiftDownUntilAny(u,N)}return u}move(u,i){(this.onlyEntities||[]).includes(u)&&u.metaSync(i,this.changeSet)}addChild(u){const i=this.childEntities[u];let a=null;i.x&&i.y?a=this.getAreaIfRendered(i):!i.x&&!i.y&&this.move(i,{x:this.entity.x,y:this.entity.y}),a||(a=new ti(i,u,this.calculationEntryPoint));const l=this.ownEntityPlusBufferArea;this.children.includes(a)||(this.children.push(a),a.addParent(this));const p=a.fullBranchArea;if(p.left<l.right){const t=l.right-p.left;a.shiftRight(t)}return a}flattenChildEntities(u=new Set){return this.children.reduce((i,a)=>u.has(a.entity.id)?i:(u.add(a.entity.id),[...i,a.entity,...a.flattenChildEntities(u)]),[])}next(u){const i=[];this.childEntities.forEach((a,l)=>{const p=this.addChild(l);p&&i.push(p)}),u(i)}}var Op=(d=>(d.Amazon="amazon",d.Google="google",d.Microsoft="microsoft",d))(Op||{}),$r=(d=>(d.RelationalDatabase="relational-database",d.CompiledLocalCodebase="compiled-local-codebase",d.CloudHostedCodebase="cloud-hosted-codebase",d.HttpApi="http-api",d.HttpEndpoint="http-endpoint",d.ServerlessFunction="serverless-function",d))($r||{}),uA=(d=>(d.Post="post",d.Get="get",d.Acknowledgement="acknowledgment",d.Progress="progress",d.Error="error",d.Complete="complete",d))(uA||{}),rl=(d=>(d.Queued="queued",d.Running="running",d.Success="success",d.Failed="failed",d.CleanedUp="cleaned-up",d.Skipped="skipped",d.AbortedByUser="aborted-by-user",d.UnrecoverableFailure="unrecoverable-failure",d.Reverted="reverted",d.UnpublishingStarted="unpublishing-started",d.Unpublished="unpublished",d))(rl||{}),cA=(d=>(d.Queued="queued",d.Running="running",d.Success="success",d.Failed="failed",d.CleanedUp="cleaned-up",d.UnrecoverableFailure="unrecoverable-failure",d.Reverted="reverted",d.UnpublishingStarted="unpublishing-started",d.Unpublished="unpublished",d))(cA||{}),Qe=(d=>(d.ProjectNotFound="project-not-found",d.ProjectPublishRequestAcknowledged="project-publish-request-acknowledged",d.PublicationStepFailedReasonUnknown="publication-step-failed-reason-unknown",d.DeploymentCompleted="deployment-completed",d.DeploymentStarted="deployment-started",d.DeploymentFailed="deployment-failed",d.AllInfrastructureSuccessfullyProvisioned="all-infrastucture-successfully-provisioned",d.RequestPayloadValidationFailed="request-payload-validation-failed",d.ProjectStateValidationFailedMissingName="project-state-validation-failed-missing-name",d.ProjectStateValidationFailedMissingAnyFunctionality="project-state-validation-failed-missing-any-functionality",d.ProjectAlreadyBeingPublished="project-already-being-published",d.BillingSubscriptionUpdateFailed="billing-subscription-update-failed",d.RelationalDatabaseDeploymentStarted="relational-database-deployment-started",d.RelationalDatabaseDeploymentCompleted="relational-database-deployment-completed",d.RelationalDatabaseDeploymentFailed="relational-database-deployment-failed",d.CreatingNewRelationalDatabase="creating-new-relational-database",d.WaitingForPreviousRelationalDatabaseDeployment="waiting-for-previous-relationa-database-deployment",d.RelationalDatabaseAlreadyExists="relational-database-already-exists",d.RelationalDatabaseDeletionStarted="relational-database-deletion-started",d.RelationalDatabaseDeletionCompleted="relational-database-deletion-completed",d.RelationalDatabaseDeletionFailed="relational-database-deletion-failed",d.WaitingForPreviousRelationalDatabaseDeletion="waiting-for-previous-relationa-database-deletion",d.HttpApiDeploymentStarted="http-api-deployment-started",d.HttpApiDeploymentCompleted="http-api-deployment-completed",d.HttpApiDeploymentFailed="http-api-deployment-failed",d.CreatingNewHttpApi="creating-new-http-api",d.HttpApiAlreadyExists="http-api-already-exists",d.HttpApiDeletionStarted="http-api-deletion-started",d.HttpApiDeletionCompleted="http-api-deletion-completed",d.HttpApiDeletionFailed="http-api-deletion-failed",d.WaitingForPreviousHttpApiDeletion="waiting-for-previous-http-api-deletion",d.BusinessLogicCodebaseDeploymentStarted="business-logic-codebase-deployment-started",d.BusinessLogicCodebaseDeploymentCompleted="business-logic-codebase-deployment-completed",d.BusinessLogicCodebaseDeploymentFailed="business-logic-codebase-deployment-failed",d.BundlingCodebaseForDownload="bundling-codebase-for-download",d.UploadingCodebaseToCloudStorage="uploading-codebase-to-cloud-storage",d.UploadingCodebaseToCloudStorageCompleted="uploading-codebase-to-cloud-storage-completed",d.UploadingCodebaseToCloudStorageFailed="uploading-codebase-to-cloud-storage-failed",d.InfrastructureValuesCodebaseInterpolationStarted="infrastructure-values-codebase-interpolation-started",d.InfrastructureValuesCodebaseInterpolationCompleted="infrastructure-values-codebase-interpolation-completed",d.InfrastructureValuesCodebaseInterpolationFailed="infrastructure-values-codebase-interpolation-failed",d.CodeCompilationStarted="code-compilation-started",d.CodeCompilationCompleted="code-compilation-completed",d.CodeCompilationFailed="code-compilation-failed",d.BundleCodebaseStarted="bundle-codebase-started",d.BundleCodebaseCompleted="bundle-codebase-completed",d.BundleCodebaseFailed="bundle-codebase-failed",d.InstallingCodebaseDependenciesStarted="installing-codebase-dependencies-started",d.InstallingCodebaseDependenciesCompleted="installing-codebase-dependencies-completed",d.InstallingCodebaseDependenciesFailed="installing-codebase-dependencies-failed",d.MigrateRelationalDatabaseStarted="migrate-relational-database-started",d.MigrateRelationalDatabaseCompleted="migrate-relational-database-completed",d.MigrateRelationalDatabaseFailed="migrate-relational-database-failed",d))(Qe||{}),rn=(d=>(d.CodeCompilation="code-compilation",d.RelationalDatabaseDeployment="relational-database-deployment",d.RelationalDatabaseDeletion="relational-database-deletion",d.HttpApiDeployment="http-api-deployment",d.HttpApiDeletion="http-api-deletion",d.InfrastructureValuesCodebaseInterpolation="infrastructure-values-codebase-interpolation",d.BundleCodebase="bundle-codebase",d.MigrateRelationalDatabase="migrate-relational-database",d.BusinessLogicCodebaseDeployment="business-logic-codebase-deployment",d.CodebaseCleanup="codebase-cleanup",d))(rn||{});$r.CloudHostedCodebase,$r.HttpApi,$r.RelationalDatabase,$r.CloudHostedCodebase,$r.CloudHostedCodebase,$r.RelationalDatabase,$r.CloudHostedCodebase,$r.CloudHostedCodebase;function lF(d){return`project-${d}-http-api`}function dF(d){return`entity-${d}-database`}class uF{constructor(u,i,a,l,p,t,y,v,T){D(this,"stepType");D(this,"id");D(this,"resourceType");D(this,"index");D(this,"dependency",[]);D(this,"lastEvent",null);D(this,"lasEventTimestamp",null);D(this,"status",rl.Queued);D(this,"publicationRun");D(this,"resource");this.stepType=u,this.id=i,this.resourceType=a,this.status=l,this.dependency=p,this.index=t,this.lasEventTimestamp=y,this.publicationRun=v,this.resource=T}toJSON(){return{stepType:this.stepType,id:this.id,resourceType:this.resourceType,index:this.index,status:this.status,dependency:this.dependency,lastEvent:this.lastEvent,resource:{resourceId:this.resource.resourceId,resourceType:this.resource.resourceType,provider:this.resource.provider,details:this.resource.details,status:this.resource.status,name:this.resource.name}}}async update(u){var i,a;this.status=u.status,this.dependency=u.dependency,this.index=u.index,this.stepType=u.stepType,this.resourceType=u.resourceType,this.lastEvent=u.lastEvent,this.id=u.id,(a=this.resource)==null||a.setDetails((i=u.resource)==null?void 0:i.details)}}var cF=(d=>(d.Ready="ready",d.Provisioning="provisioning",d.Queued="queued",d.ProvisioningFailed="provisioning-failed",d.Deleting="deleting",d.DeletingFailed="deleting-failed",d.Deleted="deleted",d))(cF||{});class pA{constructor(u,i,a){D(this,"provisionedBy");D(this,"publicationRun");D(this,"resourceType");D(this,"provider");D(this,"resourceId");D(this,"details",null);D(this,"name",null);D(this,"status","queued");this.publicationRun=u,this.resourceType=i,this.provider=a}setDetails(u){this.details=u}setStatus(u){this.status=u}setProvisionedBy(u){this.provisionedBy=u}}class fA extends pA{constructor(i,a,l,p){super(i,l,p);D(this,"resourceType");D(this,"owners",new Map);D(this,"details",null);D(this,"status","queued");a.forEach(t=>{this.owners.set(t.id,t)}),this.resolveDeterministicResourceId()}resolveDeterministicResourceId(){var i,a;return this.resourceType===$r.HttpApi?this.resourceId=lF(this.publicationRun.project.id):this.resourceType===$r.RelationalDatabase&&(this.resourceId=dF((a=(i=Array.from(this.owners.values()))==null?void 0:i[0])==null?void 0:a.id)),this.resourceId}}class hA extends pA{constructor(i,a,l){super(i,a,l);D(this,"resourceType");D(this,"details",null);D(this,"status","queued");this.resolveDeterministicResourceId()}resolveDeterministicResourceId(){return this.resourceType===$r.CompiledLocalCodebase?this.resourceId=`compiled-codebase--${this.publicationRun.project.id}--${this.publicationRun.project.version}--${this.publicationRun.id}`:this.resourceType===$r.CloudHostedCodebase&&(this.resourceId=`cloud-hosted-codebase--${this.publicationRun.project.id}--${this.publicationRun.project.version}`),this.resourceId}}class t0e{constructor(u,i){D(this,"id");D(this,"projectAutoIncrementPublicationCount");D(this,"projectPublishedSemanticVersion");D(this,"projectVersion");D(this,"projectId");D(this,"cloudProvider");D(this,"triggeredBy");D(this,"createdAt");D(this,"updatedAt");D(this,"status");D(this,"steps",[]);D(this,"editor");D(this,"explicitResources",new Map);D(this,"implicitGlobalResources",new Map);D(this,"finalGlobalEvent",null);D(this,"finalStatus",null);this.id=u.id,this.projectAutoIncrementPublicationCount=u.projectAutoIncrementPublicationCount,this.projectPublishedSemanticVersion=u.projectPublishedSemanticVersion,this.projectVersion=u.projectVersion,this.projectId=u.projectId,this.cloudProvider=u.cloudProvider,this.triggeredBy=u.triggeredBy,this.createdAt=u.createdAt,this.updatedAt=u.updatedAt,this.status=u.status,this.editor=i}get project(){return this.editor.project}getInfraTypes(u){return this.steps.filter(i=>u.includes(i.resourceType))}getStepsTypes(u){return this.steps.filter(i=>u.includes(i.stepType))}toIds(u){return u.map(i=>i.id)}getResourceForEntity(u){const i=Array.from(this.explicitResources.values()).find(a=>a.owners.has(u.id));return i||null}async init(){await this.initResources()}async initResources(){this.implicitGlobalResources.set($r.CompiledLocalCodebase,new hA(this,$r.CompiledLocalCodebase,Op.Amazon)),this.implicitGlobalResources.set($r.CloudHostedCodebase,new hA(this,$r.CloudHostedCodebase,Op.Amazon));const u=this.project.entities.filter(a=>Qi(a,Ce.HTTP_ENDPOINT)),i=this.project.entities.filter(a=>Qi(a,Ce.RELATIONAL_DATABASE));if(i.length&&i.forEach(a=>{const l=new fA(this,[a],$r.RelationalDatabase,Op.Amazon);this.explicitResources.set(l.resourceId,l)}),u.length){const a=new fA(this,u,$r.HttpApi,Op.Amazon);this.explicitResources.set(a.resourceId,a)}}setSteps(u,i){u.forEach(a=>{this.addStep(a,i)}),this.editor.events.emit(Qe.ProjectPublishRequestAcknowledged,{})}addStep(u,i){const a=u.dependency||[];if(a.length){const p=a.filter(t=>!this.steps.find(y=>y.id===t));if(p.length)throw new Error(`Missing dependencies: ${p.join(", ")}`)}if(!u.resource)throw new Error(`Resource not found for step ${u.stepType} (${u.id})`);if(!this.steps.find(p=>p.id===u.id)){const p=this.implicitGlobalResources.get(u.resourceType)||this.explicitResources.get(u.resource.resourceId),t=new uF(u.stepType,u.id,u.resourceType,u.status,a,u.index,i,this,p);this.steps.push(t)}}onUpdate(u){var i;if(console.log("onUpdate",u),(i=u.payload)!=null&&i.stepType){const a=this.steps.find(l=>{var p;return l.id===((p=u.payload)==null?void 0:p.id)});a&&L(u.emittedAt).isAfter(L(a.lasEventTimestamp))&&a.update(u.payload)}this.editor.events.emit("publication-updated",{}),u.type===uA.Error?(this.finalStatus=cA.Failed,this.finalGlobalEvent=u.event,this.editor.events.emit("project-publication-error",u)):u.type===uA.Complete&&(this.finalStatus=cA.Success,this.finalGlobalEvent=u.event,this.editor.events.emit("project-publication-completed",u))}}function r0e(d){switch(d){case rn.CodeCompilation:return"Code generation";case rn.RelationalDatabaseDeployment:return"Database creation";case rn.HttpApiDeployment:return"HTTP gateway creation";case rn.InfrastructureValuesCodebaseInterpolation:return"Link code with resources";case rn.BundleCodebase:return"Bundle code";case rn.MigrateRelationalDatabase:return"Database structure migration";case rn.BusinessLogicCodebaseDeployment:return"Update servers with new code";case rn.CodebaseCleanup:return"Code cleanup";case rn.HttpApiDeletion:return"HTTP gateway deletion";case rn.RelationalDatabaseDeletion:return"Database deletion";default:return"Publication finished"}}function i0e(d){switch(d){case Qe.DeploymentCompleted:return"Successfully published";case Qe.DeploymentStarted:return"Publication started";case Qe.DeploymentFailed:return"Publication failed";case Qe.AllInfrastructureSuccessfullyProvisioned:return"All infrastructure successfully provisioned";case Qe.RequestPayloadValidationFailed:return"Request payload validation failed";case Qe.ProjectStateValidationFailedMissingName:return"Project state validation failed: missing name";case Qe.ProjectStateValidationFailedMissingAnyFunctionality:return"Project state validation failed: missing any functionality";case Qe.RelationalDatabaseDeploymentStarted:return"Database creation started";case Qe.RelationalDatabaseDeploymentCompleted:return"Database creation completed";case Qe.RelationalDatabaseDeploymentFailed:return"Database creation failed";case Qe.CreatingNewRelationalDatabase:return"Creating new database (up to 5 mins)";case Qe.WaitingForPreviousRelationalDatabaseDeployment:return"Waiting for previous database creation";case Qe.RelationalDatabaseAlreadyExists:return"Database already exists";case Qe.HttpApiDeploymentStarted:return"HTTP gateway creation started";case Qe.HttpApiDeploymentCompleted:return"HTTP gateway creation completed";case Qe.HttpApiDeploymentFailed:return"HTTP gateway creation failed";case Qe.CreatingNewHttpApi:return"Creating new HTTP gateway";case Qe.HttpApiAlreadyExists:return"HTTP gateway already exists";case Qe.BusinessLogicCodebaseDeploymentStarted:return"Update servers with new code started";case Qe.BusinessLogicCodebaseDeploymentCompleted:return"Update servers with new code completed";case Qe.BusinessLogicCodebaseDeploymentFailed:return"Update servers with new code failed";case Qe.BundlingCodebaseForDownload:return"Bundling code for download";case Qe.UploadingCodebaseToCloudStorage:return"Uploading code to cloud storage";case Qe.InfrastructureValuesCodebaseInterpolationStarted:return"Linking code with resources started";case Qe.InfrastructureValuesCodebaseInterpolationCompleted:return"Linking code with resources completed";case Qe.InfrastructureValuesCodebaseInterpolationFailed:return"Linking code with resources failed";case Qe.CodeCompilationStarted:return"Code generation started";case Qe.CodeCompilationCompleted:return"Code generation completed";case Qe.CodeCompilationFailed:return"Code generation failed";case Qe.BundleCodebaseStarted:return"Code bundling started";case Qe.BundleCodebaseCompleted:return"Code bundling completed";case Qe.BundleCodebaseFailed:return"Code bundling failed";case Qe.InstallingCodebaseDependenciesStarted:return"Installing code dependencies";case Qe.InstallingCodebaseDependenciesCompleted:return"Installing code dependencies completed";case Qe.InstallingCodebaseDependenciesFailed:return"Installing code dependencies failed";case Qe.MigrateRelationalDatabaseStarted:return"Database structure migration started";case Qe.MigrateRelationalDatabaseCompleted:return"Database structure migration completed";case Qe.MigrateRelationalDatabaseFailed:return"Database structure migration failed";case Qe.ProjectAlreadyBeingPublished:return"Project already being published. You need to wait for the previous publication to complete";case Qe.ProjectPublishRequestAcknowledged:return"Project publish request acknowledged";case Qe.UploadingCodebaseToCloudStorageCompleted:return"Uploading code to cloud storage completed";case Qe.UploadingCodebaseToCloudStorageFailed:return"Uploading code to cloud storage failed";case Qe.BillingSubscriptionUpdateFailed:return"Billing subscription update failed";case Qe.ProjectNotFound:return"Project not found";case Qe.HttpApiDeletionCompleted:return"HTTP gateway deletion completed";case Qe.HttpApiDeletionFailed:return"HTTP gateway deletion failed";case Qe.HttpApiDeletionStarted:return"HTTP gateway deletion started";case Qe.PublicationStepFailedReasonUnknown:return"Publication step failed: reason unknown";case Qe.WaitingForPreviousHttpApiDeletion:return"Waiting for previous HTTP gateway deletion";case Qe.RelationalDatabaseDeletionStarted:return"Database deletion started";case Qe.RelationalDatabaseDeletionCompleted:return"Database deletion completed";case Qe.RelationalDatabaseDeletionFailed:return"Database deletion failed";case Qe.WaitingForPreviousRelationalDatabaseDeletion:return"Waiting for previous database deletion"}return"Unknown event"}var pF=(d=>(d.NO_LOGIC="NO_LOGIC",d.NO_NAME="NO_NAME",d.NO_CHANGES="NO_CHANGES",d.PROJECT_PUBLICATION_ALREADY_ONGOING="PROJECT_PUBLICATION_ALREADY_ONGOING",d))(pF||{});function s0e(d){switch(d){case"NO_LOGIC":return"This project has no logic";case"NO_NAME":return"This project has no name";case"NO_CHANGES":return"This version has already been published";case"PROJECT_PUBLICATION_ALREADY_ONGOING":return"This project is already being published";default:return"Publishing is currently not available. Try again later"}}function n0e(d){switch(d){case $r.RelationalDatabase:return"Relational database";case $r.HttpEndpoint:case $r.HttpApi:return"HTTP endpoints";case $r.ServerlessFunction:case $r.CloudHostedCodebase:return"Server code functions";default:return"Resources"}}function a0e(d){switch(d){case rl.Running:return"In progress";case rl.Failed:return"Failed";case rl.Success:return"Succeeded";case rl.Skipped:return"Skipped";case rl.Queued:default:return"Queued"}}function o0e(d,u){let i=null;const a=[];if(!d.id)i={...d,id:P.UUID.uuid()};else if(!MU(d.id)){const y=P.UUID.uuid();i={...d,id:y},a.push(new ee({id:`${d.id}--${q.InvalidUUIDStringFormat}`,message:`Entity with id "${d.id}" has an invalid UUID string format. The 'id' property must be a valid UUID string.
|
|
203
|
+
${On({describe_entity:y.error.id})}`,issue:null}))),{errors:p,modifiedData:l}}validateGeneratedUpdate(i){return{errors:[],modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){var i,a,l;return(l=(a=(i=this.dataType)==null?void 0:i.entity)==null?void 0:a.unsubscribeDependents)==null||l.call(a,[{entity:this,field:"data-type-entity"}]),this}subscribeToDependencies(){var i,a,l;return(l=(a=(i=this.dataType)==null?void 0:i.entity)==null?void 0:a.subscribeDependents)==null||l.call(a,[{entity:this,field:"data-type-entity"}]),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new Pt(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.defaultValue=this.defaultValue,i.dataType=this.dataType,i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new Pt(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.defaultValue=y.defaultValue,this.dataType=y.dataType,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&(this.removeFromParent(a),this.parent=null),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);return this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);return{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];return this.initialized=!0,this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){var y,v,T,w,A,V,N,j;const a=[this],l=[],p=[],t=[];return this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument?((y=this.parent)==null?void 0:y.type)===f.Search||((v=this.parent)==null?void 0:v.type)===f.Loop?(this.parent.addInputDeclaration(this,i),t.push(this.parent)):((w=(T=this.parent)==null?void 0:T.addInput)==null||w.call(T,this,i),a.push(this.parent)):this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((A=this.parent)==null?void 0:A.type)===f.Search||((V=this.parent)==null?void 0:V.type)===f.Loop?(this.parent.addOutputDeclaration(this,i),t.push(this.parent)):((j=(N=this.parent)==null?void 0:N.addOutput)==null||j.call(N,this,i),a.push(this.parent)):this.parentRelationType===le.ReturnedError&&this.parent&&(this.parent.error=this,t.push(this.parent)),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.initialData.defaultValue&&(this.defaultValue=te(this.initialData.defaultValue,this.project),this.defaultValue.setParent(this,null),this.defaultValue.initChildren(i)),this.initialData.dataType&&(this.dataType=te(this.initialData.dataType,this.project),this.dataType.setParent(this,null),this.dataType.initChildren(i)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.name=i.name!==void 0?i.name:p.name,this.codeName=i.codeName!==void 0?i.codeName:p.codeName,this.description=i.description!==void 0?i.description:p.description,this.index=i.index||(i.index!==0?p.index:0),this.required=i.required!==void 0?i.required:this.required,this.parentRelationType=i.parentRelationType!==void 0?i.parentRelationType:this.parentRelationType,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await Pt.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await Pt.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await Pt.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await Pt.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await Pt.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await Pt.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){var y,v,T,w,A,V,N;const a=[],l=[],p=[],t=[];return this.parent&&(((y=this.parent)==null?void 0:y.type)===f.Search?this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((v=this.parent)==null||v.removeOutputDeclaration(this,i),t.push(this.parent)):this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument?((T=this.parent)==null||T.removeInputDeclaration(this,i),t.push(this.parent)):this.parentRelationType===le.ReturnedError&&(this.parent.error=null,t.push(this.parent)):((w=this.parent)==null?void 0:w.type)===f.Loop?this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((A=this.parent)==null||A.removeOutputDeclaration(this,i),t.push(this.parent)):this.parentRelationType===le.ReturnedError&&(this.parent.error=null,t.push(this.parent)):this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?((V=this.parent)==null||V.removeOutput(this,i),t.push(this.parent)):(this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument)&&((N=this.parent)==null||N.removeInput(this,i),t.push(this.parent))),i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){const l=[],p=[],t=[],y=[];if(Array.from(new Set([...Vs(),...this.project.getAllBuiltInIds()])).includes(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(T=>{const{updated:w,removed:A,added:V}=T.entity.onDetachedDependencyRemoved(this,T.field,a);l.push(...w),p.push(...A),t.push(...V)}),this.defaultValue){const{updated:T,removed:w}=this.defaultValue.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(this.dataType){const{updated:T,removed:w}=this.dataType.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(!i){const T=this.removeFromParent(a);t.push(...T.added),l.push(...T.updated),p.push(...T.removed),y.push(...T.affected)}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){var y,v,T,w,A,V,N;const a=[],l=[],p=[],t=[];if(i!=null&&i.hasAdded(this.id))return i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(j=>{const{updated:k,removed:S,added:W}=j.entity.onDetachedDependencyRestored(this,j.field,i);l.push(...k),p.push(...S),a.push(...W)}),this.defaultValue){const{updated:j}=this.defaultValue.restore({},i);l.push(...j)}if(this.dataType){const{updated:j}=this.dataType.restore({},i);l.push(...j)}return((y=this.parent)==null?void 0:y.type)===f.Search?this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?(v=this.parent)==null||v.addOutputDeclaration(this,i):(this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument)&&((T=this.parent)==null||T.addInputDeclaration(this,i)):((w=this.parent)==null?void 0:w.type)===f.Loop?(this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn)&&((A=this.parent)==null||A.addOutputDeclaration(this,i)):this.parentRelationType===le.FixedReturns||this.parentRelationType===le.DynamicReturn?(V=this.parent)==null||V.addOutput(this,i):(this.parentRelationType===le.FixedArguments||this.parentRelationType===le.DynamicArgument)&&((N=this.parent)==null||N.addInput(this,i)),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this}}toFlat(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this,...((l=this.defaultValue)==null?void 0:l.toFlat(i))||[],...this.dataType?this.dataType.toFlat(i):[]])}toFlatIds(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.id,...((l=this.defaultValue)==null?void 0:l.toFlatIds(i))||[],...this.dataType?this.dataType.toFlatIds(i):[]])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,codeName:this.codeName,description:this.description,index:this.index,required:this.required,parentRelationType:this.parentRelationType,type:this.type,name:this.name}}toJSON(i=new Set){var a,l,p;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,codeName:this.codeName,description:this.description,index:this.index,required:this.required,defaultValue:((a=this.defaultValue)==null?void 0:a.toJSON(i))||null,parentRelationType:this.parentRelationType,dataType:((l=this.dataType)==null?void 0:l.toJSON(i))||null,parent:((p=this.parent)==null?void 0:p.toReference())||null})}toJSONClone(i=Le){var l,p,t,y,v,T,w,A;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:this.type,name:this.name,codeName:this.codeName,description:this.description,index:this.index,required:this.required,defaultValue:((T=this.defaultValue)==null?void 0:T.toJSONClone({...i,newId:null}))||null,parentRelationType:this.parentRelationType,dataType:((w=this.dataType)==null?void 0:w.toJSONClone({...i,newId:null}))||null,parent:((A=this.parent)==null?void 0:A.toReference({seenEntityMaps:i.seenEntityMaps}))||null})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l,p,t,y;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,codeName:this.codeName,description:this.description,index:this.index,required:this.required,parentRelationType:this.parentRelationType,defaultValue:((p=this.defaultValue)==null?void 0:p.toReference(i))||null,dataType:((t=this.dataType)==null?void 0:t.toReference(i))||null,parent:((y=this.parent)==null?void 0:y.toReference(i))||null}}toFlatJSON(i=new Set){var l;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...((l=this.defaultValue)==null?void 0:l.toFlatJSON(i))||[],...this.dataType?this.dataType.toFlatJSON(i):[]])}toGenerationTarget(){var i;return{id:this.id,name:this.name,codeName:this.codeName,description:this.description,type:this.type,required:this.required,parentRelationType:this.parentRelationType,parent:(i=this.parent)==null?void 0:i.id}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.defaultValue?this.defaultValue.toFlatGenerationTarget(i):[],...this.dataType?this.dataType.toFlatGenerationTarget(i):[]])}clearErrors(){var i,a;return this.errors=[],(i=this.defaultValue)==null||i.clearErrors(),(a=this.dataType)==null||a.clearErrors(),this}validate(){const i=Lx(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.dataType?this.dataType.getErrors():[]]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var N,j;if(Array.from(new Set([...Vs(),...this.project.getAllBuiltInIds()])).includes(this.id))return this;let y=gr(a,this);const v=l||P.UUID.uuid(),T=this.toJSON();T.id=v,T.version=P.UUID.uuid(),T.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),T.author=(i==null?void 0:i.author)||"1",T.previousVersion=null,T.deleted=!1;const w=St(T,y);a&&w.setParent(a,null),i==null||i.add(w,K.Added),p&&w.subscribe();const A=((N=this.dataType)==null?void 0:N.clone(i,w,P.UUID.uuid(),p))||null;A&&w.setDataType(A,i);const V=(j=this.defaultValue)==null?void 0:j.clone(i,w,P.UUID.uuid(),p);return w.defaultValue=V||null,i==null||i.attemptAutoclose("clone-entity",this.id),w}getDataType(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"get-data-type"))){return i==null||i.attemptAutoclose("get-data-type",this.id),this.dataType||null}setDataType(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-data-type"))){const l=this.dataType;return(l==null?void 0:l.id)!==(i==null?void 0:i.id)&&(l==null||l.remove({ignoreUpstream:!0},a),this.dataType=i,this.subscribeToDependencies(),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("set-data-type",this.id),this}getDefaultValue(){return this.defaultValue||null}setDefaultValue(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-default-value"))){const l=this.defaultValue;return(l==null?void 0:l.id)!==(i==null?void 0:i.id)&&(l==null||l.remove({ignoreUpstream:!0},a),this.defaultValue=i,a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("set-default-value",this.id),this}removeDataType(){return this.dataType=null,this}implementAsReturnDeclaration(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"implement-as-return-declaration")),a,l){const p=Ni.new(i);p.id=l||p.id,p.name=this.name,p.description=this.description,p.parent=a.toReference(),p.implements=this.toJSON(),p.isError=this.parentRelationType===le.ReturnedError;const t=St(p,this.project);if(t.hydrateAncestors(),t.addSelfToProject(i),i==null||i.add(t,K.Added),t.initChildren(i),this.dataType){const y=this.dataType.clone(i,t);t.setDataType(y,i)}if(this.defaultValue){const y=this.defaultValue.clone(i,t);t.setDefaultValue(y,i)}return i==null||i.attemptAutoclose("implement-as-return-declaration",this.id),t}implementAsArgumentDeclaration(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"implement-as-return-declaration")),a,l){const p=fa.new(i);p.id=l||p.id,p.name=this.name,p.description=this.description,p.parent=a.toReference(),p.implements=this.toJSON();const t=St(p,this.project);if(t.hydrateAncestors(),t.addSelfToProject(i),i==null||i.add(t,K.Added),t.initChildren(i),this.dataType){const y=this.dataType.clone(i,t);t.setDataType(y,i)}if(this.defaultValue){const y=this.defaultValue.clone(i,t);t.setDefaultValue(y,i)}return i==null||i.attemptAutoclose("implement-as-return-declaration",this.id),t}};D(Pt,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(Pt,"type",f.ValueDescriptor),D(Pt,"USER_MANAGED_PARENT_TYPES",[f.ActionDescriptor,f.Loop,f.Search]),D(Pt,"PARENT_TYPES",[...Pt.USER_MANAGED_PARENT_TYPES]),D(Pt,"MUTABLE_BASE_PROPERTIES",["name","codeName","description","required"]),D(Pt,"INMUTABLE_BASE_PROPERTIES",["id","version","type","parentRelationType","createdAt","author","previousVersion"]),D(Pt,"BASE_PROPERTIES",[...Pt.MUTABLE_BASE_PROPERTIES,...Pt.INMUTABLE_BASE_PROPERTIES]),D(Pt,"MUTABLE_META_PROPERTIES",[...Pt.MUTABLE_BASE_PROPERTIES,"index"]),D(Pt,"INMUTABLE_META_PROPERTIES",[...Pt.INMUTABLE_BASE_PROPERTIES]),D(Pt,"META_PROPERTIES",[...Pt.MUTABLE_META_PROPERTIES,...Pt.INMUTABLE_META_PROPERTIES]),D(Pt,"MUTABLE_UPSTREAM_PROPERTIES",[]),D(Pt,"INMUTABLE_UPSTREAM_PROPERTIES",["parent"]),D(Pt,"UPSTREAM_PROPERTIES",[...Pt.MUTABLE_UPSTREAM_PROPERTIES,...Pt.INMUTABLE_UPSTREAM_PROPERTIES]),D(Pt,"MUTABLE_DOWNSTREAM_PROPERTIES",["dataType","defaultValue"]),D(Pt,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(Pt,"DOWNSTREAM_PROPERTIES",[...Pt.MUTABLE_DOWNSTREAM_PROPERTIES,...Pt.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(Pt,"PROPERTIES",[...Pt.META_PROPERTIES,...Pt.UPSTREAM_PROPERTIES,...Pt.DOWNSTREAM_PROPERTIES]);let Qs=Pt;var be=(d=>(d.Inherited="inherited",d.DefaultValue="default-value",d.Missing="missing",d.Empty="empty",d.AutoCalculated="auto-calculated",d.QueuedAutocalculation="queued-autocalculation",d.External="external",d.Testing="testing",d.ExecutionResult="execution-result",d))(be||{});const Mx={initialized:!1,id:"",project:null,values:{},onWriteCallback:()=>{},onRemoveCallback:()=>{},onWrite:()=>{},onRemove:()=>{},init:()=>{},toJSON:()=>({}),writeValue:()=>{},readValue:()=>null,removeValue:()=>{},clear:()=>{}};function Vme(d,u){return{...Mx,id:d,project:u}}class Ap{constructor(u,i){D(this,"initialized",!1);D(this,"id");D(this,"project");D(this,"values",{});D(this,"onWriteCallback",()=>{});D(this,"onRemoveCallback",()=>{});this.id=u,this.project=i,this.init()}onWrite(u){this.onWriteCallback=u}onRemove(u){this.onRemoveCallback=u}init(){if(!this.project.id||this.initialized)return;const u={},i={};Object.keys(u).forEach(a=>{const l=u[a],p=new Ti(l,this.project);try{if(l.parent){const v=this.project.findSubscribedInstanceFromReference(l.parent);if(!v)return;p.setParent(v,null),p.hydrateAncestors(),p.initChildren(null)}else if(l.standaloneParent){const v=this.project.findSubscribedInstanceFromReference(l.standaloneParent);if(!v)return;p.standalone=!0,p.setStandaloneParent(v),p.hydrateAncestors(),p.initChildren(null)}i[a]=p;const t=p.parent||p.standaloneParent,y=jx(p,t,this.project);y?i[a]=y:delete u[a]}catch(t){console.error("Error hydrating ancestors: ",t),delete u[a]}}),this.values={...this.values,...i},this.initialized=!0}toJSON(){const u={};return Object.keys(this.values).forEach(i=>{u[i]=this.values[i].toJSON()}),u}writeValue(u,i){if(!u)throw new Error("The value owner entity is required when writing a value to a value store");let l=this.values[u.id];if(!l)if(i instanceof Ti)l=i;else if(i)l=St(i,this.project);else{const p={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:null,type:f.LiteralValue,standaloneParent:u.toReference(),parent:null,valueAsTypeSingle:null,valueAsTypeList:null,autogeneration:null,name:Ho(u.getDataType(null))};l=St(p,this.project)}l.standalone=!0,l.initialData.standaloneParent||console.warn("instance.initialData: ",l.initialData),l.setStandaloneParent(u),l.hydrateAncestors(),l.initChildren(null),i&&(l.metaSync({...i},null),l.setValueAsType(i.valueAsType,null)),this.values[u.id]=l,this.onWriteCallback(u,l)}readValue(u){return this.values[u]||null}removeValue(u){if(!this.values[u])return;delete this.values[u];const i=this.project.get(u);i&&this.onRemoveCallback(i)}clear(){this.values={}}}function zo(d){var u;return!!(d.required||(u=d.declaration)!=null&&u.required)}function Ux(d){return IM(d)||d===void 0||d===""}function Sb(d){return d?d.valueAsType?!1:Ux(d.value):!0}function en(d,u,i,a){var y;let l;if(((y=d==null?void 0:d.entity)==null?void 0:y.type)===f.PrimitiveEntity)switch(d.entity.name){case Q.EntityTemplate:l=Q.EntityTemplate;break;case Q.String:l=Q.String;break;case Q.Number:l=Q.Number;break;case Q.Boolean:l=Q.Boolean;break;case Q.Null:l=Q.Null;break;case Q.Enum:l=Q.Enum;break;case Q.KeyValue:l=Q.KeyValue;break;case Q.Untyped:l=Q.Untyped;break;case Q.KeyValue:l=Q.KeyValue;break;case Q.Date:l=Q.Date;break;case Q.UUID:l=Q.UUID;break;case Q.File:l=Q.File;break;default:throw new Error(`Primitive type ${ie(d.entity,i)} is not supported`)}else l=Q.Untyped;const p=Ti.new();p.name=l,p.parent=u.toReference();const t=te(p,i);return t.hydrateAncestors(),a==null||a.add(t,K.Added),t.addSelfToProject(a),t.initChildren(a),t}function tn(d,u,i=new Set){var a,l;if(i.has(d.id))return[];if(i.add(d.id),d.type===f.ReturnDeclaration){const p=[d,...d.getCounterparts()];return console.log("Resolved counterparts for return declaration: ",`${d.name} ${d.id}`),console.log("equivalentReturnDeclarations: ",p.map(t=>`${t.name} ${t.id}`)),R([...p,...p.flatMap(t=>tn(t,u,i))])}else if(st.includes(d.type)){const p=di(d);return R([p,...[p].flatMap(t=>tn(t,u,i))])}else if(d.type===f.OutputMap){if(st.includes(d.parent.type)&&d.declaration.type===f.Property&&d.declaration.static)return R([d,d.declaration,...[d,d.declaration].flatMap(p=>tn(p,u,i))])}else if(d.type===f.InputMap&&st.includes(d.parent.type)&&((a=d.declaration)==null?void 0:a.type)===f.Property&&(l=d.declaration)!=null&&l.static)return R([d.declaration,...[d.declaration].flatMap(p=>tn(p,u,i))]);return[d]}function jx(d,u,i){return d}function Dd(d,u){const i=d.readsValue;let a=null;if((i==null?void 0:i.type)===f.VariableDeclaration){const p=wp(i,u);if(p&&p.value){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}else if((i==null?void 0:i.type)===f.VariableInstance){const p=Dy(i,u);if(p&&p.value){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}else if((i==null?void 0:i.type)===f.OutputMap){const p=Wb(i,u);if(p&&p.value){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}else if((i==null?void 0:i.type)===f.ArgumentDeclaration){const p=Zb(i,u);if(p){const t={sources:[p],target:d};a={value:p.value,valueOwner:d,type:be.Inherited,inheritanceLink:t}}}return a}function We(d,u,i){var y;if(!u)return null;let a;if(((y=d==null?void 0:d.entity)==null?void 0:y.type)===f.PrimitiveEntity)switch(d.entity.name){case Q.EntityTemplate:a=Q.EntityTemplate;break;case Q.String:a=Q.String;break;case Q.Number:a=Q.Number;break;case Q.Boolean:a=Q.Boolean;break;case Q.Null:a=Q.Null;break;case Q.Enum:a=Q.Enum;break;case Q.KeyValue:a=Q.KeyValue;break;case Q.Untyped:a=Q.Untyped;break;case Q.KeyValue:a=Q.KeyValue;break;case Q.Date:a=Q.Date;break;case Q.UUID:a=Q.UUID;break;case Q.File:a=Q.File;break;default:throw new Error(`Primitive type ${ie(d.entity,i)} is not supported`)}else a=Q.Untyped;if(!i.get(u.id))return null;const p=Ti.new();p.name=a,p.standaloneParent=u.toReference();let t=new Ti(p,i);return t.hydrateAncestors(),t.standalone=!0,t.setStandaloneParent(u),t.initChildren(null),t}function _y(d,u,i){var p;const a={...d},l=u.inputs;if(!l)return a;for(const t of l){if(!xp(t))continue;const y=Yb(t,i);if(y&&y.value){const v=ie(t,i.project),T=Tr(v);a[T]=(p=y==null?void 0:y.value)==null?void 0:p.value}}return a}function Ip(d,u,i){var p;const a={...d},l=u.inputs;if(!l)return a;for(const t of l){if(!xp(t))continue;const y=Hb(t,i);if(y&&y.value){const v=ie(t,i.project),T=Tr(v);a[T]=(p=y==null?void 0:y.value)==null?void 0:p.value}}return a}function xx(d,u){var y,v,T,w,A,V,N;let i={};if(((v=(y=d.dataType)==null?void 0:y.entity)==null?void 0:v.type)===f.DefinitionEntity&&(i={...i,...d.dataType.entity.getActiveRawDefaultValue()},d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("initialDefaultValue",i)),u.execution&&u.execution.hasEntity(d)){const j=(T=u.lastExecutionResults)==null?void 0:T.readValue(d.id);if(j){if(ar(j.value)){const S={...i,...j.value},W={...Ip(S,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("1- newRawValue",W),j.metaSync({value:W},null)}return{value:j,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}}const a=!!((w=u.execution)!=null&&w.entities.length),l=(A=u.execution)==null?void 0:A.hasEntity(d),p=d.readsValue;let t=null;if(p){const j=(V=u.execution)==null?void 0:V.hasEntity(p);if((!a||a&&j&&l||a&&!j&&!l)&&(t=Dd(d,u),t&&t.value&&ar(t.value.value))){const S={...i,...t.value.value},W={...Ip(S,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("2- newRawValue",W),t.value.metaSync({value:W},null)}}if(!t&&d.defaultValue){const j=d.defaultValue;if(j.value===null&&j.autogeneration){const k=bh(j);if(j.metaSync({value:k},null),ar(k)){const S={...Ip(k,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("3- newRawValue",S),j.metaSync({value:S},null)}}t={value:j,valueOwner:d,type:j.value===null?be.Empty:be.DefaultValue,inheritanceLink:null}}if(!t||t.type===be.DefaultValue){const j=(N=u.localTestValues)==null?void 0:N.readValue(d.id);if(j){if(ar(j.value)){const k={...i,...j.value},S={...Ip(k,d,u)};d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("4- newRawValue",S),j.metaSync({value:S},null)}return{value:j,valueOwner:d,type:be.Testing,inheritanceLink:null}}}return t||{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}}function Fx(d,u){var l,p,t,y,v;let i={};if(((p=(l=d.dataType)==null?void 0:l.entity)==null?void 0:p.type)===f.DefinitionEntity&&(i={...i,...d.dataType.entity.getActiveRawDefaultValue()},d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("initialDefaultValue",i)),u.execution&&u.execution.hasEntity(d)){const T=(t=u.lastExecutionResults)==null?void 0:t.readValue(d.id);if(T){if(ar(T.value)){const A={...i,...T.value};T==null||T.metaSync({value:{..._y(A,d,u)}},null)}return{value:T,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}}const a=(y=u.localTestValues)==null?void 0:y.readValue(d.id);if(d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("testValue",a),a){if(ar(a.value)){const w={...i,...a.value};a.metaSync({value:{..._y(w,d,u)}},null)}return{value:a,valueOwner:d,type:be.Testing,inheritanceLink:null}}if((v=d.dataType)!=null&&v.entity&&d.dataType.entity.type===f.DefinitionEntity&&d.dataType.isObject()){const T=We(d.dataType,d,u.project);return T==null||T.metaSync({value:_y(i,d,u)},null),{value:T,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}}return null}function wp(d,u){var y,v,T,w,A,V;if((y=d.dataType)!=null&&y.isObject())return d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("Is object: ",d),xx(d,u);const i=rr(d),a=!!((v=u.execution)!=null&&v.entities.length),l=(T=u.execution)==null?void 0:T.hasEntity(i),p=d.readsValue;let t=null;if(p){const N=(w=u.execution)==null?void 0:w.hasEntity(p);(!a||a&&N&&l||a&&!N&&!l)&&(t=Dd(d,u))}if(!t&&d.defaultValue){const N=d.defaultValue;if(N.value===null&&N.autogeneration){const j=bh(N);N.metaSync({value:j},null)}t={value:N,valueOwner:d,type:N.value===null?be.Empty:be.DefaultValue,inheritanceLink:null}}return(!t||t.type===be.DefaultValue)&&(A=u.localTestValues)!=null&&A.values[d.id]?{value:(V=u.localTestValues)==null?void 0:V.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null}:t||{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}}function qb(d,u){var a,l,p,t;if(d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("resolveVarDeclarationValue",d),(a=d.dataType)!=null&&a.isObject())return d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("current value is object"),Fx(d,u);if(u.execution&&u.execution.hasEntity(d)){const y=(l=u.lastExecutionResults)==null?void 0:l.readValue(d.id);if(y)return{value:y,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=(p=u.localTestValues)==null?void 0:p.readValue(d.id);if(i)return{value:i,valueOwner:d,type:be.Testing,inheritanceLink:null};if((t=d.dataType)!=null&&t.entity&&d.dataType.entity.type===f.DefinitionEntity&&d.dataType.isObject()){const y=We(d.dataType,d,u.project),v=d.dataType.entity.getActiveRawDefaultValue();return d.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("resolvedRawValue",v),y==null||y.metaSync({value:v},null),{value:y,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}}return null}function Dy(d,u){var T,w,A,V,N;d.id==="e749df9b-6b68-4baf-a3c5-59ca15c2492f"&&console.log("resolveVarInstanceNextValue");const i=!!((T=u.execution)!=null&&T.entities.length),a=(w=u.execution)==null?void 0:w.hasEntity(d);let l=null;const p=d.readsValue;if(p){const j=(A=u.execution)==null?void 0:A.hasEntity(p);(!i||i&&j&&a||i&&!j&&!a)&&(l=Dd(d,u))}const t=d.declaration;if(!l&&t){d.id==="e749df9b-6b68-4baf-a3c5-59ca15c2492f"&&console.log("resolveVarInstanceNextValue resolveVarDeclarationNextValue");const j=wp(t,u);j&&j.value&&(l=j)}if((!l||l.type===be.DefaultValue)&&(V=u.localTestValues)!=null&&V.values[d.id])return{value:(N=u.localTestValues)==null?void 0:N.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const y=zo(d);return y&&a&&!l?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:a&&!y&&!l?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:l||{value:null,valueOwner:d,type:be.External,inheritanceLink:null}}function Gx(d,u){return qb(d.declaration,u)}function Zb(d,u){var v,T,w,A,V;if(u.execution&&u.execution.hasEntity(d)){const N=(v=u.lastExecutionResults)==null?void 0:v.readValue(d.id);if(N)return{value:N,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=rr(d),a=d.parent.type===f.FunctionDeclaration&&d.parent.parent.type===f.Loop?d.parent:null,l=!!((T=u.execution)!=null&&T.hasEntity(i))||!!a&&!!((w=u.execution)!=null&&w.hasEntity(a));let p=null;if(d.defaultValue){const N=d.defaultValue;if(N.value===null&&N.autogeneration){const j=bh(N);N.metaSync({value:j},null)}p={value:N,valueOwner:d,type:N.value===null?be.Empty:be.DefaultValue,inheritanceLink:null}}if((!p||p.type===be.DefaultValue)&&(A=u.localTestValues)!=null&&A.values[d.id])return{value:(V=u.localTestValues)==null?void 0:V.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const t=zo(d);let y=t&&l&&!p;return i.type===f.Loop&&l&&(y=!1),y?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:l&&!t&&!p?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:p||{value:null,valueOwner:d,type:be.External,inheritanceLink:null}}function Jb(d,u){var T,w,A,V,N,j;if(u.execution&&u.execution.hasEntity(d)){const k=(T=u.lastExecutionResults)==null?void 0:T.readValue(d.id);if(k)return{value:k,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=rr(d),a=!!((w=u.execution)!=null&&w.entities.length),l=(A=u.execution)==null?void 0:A.hasEntity(i),p=d.readsValue;let t=null;if(p){const k=(V=u.execution)==null?void 0:V.hasEntity(p);(!a||a&&k&&l||a&&!k&&!l)&&(t=Dd(d,u))}if(!t&&d.defaultValue&&(t={value:d.defaultValue,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}),(!t||t.type===be.DefaultValue)&&(N=u.localTestValues)!=null&&N.values[d.id])return{value:(j=u.localTestValues)==null?void 0:j.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const y=zo(d);return y&&!t?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:!y&&!t?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:t}function Wb(d,u){var y,v,T,w,A;if(u.execution&&u.execution.hasEntity(d)){const V=(y=u.lastExecutionResults)==null?void 0:y.readValue(d.id);if(V)return{value:V,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const i=rr(d);if(st.includes(i.type)){const V=Xo(i,u),N=Tr(ie(d,u.project));if(V!=null&&V.value&&ar(V.value.value)){const j=V.value.value[N],k=We(d.getDataType(null),d,u.project);return k==null||k.metaSync({value:j},null),{value:k,valueOwner:d,type:V.type,inheritanceLink:{sources:[V],target:d}}}return null}const a=(v=u.execution)==null?void 0:v.hasEntity(i),l=((T=u.execution)==null?void 0:T.state)===Xb.Running;if((w=u.persistedExecutionResults)!=null&&w.values[d.id]&&!a&&!l){const V=(A=u.persistedExecutionResults)==null?void 0:A.readValue(d.id);if((V==null?void 0:V.value)!==null||(V==null?void 0:V.valueAsType)!==null)return{value:V,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}const p=d.getDefaultValue();if(p&&(p.value!==null||p.valueAsType!==null))return{value:p,valueOwner:d,type:be.DefaultValue,inheritanceLink:null};const t=d.parent;if(!t)throw new Error(`Couldn't find the parent that generates the output ${d.id}`);switch(t.type){case f.VariableInstance:{const N=Dy(t,u);if(N&&N.value){const k=d.declaration;if(ar(N.value.value)){const S=N.value.value[k.name],W=We(d.declaration.dataType,d,u.project);return W==null||W.metaSync({value:S},null),{value:W,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:[N],target:d}}}}const j=We(d.declaration.dataType,d,u.project);return j==null||j.metaSync({value:null},null),{value:j,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:N?[N]:[],target:d}}}case f.VariableDeclaration:{const N=wp(t,u);if(N&&N.value){const k=d.declaration;if(ar(N.value.value)){const S=N.value.value[k.name],W=We(d.declaration.dataType,d,u.project);return W==null||W.metaSync({value:S},null),{value:W,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:[N],target:d}}}}const j=We(d.declaration.dataType,d,u.project);return j==null||j.metaSync({value:null},null),{value:j,valueOwner:d,type:be.Inherited,inheritanceLink:{sources:N?[N]:[],target:d}}}case f.Operation:{const V=t.outputs.map(j=>{var S,W;if((S=u.persistedExecutionResults)!=null&&S.values[j.id]){const ne=(W=u.persistedExecutionResults)==null?void 0:W.values[j.id];if(ne.value!==null||ne.valueAsType!==null)return{value:ne,valueOwner:j,type:be.ExecutionResult,inheritanceLink:null}}const k=j.getDefaultValue();if(k&&(k.value!==null||k.valueAsType!==null))return{value:k,valueOwner:j,type:be.DefaultValue,inheritanceLink:null}}).filter(j=>!!j),N=We(d.declaration.dataType,d,u.project);return N==null||N.metaSync({value:null},null),{value:N,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:V.length?{sources:V,target:d}:null}}case f.FunctionCall:{const V=t.inputs.map(j=>Rp(j,u)).filter(j=>!!j),N=We(d.declaration.dataType,d,u.project);return N==null||N.metaSync({value:null},null),{value:N,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:V.length?{sources:V,target:d}:null}}case f.Loop:{const V=t.inputs.map(j=>Rp(j,u)).filter(j=>!!j),N=We(d.declaration.dataType,d,u.project);return N==null||N.metaSync({value:null},null),{value:N,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:V.length?{sources:V,target:d}:null}}case f.Search:return{value:null,valueOwner:d,type:be.QueuedAutocalculation,inheritanceLink:null}}return null}function Kx(d,u){var y,v;if(!st.includes(d.parent.type)||!xp(d))return null;if(((y=d.declaration)==null?void 0:y.type)===f.Property&&d.declaration.static)return Xo(d.declaration,u);const i=di(d.parent),a=Oy(i,u),l=Tr(ie(d,u.project)),p=We(d.getDataType(null),d,u.project),t=(v=a==null?void 0:a.value)==null?void 0:v.value;return t&&ar(t)?(p==null||p.metaSync({value:t[l]||null},null),{value:p,valueOwner:d,type:a.type,inheritanceLink:{sources:a?[a]:[],target:d}}):null}function kx(d,u){var y,v;if(!st.includes(d.parent.type)||!xp(d))return null;if(((y=d.declaration)==null?void 0:y.type)===f.Property&&d.declaration.static)return Xo(d.declaration,u);const i=di(d.parent),a=Xo(i,u),l=Tr(ie(d,u.project)),p=We(d.getDataType(null),d,u.project),t=(v=a==null?void 0:a.value)==null?void 0:v.value;return t&&ar(t)?(p==null||p.metaSync({value:t[l]||null},null),{value:p,valueOwner:d,type:a.type,inheritanceLink:{sources:[a],target:d}}):null}function Hb(d,u){var T,w,A,V,N;const i=rr(d),a=!!((T=u.execution)!=null&&T.entities.length),l=(w=u.execution)==null?void 0:w.hasEntity(i),p=d.readsValue;let t=null;if(p){const j=(A=u.execution)==null?void 0:A.hasEntity(p);(!a||a&&j&&l||a&&!j&&!l)&&(t=Dd(d,u))}if(!t&&d.defaultValue){const j=d.defaultValue;j&&(t={value:j,valueOwner:d,type:be.DefaultValue,inheritanceLink:null})}if(!t&&d.declaration){const j=Xo(d.declaration,u);j&&j.value&&(t={...j,valueOwner:d,type:be.DefaultValue})}if((!t||t.type===be.DefaultValue||(t==null?void 0:t.type)===be.Empty)&&(V=u.localTestValues)!=null&&V.values[d.id])return{value:(N=u.localTestValues)==null?void 0:N.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const y=zo(d);return y&&!t||(t==null?void 0:t.type)===be.Empty?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:(t==null?void 0:t.inheritanceLink)||null}:!y&&(!t||t.type===be.Inherited)&&!(t!=null&&t.inheritanceLink)?(d.id==="6589602d-30df-4ef8-8161-fb5c228c9254"&&console.log("Here input-map -- resolved as empty","value: ",t,"isDefinitionRequired: ",y,"!value: ",!t,"value.type: ",t==null?void 0:t.type),{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}):t}function Yb(d,u){var a;if(u.execution&&u.execution.hasEntity(d)){const l=(a=u.lastExecutionResults)==null?void 0:a.readValue(d.id);if(l)return{value:l,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}return Rp(d,u)}function Rp(d,u){var i;return d.id==="6589602d-30df-4ef8-8161-fb5c228c9254"&&console.log("resolveInputMapNextValue"),st.includes(d.parent.type)&&(i=di(d.parent).dataType)!=null&&i.isObject()?Kx(d,u):Hb(d,u)}function Sx(d,u){var i;return st.includes(d.parent.type)&&(i=di(d.parent).dataType)!=null&&i.isObject()?kx(d,u):Yb(d,u)}function qx(d,u){var t,y,v;if(!d.static)return null;if(u.execution){const T=(t=u.lastExecutionResults)==null?void 0:t.readValue(d.id);if(T)return{value:T,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}if((y=u.localTestValues)!=null&&y.values[d.id])return{value:(v=u.localTestValues)==null?void 0:v.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const i=d.getDefaultValue();let a=null;return i&&(a={value:i,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}),zo(d)&&Sb(a==null?void 0:a.value)?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:Sb(a==null?void 0:a.value)?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:a}function Zx(d,u){var t,y,v,T,w,A,V;if(u.execution&&u.execution.hasEntity(d)){const N=(t=u.lastExecutionResults)==null?void 0:t.readValue(d.id);if(N)return{value:N,valueOwner:d,type:be.ExecutionResult,inheritanceLink:null}}if((y=u.localTestValues)!=null&&y.values[d.id])return{value:(v=u.localTestValues)==null?void 0:v.values[d.id],valueOwner:d,type:be.Testing,inheritanceLink:null};const i=d.getDefaultValue();let a=null;return i&&(a={value:i,valueOwner:d,type:be.DefaultValue,inheritanceLink:null}),zo(d)&&!((T=a==null?void 0:a.value)!=null&&T.value)&&!((w=a==null?void 0:a.value)!=null&&w.valueAsType)?{value:null,valueOwner:d,type:be.Missing,inheritanceLink:null}:!((A=a==null?void 0:a.value)!=null&&A.value)&&!((V=a==null?void 0:a.value)!=null&&V.valueAsType)?{value:null,valueOwner:d,type:be.Empty,inheritanceLink:null}:a}function Xo(d,u){switch(d.type){case f.ArgumentDeclaration:return Zb(d,u);case f.InputMap:return Sx(d,u);case f.VariableDeclaration:return qb(d,u);case f.VariableInstance:return Gx(d,u);case f.OutputMap:return Wb(d,u);case f.ReturnDeclaration:return Jb(d,u);case f.Property:return qx(d,u);case f.ValueDescriptor:return Zx(d,u);default:return null}}function Oy(d,u){switch(d.type){case f.InputMap:return Rp(d,u);case f.VariableDeclaration:return wp(d,u);case f.VariableInstance:return Dy(d,u);case f.ReturnDeclaration:return Jb(d,u);default:return null}}function Nme(d){var u;if(d&&d.type===be.DefaultValue&&d.value&&d.valueOwner&&((u=d.valueOwner.defaultValue)==null?void 0:u.id)===d.value.id){const i=We(d.valueOwner.getDataType(null),d.valueOwner,d.valueOwner.project);return{type:be.DefaultValue,value:i,valueOwner:d.valueOwner,inheritanceLink:null}}return d}function Qo(d,u,i,a){let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=d.parent;return u.getVariableDeclarations().forEach(T=>{var A,V,N,j;const w=T.getDataType(null);if(((A=w==null?void 0:w.entity)==null?void 0:A.id)===y.id){let k=l?T.defaultValue:t==null?void 0:t.readValue(T.id);k?!l&&k&&k.id===((V=T.defaultValue)==null?void 0:V.id)&&(k=We(T.getDataType(null),T,u)):l?k=en(T.getDataType(null),T,u,p):k=We(T.getDataType(null),T,u);const S=ie(d,u),W=Tr(S);let ne={};((j=(N=T.dataType)==null?void 0:N.entity)==null?void 0:j.type)===f.DefinitionEntity&&(ne={...ne,...T.dataType.entity.getActiveRawDefaultValue()}),ar(k==null?void 0:k.value)&&(ne={...ne,...k.value}),ne[W]=i,k==null||k.metaSync({value:ne},p),l||t==null||t.writeValue(T,k);return}}),p}function gp(d,u,i,a){var N,j,k;let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=di(d.parent),v=y.getDataType(null);if(!(v!=null&&v.isObject()))return p;let T=l?y.defaultValue:t==null?void 0:t.readValue(y.id);T?!l&&T&&T.id===((N=y.defaultValue)==null?void 0:N.id)&&(T=We(y.getDataType(null),y,u)):l?T=en(y.getDataType(null),y,u,p):T=We(y.getDataType(null),y,u);const w=ie(d,u),A=Tr(w);let V={};if(((k=(j=y.dataType)==null?void 0:j.entity)==null?void 0:k.type)===f.DefinitionEntity&&(V={...V,...y.dataType.entity.getActiveRawDefaultValue()}),ar(T==null?void 0:T.value)&&(V={...V,...T.value}),V[A]=i,T==null||T.metaSync({value:V},p),l||t==null||t.writeValue(y,T),(i===""||i===null||i===void 0)&&d.type===f.OutputMap){const S=y.inputs.find(W=>{var ne;return((ne=W.declaration)==null?void 0:ne.id)===d.declaration.id||ie(W,u)===w});if(S){let W=l?S.defaultValue:t==null?void 0:t.readValue(S.id);W&&W.metaSync({value:null},p),l||t==null||t.removeValue(S.id)}}return p}function Jx(d,u,i){var t,y,v,T;let a=!1,l=null,p=null;if(i instanceof G?(a=!0,l=i,p=null):(l=null,p=i),st.includes(d.type)){const w=di(d);(t=w.dataType)!=null&&t.isObject()&&w.inputs.forEach(A=>{var V,N,j,k;if(((V=A.declaration)==null?void 0:V.type)===f.Property&&A.declaration.static){let S=a?d.defaultValue:p==null?void 0:p.readValue(A.declaration.id);S?!a&&S&&S.id===((N=A.declaration.defaultValue)==null?void 0:N.id)&&(S=We(A.declaration.getDataType(null),A.declaration,u)):a?S=en(A.declaration.getDataType(null),A.declaration,u,l):S=We(A.declaration.getDataType(null),A.declaration,u),S==null||S.metaSync({value:null},l),a||p==null||p.removeValue((j=A.declaration)==null?void 0:j.id)}else if(((k=A.declaration)==null?void 0:k.type)===f.Property){let S=a?d.defaultValue:p==null?void 0:p.readValue(A.id);S&&S.metaSync({value:null},l),a||p==null||p.removeValue(A.id)}})}else d.type===f.InputMap?((y=d.declaration)==null?void 0:y.type)===f.Property&&d.declaration.static?Qo(d.declaration,u,null,i):st.includes(d.parent.type)&&((v=d.declaration)==null?void 0:v.type)===f.Property&&gp(d,u,null,i):d.type===f.OutputMap?((T=d.declaration)==null?void 0:T.type)===f.Property&&d.declaration.static?Qo(d.declaration,u,null,i):st.includes(d.parent.type)&&d.declaration.type===f.Property&&gp(d,u,null,i):d.type===f.Property&&d.static&&Qo(d,u,null,i);return l}function Wx(d,u,i,a){var y,v,T,w,A,V;let l=!1,p=null,t=null;if(a instanceof G?(l=!0,p=a,t=null):(p=null,t=a),st.includes(u.type)){const N=di(u);if((y=N.dataType)!=null&&y.isObject()){let j={};((T=(v=N.dataType)==null?void 0:v.entity)==null?void 0:T.type)===f.DefinitionEntity&&(j={...j,...N.dataType.entity.getActiveRawDefaultValue()});const k=ar(d)?d:j;N.inputs.forEach(S=>{var W,ne,re;if(((W=S.declaration)==null?void 0:W.type)===f.Property&&S.declaration.static){let pe=l?u.defaultValue:t==null?void 0:t.readValue(S.declaration.id);pe?!l&&pe&&pe.id===((ne=S.declaration.defaultValue)==null?void 0:ne.id)&&(pe=We(S.declaration.getDataType(null),S.declaration,i)):l?pe=en(S.declaration.getDataType(null),S.declaration,i,p):pe=We(S.declaration.getDataType(null),S.declaration,i);const se=ie(S,i),he=Tr(se),X=k[he];pe==null||pe.metaSync({value:X},p),l||t==null||t.writeValue(S.declaration,pe)}else if(((re=S.declaration)==null?void 0:re.type)===f.Property){let pe=l?u.defaultValue:t==null?void 0:t.readValue(S.id);pe&&pe.metaSync({value:null},p),l||t==null||t.removeValue(S.id)}})}}else u.type===f.InputMap?((w=u.declaration)==null?void 0:w.type)===f.Property&&u.declaration.static?Qo(u.declaration,i,d,a):st.includes(u.parent.type)&&((A=u.declaration)==null?void 0:A.type)===f.Property&&gp(u,i,d,a):u.type===f.OutputMap?((V=u.declaration)==null?void 0:V.type)===f.Property&&u.declaration.static?Qo(u.declaration,i,null,a):st.includes(u.parent.type)&&u.declaration.type===f.Property&&gp(u,i,null,a):u.type===f.Property&&u.static&&Qo(u,i,d,a);return p}function Hx(d,u,i){const a=tn(d,u);let l=!1,p=null,t=null;return i instanceof G?(l=!0,p=i,t=null):(p=null,t=i),a.forEach(y=>{var T;let v=l?y.defaultValue:t==null?void 0:t.readValue(y.id);v?!l&&v&&v.id===((T=y.defaultValue)==null?void 0:T.id)&&(v=We(d.getDataType(null),d,d.project)):l?v=en(y.getDataType(null),y,u,p):v=We(y.getDataType(null),y,u),v==null||v.metaSync({value:null},p),l||t==null||t.removeValue(y.id),Jx(y,u,i)}),p}function Lme(d,u,i,a){if(d===""||d===null||d===void 0)return Hx(u,i,a);const l=tn(u,i);let p=!1,t=null,y=null;return a instanceof G?(p=!0,t=a,y=null):(t=null,y=a),l.forEach(v=>{var w;let T=p?u.defaultValue:y==null?void 0:y.readValue(u.id);T?!p&&T&&T.id===((w=v.defaultValue)==null?void 0:w.id)&&(T=We(v.getDataType(null),v,i)):p?T=en(v.getDataType(null),v,i,t):T=We(v.getDataType(null),v,i),T==null||T.metaSync({value:d},t),p||y==null||y.writeValue(v,T),Wx(d,v,i,a)}),t}function el(d,u,i,a){let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=d.parent;return u.getVariableDeclarations().forEach(T=>{var A,V,N,j;const w=T.getDataType(null);if(((A=w==null?void 0:w.entity)==null?void 0:A.id)===y.id){let k=l?T.defaultValue:t==null?void 0:t.readValue(T.id);k?!l&&k&&k.id===((V=T.defaultValue)==null?void 0:V.id)&&(k=We(T.getDataType(null),T,u)):l?k=en(T.getDataType(null),T,u,p):k=We(T.getDataType(null),T,u);const S=ie(d,u),W=Tr(S);let ne={};((j=(N=T.dataType)==null?void 0:N.entity)==null?void 0:j.type)===f.DefinitionEntity&&(ne={...ne,...T.dataType.entity.getActiveRawDefaultValue()}),ar(k==null?void 0:k.value)&&(ne={...ne,...k.value}),Array.isArray(i)?ne[W]=(i==null?void 0:i.map(re=>re.toShallowJSON()))||null:ne[W]=(i==null?void 0:i.toShallowJSON())||null,k==null||k.metaSync({value:ne},p),l||t==null||t.writeValue(T,k);return}}),p}function _p(d,u,i,a){var N,j,k;let l=!1,p=null,t=null;a instanceof G?(l=!0,p=a,t=null):(p=null,t=a);const y=di(d.parent),v=y.getDataType(null);if(!(v!=null&&v.isObject()))return p;let T=l?y.defaultValue:t==null?void 0:t.readValue(y.id);T?!l&&T&&T.id===((N=y.defaultValue)==null?void 0:N.id)&&(T=We(y.getDataType(null),y,u)):l?T=en(y.getDataType(null),y,u,p):T=We(y.getDataType(null),y,u);const w=ie(d,u),A=Tr(w);let V={};if(((k=(j=y.dataType)==null?void 0:j.entity)==null?void 0:k.type)===f.DefinitionEntity&&(V={...V,...y.dataType.entity.getActiveRawDefaultValue()}),ar(T==null?void 0:T.value)&&(V={...V,...T.value}),Array.isArray(i)?V[A]=(i==null?void 0:i.map(S=>S.toShallowJSON()))||null:V[A]=(i==null?void 0:i.toShallowJSON())||null,T==null||T.metaSync({value:V},p),l||t==null||t.writeValue(y,T),i==null&&d.type===f.OutputMap){const S=y.inputs.find(W=>{var ne;return((ne=W.declaration)==null?void 0:ne.id)===d.declaration.id||ie(W,u)===w});if(S){let W=l?S.defaultValue:t==null?void 0:t.readValue(S.id);W&&(Array.isArray(i)?W==null||W.setValueAsTypeList(i,p):W==null||W.setValueAsTypeSingle(i,p)),l||t==null||t.removeValue(S.id)}}return p}function Yx(d,u,i){var a,l,p;return d.type===f.InputMap?((a=d.declaration)==null?void 0:a.type)===f.Property&&d.declaration.static?el(d.declaration,u,null,i):st.includes(d.parent.type)&&((l=d.declaration)==null?void 0:l.type)===f.Property&&_p(d,u,null,i):d.type===f.OutputMap?((p=d.declaration)==null?void 0:p.type)===f.Property&&d.declaration.static?el(d.declaration,u,null,i):st.includes(d.parent.type)&&d.declaration.type===f.Property&&_p(d,u,null,i):d.type===f.Property&&d.static&&el(d,u,null,i),i}function zx(d,u,i,a){var l,p,t;return u.type===f.InputMap?((l=u.declaration)==null?void 0:l.type)===f.Property&&u.declaration.static?el(u.declaration,i,d,a):st.includes(u.parent.type)&&((p=u.declaration)==null?void 0:p.type)===f.Property&&_p(u,i,d,a):u.type===f.OutputMap?((t=u.declaration)==null?void 0:t.type)===f.Property&&u.declaration.static?el(u.declaration,i,null,a):st.includes(u.parent.type)&&u.declaration.type===f.Property&&_p(u,i,null,a):u.type===f.Property&&u.static&&el(u,i,d,a),a}function Xx(d,u,i){const a=tn(d,u);let l=!1,p=null,t=null;return i instanceof G?(l=!0,p=i,t=null):(p=null,t=i),a.forEach(y=>{var T;let v=l?y.defaultValue:t==null?void 0:t.readValue(y.id);v?!l&&v&&v.id===((T=y.defaultValue)==null?void 0:T.id)&&(v=We(y.getDataType(null),y,y.project)):l?v=en(y.getDataType(null),y,u,p):v=We(y.getDataType(null),y,u),v==null||v.setValueAsTypeSingle(null,p),v==null||v.setValueAsTypeList(null,p),l||t==null||t.removeValue(y.id),Yx(y,u,i)}),p}function Bme(d,u,i,a){if(d==null)return Xx(u,i,a);const l=tn(u,i);let p=!1,t=null,y=null;return a instanceof G?(p=!0,t=a,y=null):(t=null,y=a),l.forEach(v=>{var w;let T=p?v.defaultValue:y==null?void 0:y.readValue(v.id);T?!p&&T&&T.id===((w=v.defaultValue)==null?void 0:w.id)&&(T=We(v.getDataType(null),v,v.project)):p?T=en(v.getDataType(null),v,i,t):T=We(v.getDataType(null),v,i),Array.isArray(d)?T==null||T.setValueAsTypeList(d,t):T==null||T.setValueAsTypeSingle(d,t),p||y==null||y.writeValue(v,T),zx(d,v,i,a)}),t}var Mme=Object.defineProperty,Ume=(d,u,i)=>u in d?Mme(d,u,{enumerable:!0,configurable:!0,writable:!0,value:i}):d[u]=i,tl=(d,u,i)=>(Ume(d,typeof u!="symbol"?u+"":u,i),i);let jme=class{constructor(u){tl(this,"eventName"),tl(this,"callbacks",[]),this.eventName=u,this.on=this.on.bind(this),this.off=this.off.bind(this),this.destroy=this.destroy.bind(this)}on(u){if(typeof u!="function")throw new Error("Event callback must be a function");this.callbacks.includes(u)||this.callbacks.push(u)}off(u){if(typeof u!="function")throw new Error("Event callback must be a function");this.callbacks=this.callbacks.filter(i=>i!==u)}destroy(){this.callbacks=[]}},zb=class{constructor(){tl(this,"subscribedEvents",{}),tl(this,"on",this._on),tl(this,"emit",this._emit),tl(this,"off",this._off),tl(this,"destroy",this._destroy),this.getEvent=this.getEvent.bind(this),this._on=this._on.bind(this),this._emit=this._emit.bind(this),this._off=this._off.bind(this),this._destroy=this._destroy.bind(this),this.on=this.on.bind(this),this.emit=this.emit.bind(this),this.off=this.off.bind(this),this.destroy=this.destroy.bind(this)}getEvent(u){return this.subscribedEvents[u]||(this.subscribedEvents[u]=new jme(u)),this.subscribedEvents[u]}_on(u,i){this.getEvent(u).on(i)}_emit(u,...i){const a=this.getEvent(u);a&&a.callbacks.forEach(l=>{l.apply(null,i)})}_off(u,i){const a=this.getEvent(u);a&&(i?a.off(i):(a.destroy(),delete this.subscribedEvents[u]))}_destroy(){Object.keys(this.subscribedEvents).forEach(u=>{this._off(u)}),this.subscribedEvents={}}};const Ja={onBeforeEntityExecution:async()=>{},onEntityExecuted:async()=>{}};var Xb=(d=>(d.FinishedSuccess="finished-success",d.FinishedError="finished-error",d.Running="running",d.Paused="paused",d.Stopped="stopped",d.NotStarted="not-started",d))(Xb||{});const Bi=class Bi extends zb{constructor(i,a,l,p=null){super();D(this,"project");D(this,"entryPoint");D(this,"state","not-started");D(this,"events",new zb);D(this,"entities",[]);D(this,"parentExecution",null);D(this,"executing",[]);D(this,"executed",[]);D(this,"skipped",[]);D(this,"scheduled",[]);D(this,"localTestValues");D(this,"resolvedValues");D(this,"persistedExecutionResults");D(this,"lastExecutionResults");D(this,"onAddToSkippedListCallback",null);D(this,"onRemoveFromSkippedListCallback",null);D(this,"onAddEntityCallback",null);D(this,"onRemoveEntityCallback",null);this.entities=a,this.entryPoint=l,this.project=i,this.parentExecution=p,this.localTestValues=new Ap(P.UUID.uuid(),this.project),this.resolvedValues=new Ap(P.UUID.uuid(),this.project),this.persistedExecutionResults=new Ap(P.UUID.uuid(),this.project),this.lastExecutionResults=new Ap(P.UUID.uuid(),this.project)}get valueResolutionContext(){return{execution:this,project:this.project,localTestValues:this.localTestValues,resolvedValues:this.resolvedValues,persistedExecutionResults:this.persistedExecutionResults,lastExecutionResults:this.lastExecutionResults}}static injectSearchImplementation(i){Bi.searchImplementation=i}skip(i){this.hasEntity(i)&&(this.skipped.includes(i)||(this.skipped.push(i),this.onAddToSkippedListCallback&&this.onAddToSkippedListCallback(i),Rs.includes(i.type)&&[...i.successCalls||[],...i.errorCalls||[],...i.calls||[]].forEach(a=>this.skip(a))))}async schedule(i,a,l){if(this.hasExecuted(i))return null;if(Ht.includes(i.type))return this.executeBranch(i,l,a);if(ws.includes(i.type)){if(i.calledBy.every(t=>this.hasExecuted(t)||!this.hasEntity(t)))return this.executeBranch(i,l,a);this.scheduled.includes(i)||this.scheduled.push(i)}return null}mergeExernalValuesWithInternalInputs(i,a){const l=[];return[...er,...Ht].includes(a.type)?l.push(...a.inputs):nr.includes(a.type)&&l.push(...a.outputs),l.map(t=>{var v;let y=i.find(T=>T.valueOwner.id===t.id);if(y)return y;if(!y&&Ht.includes(a.type)&&(y=i.find(T=>{var w;return((w=T.valueOwner.declaration)==null?void 0:w.id)===t.id})),y){const T=(v=y.value)==null?void 0:v.clone(null);return T==null||T.setStandaloneParent(t),{...y,valueOwner:t,value:T||null,inheritanceLink:{sources:[y],target:t}}}return Wn.includes(t.type)?Oy(t,this.valueResolutionContext):Xo(t,this.valueResolutionContext)}).reduce((t,y)=>{const v=tn(y==null?void 0:y.valueOwner,this.project),T=y?[y]:[];return v.forEach(w=>{var N,j,k;if(w.id===(y==null?void 0:y.valueOwner.id))return;const A=We(w.getDataType(null),w,this.project);A==null||A.metaSync({value:(N=y==null?void 0:y.value)==null?void 0:N.value},null),A==null||A.setValueAsTypeList(((j=y==null?void 0:y.value)==null?void 0:j.valueAsTypeList)||null),A==null||A.setValueAsTypeSingle(((k=y==null?void 0:y.value)==null?void 0:k.valueAsTypeSingle)||null);const V={...y,valueOwner:w,value:A};T.push(V)}),[...t,...T]},[]).sort((t,y)=>t.valueOwner.index-y.valueOwner.index)}inheritValuesFromContext(i){this.localTestValues=i.localTestValues,this.resolvedValues=i.resolvedValues,this.persistedExecutionResults=i.persistedExecutionResults}async executeInternalCall(i,a,l,p={}){var y,v;const t={...Ja,...p};try{let T={value:Ke.Success,error:null,results:[]};if(a.sort((w,A)=>w.valueOwner.index-A.valueOwner.index),Object.values(gi).includes(i.declaration.id)){const w=Bi.builtInFunctionImplementations[i.declaration.id];w?T=await w(i,a):console.warn(`No implementation found for built-in function: ${i.declaration.id}`)}else{console.log("executeFunctionCall",a),T=await this.executeDetachedFullFunctionDeclarationLogic(i.declaration,a,l,t);const w=i.outputs.map(V=>{var W,ne,re,pe;const N=[...V.declaration.getCounterparts(),V.declaration];console.log("declarations",N);const j=T.results.find(se=>N.some(X=>se.valueOwner.id===X.id));console.log("resultValue",j);const k=V==null?void 0:V.getDataType(null),S=We(k,V,l);return k!=null&&k.asType?Array.isArray((W=j==null?void 0:j.value)==null?void 0:W.valueAsType)?S==null||S.setValueAsTypeList((ne=j==null?void 0:j.value)==null?void 0:ne.valueAsTypeList):S==null||S.setValueAsTypeSingle(((re=j==null?void 0:j.value)==null?void 0:re.valueAsType)||null):S==null||S.metaSync({value:(pe=j==null?void 0:j.value)==null?void 0:pe.value},null),{valueOwner:V,type:be.ExecutionResult,inheritanceLink:null,value:S}});let A=null;if(T.error){console.warn("Raw error executing entity: ",T.error);const V=(y=i.error)==null?void 0:y.getDataType(null),N=We(V||null,i.error,l);V!=null&&V.asType?N==null||N.setValueAsTypeSingle(T.error):N==null||N.metaSync({value:T.error},null),A={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:N}}return{value:T.value,entity:i,error:A,results:w}}return{value:Ke.Error,entity:i,error:null,results:[]}}catch(T){console.warn("Operation execution error: ",T);let w=null;if(i.error){const A=(v=i.error)==null?void 0:v.getDataType(null),V=We(A,i.error,l);A!=null&&A.asType?V==null||V.setValueAsTypeSingle(T):V==null||V.metaSync({value:T},null),w={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:V}}return{value:Ke.Error,entity:i,error:w,results:[]}}}static async executeOperation(i,a,l){var p,t;try{let y={value:Ke.Success,error:null,results:[]};a.sort((w,A)=>w.valueOwner.index-A.valueOwner.index),i.declaration.implementation&&(y=await i.declaration.implementation(i,a));const v=i.outputs.map((w,A)=>{const V=w==null?void 0:w.getDataType(null),N=We(V,w,l);return V!=null&&V.asType?N==null||N.setValueAsTypeSingle(y.results[A]):N==null||N.metaSync({value:y.results[A]},null),{valueOwner:w,type:be.ExecutionResult,inheritanceLink:null,value:N}});let T=null;if(y.error&&i.error){console.warn("Raw error executing entity: ",y.error);const w=((p=i.error)==null?void 0:p.getDataType(null))||null,A=We(w,i.error,l);w!=null&&w.asType?A==null||A.setValueAsTypeSingle(y.error):A==null||A.metaSync({value:y.error},null),T={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:A}}return{value:y.value,entity:i,error:T,results:v}}catch(y){console.warn("Operation execution error: ",y);let v=null;if(i.error){const T=(t=i.error)==null?void 0:t.getDataType(null),w=We(T,i.error,l);T!=null&&T.asType?w==null||w.setValueAsTypeSingle(y):w==null||w.metaSync({value:y},null),v={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:w}}return{value:Ke.Error,entity:i,error:v,results:[]}}}async executeSearch(i,a,l){var p;console.log("executeSearch");try{let t={value:Ke.Success,error:null,results:[]};const y=i.outputs[0];if(!y)return{value:Ke.Success,entity:i,error:null,results:[]};let v={value:null,valueOwner:y,type:be.ExecutionResult,inheritanceLink:null};const T=await Bi.searchImplementation(i,a),w=y==null?void 0:y.getDataType(null),A=We(w,y,l);return A==null||A.metaSync({value:T.data},null),v.value=A,{value:t.value,entity:i,error:null,results:[v]}}catch(t){if(console.warn(`Search node execution error: ${t}`),!i.error)return{value:Ke.Error,entity:i,error:null,results:[]};const y=(p=i.error)==null?void 0:p.getDataType(null),v=We(y,i.error,l);return v==null||v.metaSync({value:t},null),{value:Ke.Error,entity:i,error:{valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:v},results:[]}}}async executeLoop(i,a,l,p={}){var y,v;const t={...Ja,...p};try{let T={value:Ke.Success,error:null,results:[]};const w=a.map(S=>{var W,ne;return((W=S==null?void 0:S.value)==null?void 0:W.valueAsType)||((ne=S==null?void 0:S.value)==null?void 0:ne.value)});console.log("Loops' resolved raw input-map values: ",w);let A={};i.getUniqueReturnDeclarations().forEach(S=>{const W=i.body.inputs.find(se=>ie(se,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(S)),ne=S==null?void 0:S.getDataType(null),re=We(ne,W,l);ne!=null&&ne.asType?re==null||re.setValueAsTypeList([]):re==null||re.metaSync({value:[]},null),this.lastExecutionResults.writeValue(W,re);const pe={value:re,valueOwner:W,type:be.ExecutionResult,inheritanceLink:null};A[W.id]=pe});let N={value:Ke.Success,entity:i.body,error:null,results:[]};switch(console.log("aggregateListResults: ",A),i.declaration.id){case ve.loop["counted-loop"].id:{const S=w[0];console.log("maxCount",S);let W=1;for(console.log("currentIteration",W);W<=S&&W<=50;){console.log("iterating",W);const ne=i.body.inputs.map(pe=>{if(pe===i.currentIterationNumberArgumentDeclaration){console.log("Argument is body iteration number");const se=i.currentIterationNumberArgumentDeclaration.getDataType(null),he=Ho(se),X=this.lastExecutionResults.readValue(pe.id);if(X){X.metaSync({value:W},null),console.log("existingValue",W),this.lastExecutionResults.writeValue(pe,X);const de={value:X,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null};return A[pe.id]=de,de}const z={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:W,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:he,standaloneParent:pe.toReference()},ce=St(z,l);this.lastExecutionResults.writeValue(pe,ce);const H={value:ce,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null};return console.log("newDynamicValue",W),A[pe.id]=H,H}else return A[pe.id]}).filter(pe=>!!pe);console.log("Loop executes body with inputs: ",ne);const re=await this.executeFullFunctionDeclarationLogic(i.body,ne,t);if(N=re,N.results.forEach(pe=>{var z,ce,H,de;if(pe.valueOwner.type!==f.ReturnDeclaration)return;const se=i.body.inputs.find(Te=>ie(Te,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(pe.valueOwner)),X=[...((ce=(z=A==null?void 0:A[se.id])==null?void 0:z.value)==null?void 0:ce.value)||[],((H=pe==null?void 0:pe.value)==null?void 0:H.value)||null];(de=A[se.id].value)==null||de.metaSync({value:X},null),this.lastExecutionResults.writeValue(se,A[se.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(re.value))break;console.log("Loop iteration finished"),W++}break}case ve.loop["manual-flow-loop"].id:{let S=1;for(;S<=50;){const W=i.body.inputs.map(re=>{if(re===i.currentIterationNumberArgumentDeclaration){const pe=this.lastExecutionResults.readValue(re.id);if(pe){pe.metaSync({value:S},null),this.lastExecutionResults.writeValue(re,pe);const z={value:pe,valueOwner:re,type:be.ExecutionResult,inheritanceLink:null};return A[re.id]=z,z}const se=i.currentIterationNumberArgumentDeclaration.getDataType(null),he=We(se,re,l);he==null||he.metaSync({value:S},null),this.lastExecutionResults.writeValue(re,he);const X={value:he,valueOwner:re,type:be.ExecutionResult,inheritanceLink:null};return console.log("newDynamicValue",S),X}else return A[re.id]}).filter(re=>!!re);console.log("Loop executes body");const ne=await this.executeFullFunctionDeclarationLogic(i.body,W,t);if(N=ne,N.results.forEach(re=>{var X,z,ce;if(re.valueOwner.type!==f.ReturnDeclaration)return;const pe=i.body.inputs.find(H=>ie(H,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(re.valueOwner)),he=[...(X=A[pe.id].value)==null?void 0:X.value,((z=re.value)==null?void 0:z.value)||null];(ce=A[pe.id].value)==null||ce.metaSync({value:he},null),this.lastExecutionResults.writeValue(pe,A[pe.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(ne.value))break;S++}break}case ve.loop["list-loop"].id:{const S=w[0];let W=1;const ne=S;for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body");const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}case ve.loop["object-keys-loop"].id:{const S=w[0];let W=1;const ne=S?Object.keys(S):[];console.log("iterableListOfValues: ",ne);for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body");const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}case ve.loop["object-values-loop"].id:{const S=w[0];let W=1;const ne=S?Object.values(S):[];for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body"),console.log("HEREEE Object.values() resolvedBodyInputsForCurrentIteration",se);const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}case ve.loop["string-loop"].id:{const S=w[0];let W=1;const ne=S.split("");for(let re=0;re<ne.length;re++){const pe=ne[re],se=i.body.inputs.map(X=>{if(X===i.currentIterationNumberArgumentDeclaration){const z=this.lastExecutionResults.readValue(X.id);if(z)return z.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,z),{value:z,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const ce=i.currentIterationNumberArgumentDeclaration.getDataType(null),H=We(ce,X,l);return H==null||H.metaSync({value:W},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:i.currentIterationNumberArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else if(X===i.currentValueArgumentDeclaration){const z=i.currentValueArgumentDeclaration.getDataType(null),ce=Ho(z),H=this.lastExecutionResults.readValue(X.id);if(H)return H.metaSync({value:pe},null),this.lastExecutionResults.writeValue(X,H),{value:H,valueOwner:X,type:be.ExecutionResult,inheritanceLink:null};const de={id:P.UUID.uuid(),type:f.LiteralValue,autogeneration:null,version:P.UUID.uuid(),createdAt:new Date().toISOString(),author:P.sessionAuthor,deleted:!1,previousVersion:null,value:pe,valueAsTypeSingle:null,valueAsTypeList:null,parent:null,name:ce,standaloneParent:X.toReference()},Te=St(de,l);return this.lastExecutionResults.writeValue(X,Te),{value:Te,valueOwner:i.currentValueArgumentDeclaration,type:be.ExecutionResult,inheritanceLink:null}}else return A[X.id]}).filter(X=>!!X);console.log("Loop executes body");const he=await this.executeFullFunctionDeclarationLogic(i.body,se,t);if(N=he,N.results.forEach(X=>{var de,Te,Ne;if(X.valueOwner.type!==f.ReturnDeclaration)return;const z=i.body.inputs.find(we=>ie(we,l)===bi.fromReturnDeclarationToBodyArgumentDeclarationName(X.valueOwner)),H=[...(de=A[z.id].value)==null?void 0:de.value,((Te=X.value)==null?void 0:Te.value)||null];(Ne=A[z.id].value)==null||Ne.metaSync({value:H},null),this.lastExecutionResults.writeValue(z,A[z.id].value)}),[Ke.Error,Ke.Break,Ke.Return].includes(he.value))break;W++}break}}let j=[];i.body.inputs.forEach(S=>{var ne;const W=A[S.id];if(W){const re=(ne=W.value)==null?void 0:ne.clone(null),pe=i.outputs.find(se=>se.declaration&&bi.fromLoopOutputDeclarationToBodyArgumentDeclarationName(se.declaration)===ie(S,l));if(!pe)return;j.push({valueOwner:pe,type:be.ExecutionResult,inheritanceLink:null,value:re})}}),T={value:[Ke.Error,Ke.Return].includes(N.value)?N.value:Ke.Success,error:null,results:j};let k=null;if(T.error&&i.error){console.warn("Raw error executing entity: ",T.error);const S=(y=i.error)==null?void 0:y.getDataType(null),W=We(S||null,i.error,l);S!=null&&S.asType?W==null||W.setValueAsTypeSingle(T.error):W==null||W.metaSync({value:T.error},null),k={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:W}}return{value:T.value,entity:i,error:k,results:T.results}}catch(T){if(console.warn("Error executing loop: ",T),i.error){const w=(v=i.error)==null?void 0:v.getDataType(null),A=We(w,i.error,l);return w!=null&&w.asType?A==null||A.setValueAsTypeSingle(T):A==null||A.metaSync({value:T},null),{value:Ke.Error,entity:i,error:{valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:A},results:[]}}else return{value:Ke.Error,entity:i,error:null,results:[]}}}async executeFunctionCall(i,a,l,p={}){var y,v;const t={...Ja,...p};try{let T={value:Ke.Success,error:null,results:[]};console.log("executeFunctionCall",a),T=await this.executeDetachedFullFunctionDeclarationLogic(i.declaration,a,l,t);const w=i.outputs.map(V=>{var W,ne,re,pe;const N=[...V.declaration.getCounterparts(),V.declaration];console.log("declarations",N);const j=T.results.find(se=>N.some(X=>se.valueOwner.id===X.id));console.log("resultValue",j);const k=V==null?void 0:V.getDataType(null),S=We(k,V,l);return k!=null&&k.asType?Array.isArray((W=j==null?void 0:j.value)==null?void 0:W.valueAsType)?S==null||S.setValueAsTypeList((ne=j==null?void 0:j.value)==null?void 0:ne.valueAsTypeList):S==null||S.setValueAsTypeSingle(((re=j==null?void 0:j.value)==null?void 0:re.valueAsType)||null):S==null||S.metaSync({value:(pe=j==null?void 0:j.value)==null?void 0:pe.value},null),{valueOwner:V,type:be.ExecutionResult,inheritanceLink:null,value:S}});let A=null;if(T.error&&i.error){console.warn("Raw error executing entity: ",T.error);const V=(y=i.error)==null?void 0:y.getDataType(null),N=We(V||null,i.error,l);V!=null&&V.asType?N==null||N.setValueAsTypeSingle(T.error):N==null||N.metaSync({value:T.error},null),A={valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:N}}return{value:T.value,entity:i,error:A,results:w}}catch(T){if(console.log("error: ",T),!i.error)return{value:Ke.Error,entity:i,error:null,results:[]};const w=(v=i.error)==null?void 0:v.getDataType(null),A=We(w,i.error,l);return w!=null&&w.asType?A==null||A.setValueAsTypeSingle(T):A==null||A.metaSync({value:T},null),{value:Ke.Error,entity:i,error:{valueOwner:i.error,type:be.ExecutionResult,inheritanceLink:null,value:A},results:[]}}}static async executeCondition(i,a){var p,t,y,v,T,w,A,V,N,j,k,S,W,ne,re,pe,se,he,X,z,ce,H,de,Te,Ne,we,Re,ge,Ue,Pe,Je,ut,Jt,or,Ir,jr;let l=!1;switch(i.declaration.id){case Mr.Empty:{l=!((t=(p=a[0])==null?void 0:p.value)!=null&&t.value);break}case Mr.NotEmpty:{l=!!((v=(y=a[0])==null?void 0:y.value)!=null&&v.value);break}case cr.Equal:{if([Q.String,Q.Number,Q.Boolean,Q.Null,Q.Enum,Q.Date,Q.UUID].includes((w=(T=a[0])==null?void 0:T.value)==null?void 0:w.name)){l=((V=(A=a[0])==null?void 0:A.value)==null?void 0:V.value)===((j=(N=a[1])==null?void 0:N.value)==null?void 0:j.value);break}if(((S=(k=a[0])==null?void 0:k.value)==null?void 0:S.name)===Q.KeyValue||((ne=(W=a[0])==null?void 0:W.value)==null?void 0:ne.name)===Q.Untyped){const Kr=(pe=(re=a[0])==null?void 0:re.value)==null?void 0:pe.value,Mi=(he=(se=a[1])==null?void 0:se.value)==null?void 0:he.value;l=JSON.stringify(Kr)===JSON.stringify(Mi);break}break}case cr.NotEqual:{if([Q.String,Q.Number,Q.Boolean,Q.Null,Q.Enum,Q.Date,Q.UUID].includes((z=(X=a[0])==null?void 0:X.value)==null?void 0:z.name)){l=((H=(ce=a[0])==null?void 0:ce.value)==null?void 0:H.value)!==((Te=(de=a[1])==null?void 0:de.value)==null?void 0:Te.value);break}if(((we=(Ne=a[0])==null?void 0:Ne.value)==null?void 0:we.name)===Q.Untyped||((ge=(Re=a[0])==null?void 0:Re.value)==null?void 0:ge.name)===Q.KeyValue){const Kr=(Pe=(Ue=a[0])==null?void 0:Ue.value)==null?void 0:Pe.value,Mi=(ut=(Je=a[1])==null?void 0:Je.value)==null?void 0:ut.value;l=JSON.stringify(Kr)!==JSON.stringify(Mi);break}break}case cr.MoreThanOrEqual:{l=((or=(Jt=a[0])==null?void 0:Jt.value)==null?void 0:or.value)>=((jr=(Ir=a[1])==null?void 0:Ir.value)==null?void 0:jr.value);break}}return{value:l?Ke.Success:Ke.Error,entity:i,error:null,results:[]}}async executeDetachedFullFunctionDeclarationLogic(i,a,l,p={}){const t={...Ja,...p,onBeforeEntityExecution:(T,w,A)=>{var V;return((V=p==null?void 0:p.onBeforeEntityExecution)==null?void 0:V.call(p,T,w,{...A,detached:!0}))||Promise.resolve()},onEntityExecuted:(T,w,A)=>{var V;return((V=p==null?void 0:p.onEntityExecuted)==null?void 0:V.call(p,T,w,{...A,detached:!0}))||Promise.resolve()}},y=new Bi(l,[i,...Hy(i)],i,this);y.inheritValuesFromContext(this),console.log("functionBodyExecution",a);const v=await y.execute(t,a);return console.log("executeDetachedFullFunctionDeclarationLogic result: ",v),v}async executeFullFunctionDeclarationLogic(i,a,l={}){const p={...Ja,...l},t=Hy(i);t.forEach(A=>{this.addEntity(A)}),t.reduce((A,V)=>nr.includes(V.type)?[...A,...V.outputs]:er.includes(V.type)&&V.type!==f.Condition?[...A,...V.outputs,...V.inputs]:V.type===f.Condition?[...A,...V.inputs]:A,[]).forEach(A=>{this.lastExecutionResults.removeValue(A.id)});const v=await this.executeBranch(i,p,a),w=i.getUniqueReturnDeclarations().reduce((A,V)=>{const N=v==null?void 0:v.results.find(j=>j.valueOwner.id===V.id);return N?[...A,N]:A},[]);return{...v||{},value:(v==null?void 0:v.value)||Ke.Success,entity:i,error:(v==null?void 0:v.error)||null,results:w}}static async executeEntryPointEntity(i,a){return{value:Ke.Success,entity:i,error:null,results:a}}static async executeVariable(i,a){return{value:Ke.Success,entity:i,error:null,results:[a]}}static async executeReturnStatement(i,a){return{value:i.throws?Ke.Error:Ke.Return,entity:i,error:null,results:a}}static async executeContinueStatement(i,a){return{value:Ke.Continue,entity:i,error:null,results:a}}static async executeBreakStatement(i,a){return{value:Ke.Break,entity:i,error:null,results:a}}mergeValues(i,a){const l=[];for(let p=0;p<a.length;p++)i!=null&&i[p]?l.push(i[p]):l.push(a[p]);return l}async executeEntity(i,a=[],l={}){var y,v,T,w,A,V,N,j,k,S,W,ne,re,pe,se,he,X;const p={...Ja,...l},t={detached:!1};switch(console.log("Executing entity: ",i),console.log("Exec ent with inputs: ",a),i.type){case f.Condition:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((y=p.onBeforeEntityExecution)==null?void 0:y.call(p,i,z,t)),Bi.executeCondition(i,z)}case f.InternalCall:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((v=p.onBeforeEntityExecution)==null?void 0:v.call(p,i,z,t)),this.executeInternalCall(i,z,this.project)}case f.Operation:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((T=p.onBeforeEntityExecution)==null?void 0:T.call(p,i,z,t)),Bi.executeOperation(i,z,this.project)}case f.VariableInstance:case f.VariableDeclaration:{i.id==="ad7eae6d-c691-40a5-943b-f72008cdc3b0"&&console.log("Execute variable declaration resolveNextValue");let z=Oy(i,this.valueResolutionContext);const ce=di(i),H=ce.getDataType(null);if(H!=null&&H.isObject()){let Ne={};if(((w=H==null?void 0:H.entity)==null?void 0:w.type)===f.DefinitionEntity&&(Ne={...Ne,...H.entity.getActiveRawDefaultValue()}),z!=null&&z.value)ar((A=z==null?void 0:z.value)==null?void 0:A.value)&&(Ne={...Ne,...(V=z==null?void 0:z.value)==null?void 0:V.value}),z==null||z.value.metaSync({value:Ne},null);else{const we=We(H,i,this.project);we==null||we.metaSync({value:Ne},null),z={valueOwner:ce,type:be.ExecutionResult,inheritanceLink:null,value:we}}this.lastExecutionResults.writeValue(ce,z.value),console.log("Propagating value to inputs: ",ce.inputs.map(we=>ie(we,this.project))),ce.inputs.forEach(we=>{var Re;if(((Re=we.declaration)==null?void 0:Re.type)===f.Property&&we.declaration.static){const ge=this.lastExecutionResults.readValue(we.declaration.id),Ue=ie(we,this.project),Pe=Tr(Ue);if(ge)ge.metaSync({value:Ne[Pe]},null),this.lastExecutionResults.writeValue(we.declaration,ge);else{const Je=We(we.getDataType(null),we,this.project);Je==null||Je.metaSync({value:Ne[Pe]},null),console.log(`Created new value for static property ${Ue}: `,Ne[Pe]),this.lastExecutionResults.writeValue(we.declaration,Je)}}})}else this.lastExecutionResults.writeValue(ce,z==null?void 0:z.value);const de=[],Te=(N=z==null?void 0:z.value)!=null&&N.value&&ar((j=z.value)==null?void 0:j.value)?((k=z.value)==null?void 0:k.value)||{}:{};return i.outputs.map(Ne=>{const we=Tr(ie(Ne,this.project)),Re=Te[we],ge=We(Ne.getDataType(null),Ne,this.project);ge==null||ge.metaSync({value:Re},null);const Ue={value:ge,valueOwner:Ne,type:be.ExecutionResult,inheritanceLink:z?{sources:[z],target:i}:null};de.push(Ue)}),z.type=be.ExecutionResult,{value:Ke.Success,entity:i,error:null,results:[z,...de]}}case f.FunctionCall:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((S=p.onBeforeEntityExecution)==null?void 0:S.call(p,i,z,t)),this.executeFunctionCall(i,z,this.project)}case f.FunctionDeclaration:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((W=p.onBeforeEntityExecution)==null?void 0:W.call(p,i,z,t)),Bi.executeEntryPointEntity(i,z)}case f.Search:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((ne=p.onBeforeEntityExecution)==null?void 0:ne.call(p,i,z,t)),this.executeSearch(i,z,this.project)}case f.Loop:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((re=p.onBeforeEntityExecution)==null?void 0:re.call(p,i,z,t)),this.executeLoop(i,z,this.project,p)}case f.ReturnStatement:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((pe=p.onBeforeEntityExecution)==null?void 0:pe.call(p,i,z,t)),Bi.executeReturnStatement(i,z)}case f.ContinueStatement:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((se=p.onBeforeEntityExecution)==null?void 0:se.call(p,i,z,t)),Bi.executeContinueStatement(i,z)}case f.BreakStatement:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((he=p.onBeforeEntityExecution)==null?void 0:he.call(p,i,z,t)),Bi.executeBreakStatement(i,z)}case f.GlobalEvent:{const z=this.mergeExernalValuesWithInternalInputs(a,i);return await((X=p.onBeforeEntityExecution)==null?void 0:X.call(p,i,z,t)),Bi.executeEntryPointEntity(i,z)}default:return{value:Ke.Error,entity:i,error:null,results:[]}}}storeLastExecutionValues(i){i.error&&i.error.valueOwner&&this.lastExecutionResults.writeValue(i.error.valueOwner,i.error.value),console.log("result.results: ",i.results),i.results.forEach(a=>{const l=tn(a.valueOwner,this.project);a.value?l.forEach(p=>{this.lastExecutionResults.writeValue(p,a.value)}):l.forEach(p=>{this.lastExecutionResults.removeValue(p.id)})})}async executeBranch(i,a={},l=[]){var T;const p={...Ja,...a},t={detached:!1};if(console.log("executeBranch: ",l),!this.hasEntity(i))return console.log("Skipping entity (not part of test): ",i),null;if(this.hasSkipped(i))return console.log("Skipping entity (already skipped): ",i),null;this.addToExecutingList(i),this.hasScheduled(i)&&this.removeScheduled(i),console.log("Executing branch: ",i),console.log("values: ",l);const v=await this.executeEntity(i,l,p);if(this.removeFromExecutingList(i),this.addToAlreadyExecutedList(i),this.storeLastExecutionValues(v),await((T=p.onEntityExecuted)==null?void 0:T.call(p,i,v,t)),v.value===Ke.Success){const w=(i.successCalls||i.calls||[]).filter(k=>this.hasEntity(k));(i.errorCalls||[]).forEach(k=>{this.skip(k)});let V=[];const N=(await Promise.all(w.map(k=>this.schedule(k,v.results,p)))).filter(k=>!!k),j=N.filter(k=>!!k).find(k=>k.value===Ke.Error||k.value===Ke.Return||k.value===Ke.Break||k.value===Ke.Continue);return j||(V=[...V,...N],v)}else if(v.value===Ke.Error){const w=(i.errorCalls||[]).filter(k=>this.hasEntity(k));(i.successCalls||i.calls||[]).forEach(k=>{this.skip(k)});let V=[];const N=(await Promise.all(w.map(k=>this.schedule(k,v.results,p)))).filter(k=>!!k),j=N.filter(k=>!!k).find(k=>k.value===Ke.Error||k.value===Ke.Return||k.value===Ke.Break||k.value===Ke.Continue);return j||(V=[...V,...N],v)}else{if(v.value===Ke.Return)return v;if(v.value===Ke.Break)return v;if(v.value===Ke.Continue)return v}return v}async execute(i={},a=[]){const l={...Ja,...i};this.state="running";const p=await this.executeBranch(this.entryPoint,l,a);return this.state="finished-success",p}addEntity(i){var a;this.entities.includes(i)||(this.entities.push(i),(a=this.onAddEntityCallback)==null||a.call(this,i))}addEntities(i){i.forEach(a=>this.addEntity(a))}removeEntity(i){var a;if(i!==this.entryPoint){const l=this.entities.indexOf(i);l>-1&&(this.entities.splice(l,1),(a=this.onRemoveEntityCallback)==null||a.call(this,i))}}hasEntity(i){var p,t,y;if(this.entities.includes(i))return!0;if(((p=i.parent)==null?void 0:p.type)===f.FunctionDeclaration&&((y=(t=i.parent)==null?void 0:t.parent)==null?void 0:y.type)===f.DefinitionEntity)return this.entities.includes(i.parent);const a=rr(i);if(!a)return!1;const l=a.type===f.Loop&&i.parent===a.body?a.body:null;return l?this.entities.includes(l)||this.entities.includes(a):this.entities.includes(a)}removeScheduled(i){const a=this.scheduled.indexOf(i);a>-1&&this.scheduled.splice(a,1)}hasScheduled(i){return!!this.scheduled.includes(i)}hasSkipped(i){return!!this.skipped.includes(i)}hasExecuted(i){return!!this.executed.includes(i)}hasEntityWithId(i){const a=this.project.get(i);return a?this.hasEntity(a):!1}onAddToSkippedList(i){this.onAddToSkippedListCallback=i}onAddEntity(i){this.onAddEntityCallback=i}onRemoveFromSkippedList(i){this.onRemoveFromSkippedListCallback=i}onRemoveEntity(i){this.onRemoveEntityCallback=i}addToExecutingList(i){this.executing.includes(i)||this.executing.push(i)}removeFromExecutingList(i){const a=this.executing.indexOf(i);a>-1&&this.executing.splice(a,1)}removeFromAlreadyExecutedList(i){const a=this.executed.indexOf(i);a>-1&&this.executed.splice(a,1)}removeFromSkippedList(i){var l;const a=this.skipped.indexOf(i);a>-1&&(this.skipped.splice(a,1),(l=this.onRemoveFromSkippedListCallback)==null||l.call(this,i))}addToAlreadyExecutedList(i){this.executed.includes(i)||this.executed.push(i)}addToSkippedList(i){var a;this.skipped.includes(i)||(this.skipped.push(i),(a=this.onAddToSkippedListCallback)==null||a.call(this,i))}};D(Bi,"searchImplementation",async()=>({data:null,error:"Search module not implemented"})),D(Bi,"builtInFunctionImplementations",{[gi.AbortExecution]:async(i,a)=>({value:Ke.Error,entity:i,error:null,results:[]}),[gi.SavePersistedEntity]:async(i,a)=>({value:Ke.Error,entity:i,error:null,results:[]}),[gi.DeletePersistedEntity]:async(i,a)=>({value:Ke.Error,entity:i,error:null,results:[]})});let Qb=Bi;function xme(d){var u,i;if(d.isList)return"list";if(((u=d.entity)==null?void 0:u.type)===f.DefinitionEntity)return"definition-entity";switch((i=d.entity)==null?void 0:i.name){case Q.Number:return"number";case Q.String:return"text";case Q.Boolean:return"boolean";case Q.UUID:return"uuid";case Q.Date:return"date-time";default:return"definition-entity"}}const eA={[f.PrimitiveEntity]:{singular:"Primitive",plural:"Primitives",shortSingular:"Primitive",shortPlural:"Primitives"},[f.DefinitionEntity]:{singular:"Definition",plural:"Definitions",shortSingular:"Definition",shortPlural:"Definitions"},[f.BuiltInBaseEntity]:{singular:"Base",plural:"Bases",shortSingular:"Base definition",shortPlural:"Base definitions"},[f.Property]:{singular:"Property",plural:"Properties",shortSingular:"Property",shortPlural:"Properties"},[f.FunctionDeclaration]:{singular:"Custom trigger",plural:"Custom triggers",shortSingular:"Trigger",shortPlural:"Triggers"},[f.FunctionCall]:{singular:"Execute trigger",plural:"Execute trigger",shortSingular:"Execute",shortPlural:"Execute"},[f.GlobalEvent]:{singular:"System trigger",plural:"System triggers",shortSingular:"Trigger",shortPlural:"Triggers"},[f.Project]:{singular:"Project",plural:"Projects",shortSingular:"Project",shortPlural:"Projects"},[f.VariableDeclaration]:{singular:"Variable",plural:"Variables",shortSingular:"Variable",shortPlural:"Variables"},[f.VariableInstance]:{singular:"Variable",plural:"Variables",shortSingular:"Variable",shortPlural:"Variables"},[f.Condition]:{singular:"Condition",plural:"Conditions",shortSingular:"Condition",shortPlural:"Conditions"},[f.Operation]:{singular:"Operation",plural:"Operations",shortSingular:"Operation",shortPlural:"Operations"},[f.ReturnStatement]:{singular:"Termination",plural:"Terminations",shortSingular:"Termination",shortPlural:"Terminations"},[f.InstalledProject]:{singular:"Installed project",plural:"Installed projects",shortSingular:"Project",shortPlural:"Projects"},[f.Search]:{singular:"Search",plural:"Searches",shortSingular:"Search",shortPlural:"Searches"},[f.Loop]:{singular:"Loop",plural:"Loops",shortSingular:"Loop",shortPlural:"Loops"},[f.ActionDescriptor]:{singular:"Action descriptor",plural:"Action descriptors",shortSingular:"Action descriptor",shortPlural:"Action descriptors"},[f.InternalCall]:{singular:"Internal call",plural:"Internal calls",shortSingular:"Internal call",shortPlural:"Internal calls"},[f.BreakStatement]:{singular:"Loop exit",plural:"Loop exists",shortSingular:"Exit",shortPlural:"Exits"},[f.ContinueStatement]:{singular:"Next iteration",plural:"Next iterations",shortSingular:"Next",shortPlural:"Nexts"},[f.ArgumentDeclaration]:{singular:"Input definition",plural:"Input definitions",shortSingular:"Input",shortPlural:"Inputs"},[f.InputMap]:{singular:"Input",plural:"Inputs",shortSingular:"Input",shortPlural:"Inputs"},[f.OutputMap]:{singular:"Output",plural:"Outputs",shortSingular:"Output",shortPlural:"Outputs"},[f.ReturnDeclaration]:{singular:"Output definition",plural:"Output definitions",shortSingular:"Output",shortPlural:"Outputs"},[f.ValueDescriptor]:{singular:"Value descriptor",plural:"Value descriptors",shortSingular:"Value descriptor",shortPlural:"Value descriptors"}};function tA(d){const u=Yy(d);if(!u){const a=Vd(d);if(a.includes(Ce.HTTP_ENDPOINT))return"HTTP endpoint";if(a.includes(Ce.PERSISTED_ENTITY))return"Persisted entity";if(a.includes(Ce.CRON_JOB))return"Scheduled execution";if(a.includes(Ce.RELATIONAL_DATABASE))return"Relational database"}if(u){let a="Extension of "+ie(u,u.project)+" entity",l=vd(a);const p=Vd(d);return p.includes(Ce.HTTP_ENDPOINT)?"HTTP endpoint"+(l?", "+l:""):p.includes(Ce.PERSISTED_ENTITY)?"Persisted entity"+(l?", "+l:""):p.includes(Ce.CRON_JOB)?"Scheduled execution"+(l?", "+l:""):p.includes(Ce.RELATIONAL_DATABASE)?"Relational database"+(l?", "+l:""):a}let i="";return d.abstract&&(i="Template "),d.static&&(i+=i?" single copy ":"Single copy "),i?i+"definition":"Definition"}function Qx(d){return d.parent.type===f.DefinitionEntity||d.parent.type===f.InstalledProject?"Internal action of "+ie(d.parent,d.project):d.parent.type===f.Loop?"Action repeated on every iteration":"Internal action of entity"}function rA(d){return jA(d)?Qx(d):"Custom trigger"}function Fme(d){var u;switch(d.type){case f.DefinitionEntity:return tA(d);case f.FunctionDeclaration:return rA(d)}return(u=eA[d.type])==null?void 0:u.singular}function Gme(d){var u;switch(d.type){case f.DefinitionEntity:return tA(d);case f.FunctionDeclaration:return rA(d)}return(u=eA[d.type])==null?void 0:u.singular}const iA=4e4,eF=280,Kme=300,sA=65,Od=32,Cy=39,tF=26,rF=49,$y=44,kme=35,Py=52,nA=10,ha=nA*2,Vy=38,Ny=90,aA=270,iF=iA/2+120,sF=iA/2+180;function nF(d){let i=Od+$y+Vy+nA;const a=[...d.inputs];return a.length&&(i+=ha,a.forEach(()=>{i+=tF})),{height:i,width:280}}function aF(d){let i=sA;const a=[];if([f.DefinitionEntity].includes(d.type)){const v=[...d.suggestedProperties||[],...d.properties||[]];v.length&&(i+=ha,v.forEach(T=>{i+=T.static?rF:Cy}))}if([f.DefinitionEntity,f.InstalledProject,f.Loop].includes(d.type)){const v=[...(d==null?void 0:d.suggestedMethods)||[],...d.methods||[],...d.functions||[],...d.body?[d.body]:[]];v.length&&(i+=ha,v.forEach(T=>{const w=nF(T);i+=w.height}))}er.includes(d.type)?(st.includes(d.type)?a.push(...(d.usedInputs||[]).flatMap(v=>[v])||[]):a.push(...(d.inputs||[]).flatMap(v=>[v])||[]),d.error&&(i+=Py)):[f.ReturnStatement,f.BreakStatement,f.ContinueStatement].includes(d.type)?(a.push(...d.outputs||[]),d.throws&&(i+=Py)):d.type===f.Condition&&(a.push(d.inputs[0]),d.inputs[1]&&a.push(d.inputs[1]));const l=a.length;l&&(i+=l*Cy,i+=ha);const p=[];if(d.type===f.FunctionDeclaration||d.type===f.GlobalEvent?p.push(...d.inputs||[]):er.includes(d.type)&&(st.includes(d.type)?p.push(...d.usedOutputs||[]):p.push(...d.outputs||[])),st.includes(d.type)){d.readsValue&&(i+=ha,i+=$y),d.writesValues.length&&(i+=ha,i+=$y),d.internalCalls.length&&d.usedInternalCalls.forEach(()=>i+=Py+ha);const v=d.getDataType(null);(!v||v.inferred)&&(i+=Vy)}const t=p.length;return t&&(i+=t*Cy,i+=ha),[f.DefinitionEntity,f.FunctionDeclaration,f.ReturnStatement,f.BreakStatement,f.ContinueStatement].includes(d.type)&&(i+=Vy),{height:i,width:280}}function Dp(d){return`${d.split("-").map((a,l)=>l===0?a.charAt(0).toUpperCase()+a.slice(1):a.toLowerCase()).join(" ")}.`}function Sme(d){switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return"This template entity has non-template actions";case oe.AbstractEntityWithNonAbstractProperties:return"This template entity has non-template properties";case oe.IncorrectEntityImplementation:return"This entity incorrectly implements a template entity";case oe.IncorrectMethodImplementation:return"This action incorrectly implements the template action it's based on";case oe.IncorrectPropertyImplementation:return"This property incorrectly implements the template property it's based on";case oe.AbstractMethodInNonAbstractEntity:return"This action is a template action in a non-template entity";case oe.AbstractPropertyInNonAbstractEntity:return"This property is a template property in a non-template entity";case ae.MethodOverwritesOtherSiblingWithSameName:return"An action in this entity overwrites an action in the template entity with the same name";case ae.PropertyOverwritesOtherSiblingWithSameName:return"A property in this entity overwrites a property in the template entity with the same name";case oe.MissingMethodImplementation:return"This entity is missing an action implementation from the template entity";case oe.MissingPropertyImplementation:return"This entity is missing a property implementation from the template entity";case ae.NameNotUniqueInScope:return"Invalid name. There is another entity with the same name in the same scope";case oe.NoProperties:return"This entity has no properties, so it doesn't do anything";case oe.NonStaticPropertyInStaticEntity:return"This property is not static in a static entity";case oe.StaticEntityWithNonStaticProperties:return"This static entity has non-static properties";case oe.ReadingFromIncompatibleType:return"This entity reads data from a value of a different data type";case oe.WritingToIncompatibleType:return"This entity writes data to a value of a different data type";case oe.ScopeWithoutLogic:return"This action has no logic, so it doesn't do anything";case oe.NonStaticPropertyImplementsStatic:return"This property is static in a non-static entity";case oe.PropertyImplementsIncompatibleType:return"This property implements a property of a different data type";case oe.PropertyImplementsNonAbstact:return"This property implements a non-template property";case oe.StaticPropertyImplementsNonStatic:return"This static property implements a non-static property";case oe.VariableCallsOthersAndHasInternalCall:return"This variable calls other entities while being used to execute internal logic";case oe.VariableHasInputsAndInternalCall:return"This variable has inputs while being used to execute internal logic";case oe.VariableHasOutputsAndInternalCall:return"This variable has outputs while being used to execute internal logic";case oe.VariableIsCalledAndHasInternalCall:return"This variable is called while being used to execute internal logic";case ae.InternalCallDeclarationIsNotFunctionDeclaration:return"This internal call is not an action";case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return"This internal call is not found in the parent entity";case ae.InternalCallParentDeclarationEntityInvalidType:return"This internal call parent entity is not a data type";case ae.InternalCallParentMissingDataType:return"This internal call parent entity has no data type";case ae.UnreachableEntity:return"This entity is unreachable";case oe.DisconnectedCallableEntity:return"This entity is disconnected and won't be executed by anything after publishing";default:return Dp(d.code)}}function qme(d){switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return"Non-template actions";case oe.AbstractEntityWithNonAbstractProperties:return"Non-template properties";case oe.IncorrectEntityImplementation:return"Incorrect implementation";case oe.IncorrectMethodImplementation:return"Incorrect action implementation";case oe.IncorrectPropertyImplementation:return"Incorrect property implementation";case oe.AbstractMethodInNonAbstractEntity:return"Template action in non-template entity";case oe.AbstractPropertyInNonAbstractEntity:return"Template property in non-template entity";case ae.MethodOverwritesOtherSiblingWithSameName:return"Action overwrite";case ae.PropertyOverwritesOtherSiblingWithSameName:return"Property overwrite";case oe.MissingMethodImplementation:return"Missing action";case oe.MissingPropertyImplementation:return"Missing property";case ae.NameNotUniqueInScope:return"Duplicate name";case oe.NoProperties:return"No properties";case oe.NonStaticPropertyInStaticEntity:return"Non-static property";case oe.StaticEntityWithNonStaticProperties:return"Non-static properties";case oe.ReadingFromIncompatibleType:return"Read from different type";case oe.WritingToIncompatibleType:return"Write to different type";case oe.ScopeWithoutLogic:return"No logic";case oe.NonStaticPropertyImplementsStatic:return"Invalid static property";case oe.PropertyImplementsIncompatibleType:return"Incompatible data type";case oe.PropertyImplementsNonAbstact:return"Non-template property";case oe.StaticPropertyImplementsNonStatic:return"Non-static property";case oe.VariableCallsOthersAndHasInternalCall:return"Bad internal call";case oe.VariableHasInputsAndInternalCall:return"Bad internal call";case oe.VariableHasOutputsAndInternalCall:return"Bad internal call";case oe.VariableIsCalledAndHasInternalCall:return"Bad internal call";case ae.InternalCallDeclarationIsNotFunctionDeclaration:return"Declaration not an action";case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return"Declaration not found in parent";case ae.InternalCallParentDeclarationEntityInvalidType:return"Invalid parent declaration type";case ae.InternalCallParentMissingDataType:return"Parent has no data type";case ae.InternalCallDeclarationNotInParentDatatypeEntity:return"Declaration not in parent";case ae.UnreachableEntity:return"Unreachable entity";case oe.DisconnectedCallableEntity:return"Disconnected entity";default:return Dp(d.code)}}function Zme(d){switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return`${ie(d.entity,d.entity.project)} has non-template actions`;case oe.AbstractEntityWithNonAbstractProperties:return`${ie(d.entity,d.entity.project)} has non-template properties`;case oe.IncorrectEntityImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements template`;case oe.IncorrectMethodImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template`;case oe.IncorrectPropertyImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template`;case oe.AbstractMethodInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} can't be a template`;case oe.AbstractPropertyInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} can't be a template`;case ae.MethodOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites action`;case ae.PropertyOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites property`;case oe.MissingMethodImplementation:return`${ie(d.entity,d.entity.project)} is missing action`;case oe.MissingPropertyImplementation:return`${ie(d.entity,d.entity.project)} is missing property`;case ae.NameNotUniqueInScope:return`${ie(d.entity,d.entity.project)} name is not unique`;case oe.NoProperties:return`${ie(d.entity,d.entity.project)} has no properties`;case oe.NonStaticPropertyInStaticEntity:return`${ie(d.entity,d.entity.project)} has non-static property`;case oe.StaticEntityWithNonStaticProperties:return`${ie(d.entity,d.entity.project)} has non-static properties`;case oe.ReadingFromIncompatibleType:return`${ie(d.entity,d.entity.project)} reads from different type`;case oe.WritingToIncompatibleType:return`${ie(d.entity,d.entity.project)} writes to different type`;case oe.ScopeWithoutLogic:return`${ie(d.entity,d.entity.project)} has no logic`;case oe.NonStaticPropertyImplementsStatic:return`${ie(d.entity,d.entity.project)} has invalid static property`;case oe.PropertyImplementsIncompatibleType:return`${ie(d.entity,d.entity.project)} has incompatible data type`;case oe.PropertyImplementsNonAbstact:return`${ie(d.entity,d.entity.project)} has non-template property`;case oe.StaticPropertyImplementsNonStatic:return`${ie(d.entity,d.entity.project)} has non-static property`;case oe.VariableCallsOthersAndHasInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case oe.VariableHasInputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case oe.VariableHasOutputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case oe.VariableIsCalledAndHasInternalCall:return`${ie(d.entity,d.entity.project)} has bad internal call`;case ae.InternalCallDeclarationIsNotFunctionDeclaration:return`${ie(d.entity,d.entity.project)} has declaration that is not an action`;case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has declaration that is not found in parent`;case ae.InternalCallParentDeclarationEntityInvalidType:return`${ie(d.entity,d.entity.project)} has invalid parent declaration type`;case ae.InternalCallParentMissingDataType:return`${ie(d.entity,d.entity.project)}'s parent has no data type`;case ae.InternalCallDeclarationNotInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has declaration that is not in parent`;case ae.UnreachableEntity:return`${ie(d.entity,d.entity.project)} is unreachable`;case oe.DisconnectedCallableEntity:return`${ie(d.entity,d.entity.project)} is not executed by any entity`;default:return`${ie(d.entity,d.entity.project)} Error: ${Dp(d.code)}`}}function Jme(d){var u,i,a,l;switch(d.code){case oe.AbstractEntityWithNonAbstractMethods:return`${ie(d.entity,d.entity.project)} has non-template actions`;case oe.AbstractEntityWithNonAbstractProperties:return`${ie(d.entity,d.entity.project)} has non-template properties`;case oe.IncorrectEntityImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template entity`;case oe.IncorrectMethodImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template action it's based on`;case oe.IncorrectPropertyImplementation:return`${ie(d.entity,d.entity.project)} incorrectly implements the template property it's based on`;case oe.AbstractMethodInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} is a template action in a non-template entity`;case oe.AbstractPropertyInNonAbstractEntity:return`${ie(d.entity,d.entity.project)} is a template property in a non-template entity`;case ae.MethodOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites an action in the template entity`;case ae.PropertyOverwritesOtherSiblingWithSameName:return`${ie(d.entity,d.entity.project)} overwrites a property in the template entity`;case oe.MissingMethodImplementation:return`${ie(d.entity,d.entity.project)} is missing an action implementation from the template entity`;case oe.MissingPropertyImplementation:return`${ie(d.entity,d.entity.project)} is missing a property implementation from the template entity`;case ae.NameNotUniqueInScope:return`${ie(d.entity,d.entity.project)} has a duplicate name in the same scope`;case oe.NoProperties:return`${ie(d.entity,d.entity.project)} has no properties, so it doesn't do anything`;case oe.NonStaticPropertyInStaticEntity:return`${ie(d.entity,d.entity.project)} has a non-static property in a static entity`;case oe.StaticEntityWithNonStaticProperties:return`${ie(d.entity,d.entity.project)} has non-static properties in a static entity`;case oe.ReadingFromIncompatibleType:return`${ie(d.entity,d.entity.project)} reads data from a value of a different data type`;case oe.WritingToIncompatibleType:return`${ie(d.entity,d.entity.project)} writes data to a value of a different data type`;case oe.ScopeWithoutLogic:return`${ie(d.entity,d.entity.project)} has no logic`;case oe.NonStaticPropertyImplementsStatic:return`${ie(d.entity,d.entity.project)} has a static property in a non-static entity`;case oe.PropertyImplementsIncompatibleType:return`${ie(d.entity,d.entity.project)} implements a property of a different data type`;case oe.PropertyImplementsNonAbstact:return`${ie(d.entity,d.entity.project)} implements a non-template property`;case oe.StaticPropertyImplementsNonStatic:return`${ie(d.entity,d.entity.project)} has a static property in a non-static entity`;case oe.VariableCallsOthersAndHasInternalCall:return`${ie(d.entity,d.entity.project)} calls other entities while being used to execute internal logic`;case oe.VariableHasInputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has inputs while being used to execute internal logic`;case oe.VariableHasOutputsAndInternalCall:return`${ie(d.entity,d.entity.project)} has outputs while being used to execute internal logic`;case oe.VariableIsCalledAndHasInternalCall:return`${ie(d.entity,d.entity.project)} is called while being used to execute internal logic`;case ae.InternalCallDeclarationIsNotFunctionDeclaration:return`${ie(d.entity,d.entity.project)} has a declaration that is not an action`;case ae.InternalCallDeclarationNotFoundInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has a declaration that is not found in ${(u=d.entity.parent.getDataType(null))!=null&&u.entity?ie((i=d.entity.parent.getDataType(null))==null?void 0:i.entity,d.entity.project):"the variable's data-type entity"}`;case ae.InternalCallParentDeclarationEntityInvalidType:return`${ie(d.entity,d.entity.project)} is part of a variable whos data-type entity can't have actions`;case ae.InternalCallParentMissingDataType:return`${ie(d.entity,d.entity.project)} is part of a variable with no data-type entity`;case ae.InternalCallDeclarationNotInParentDatatypeEntity:return`${ie(d.entity,d.entity.project)} has a declaration doesn't belong to ${(a=d.entity.parent.getDataType(null))!=null&&a.entity?ie((l=d.entity.parent.getDataType(null))==null?void 0:l.entity,d.entity.project):"the variable's data-type entity"}`;case ae.UnreachableEntity:return`${ie(d.entity,d.entity.project)} is unreachable`;case oe.DisconnectedCallableEntity:return`${ie(d.entity,d.entity.project)} is disconnected and won't be executed by anything after publishing`;default:return`${ie(d.entity,d.entity.project)} Error: ${Dp(d.code)}`}}var oA=(d=>(d.ValuesAlreadyConnected="values-already-connected",d.CannotReadMoreThanOneValue="cannot-read-more-than-one-value",d.CannotReadValueFromChildren="cannot-read-value-from-children",d.CannotWriteValueToChildren="cannot-write-value-to-children",d.CannotBeCalledByChildren="cannot-be-called-by-children",d.ExecutionsAlreadyConnected="executions-already-connected",d.DataTypesNotCompatible="data-types-not-compatible",d.CannotCallAncestor="cannot-call-ancestor",d.CannotWriteValueToAncestor="cannot-write-value-to-ancestor",d.NotInScope="not-in-scope",d.IsNotValueWrittingEntity="is-not-value-writting-entity",d.IsNotValueReadingEntity="is-not-value-reading-entity",d.ContinueOrBreakStatementCalledFromOutsideLoop="continue-or-break-statement-called-from-outside-loop",d.ElementInLoopBodyCallingOutsideLoop="element-in-loop-body-calling-outside-loop",d.CallerIsInHigherScope="caller-is-in-higher-scope",d.CallerIsInLowerScope="caller-is-in-lower-scope",d.CallIsInHigherScope="call-is-in-higher-scope",d.CallIsInLowerScope="call-is-in-lower-scope",d.OtherIncompatibleScopeReason="other-incompatible-scope-reason",d.SiblingInternalCallAlreadyUsedInParentVariable="sibling-internal-call-already-used-in-parent-variable",d))(oA||{});const Wme=Object.values(oA);var lA=(d=>(d.NotPartOfOngoingTest="not-part-of-ongoing-test",d.CannotBeAddedToTest="cannot-be-added-to-test",d))(lA||{});const Hme=Object.values(lA);var dA=(d=>(d.Suggestion="suggestion",d.CanvasGloballyDisabled="canvas-globally-disabled",d.CannotInteractWithInputInVariableWithInternalCalls="cannot-interact-with-input-in-variable-with-internal-calls",d.CannotInteractWithOutputInVariableWithInternalCalls="cannot-interact-with-output-in-variable-with-internal-calls",d))(dA||{});const Yme=Object.values(dA);function zme(d,u){const i=[...d,...u];return Array.from(new Set(i))}function Xme(d,u){const i=[...d,...u],a=Array.from(new Set(i));return{hasChanged:a.length!==d.length,reasons:a}}function Qme(d,u){const i=d.filter(l=>!u.includes(l));return{hasChanged:i.length!==d.length,reasons:i}}function e0e(d,u){return d.find(i=>i.entity.id===u)||null}function oF(d){return d.filter((u,i)=>d.indexOf(u)===i)}class ti{constructor(u,i,a=null,l){D(this,"ids",[]);D(this,"entity");D(this,"entityCardHeight");D(this,"entityCardWidth");D(this,"index");D(this,"childEntities",[]);D(this,"children",[]);D(this,"parents",[]);D(this,"calculationEntryPoint");D(this,"_onlyEntities",null);D(this,"_changeSet",null);if(this.index=i,this.entity=u,this.calculationEntryPoint=a||this,this===this.calculationEntryPoint&&!l)throw new Error("Change set must be provided for the calculation entry point");this.calculateCardSize(),this.getSortedChildren()}static autoGenerateLayout(u,i,a){const l=iF-aA-eF,p=sF-Ny-sA;u.metaSync({x:u.x||l,y:u.y||p},i);const t=new ti(u,0,null,i);t._onlyEntities=a||[],t.ids=["0"];const y=[];t.next(T=>{y.push(...T)}),ti.recursivelyAssembleChildrenAreas(y),t.resolveChildrenOverlaps();const v=t.flattenChildEntities();return t._onlyEntities?v.filter(T=>(t._onlyEntities||[]).includes(T)):v}static recursivelyAssembleChildrenAreas(u){const i=[];u.forEach(a=>{a.next(l=>{i.push(...l)})}),i.length>0&&ti.recursivelyAssembleChildrenAreas(i)}get onlyEntities(){return this.calculationEntryPoint._onlyEntities}get changeSet(){return this.calculationEntryPoint._changeSet}set changeSet(u){this.calculationEntryPoint._changeSet=u}findAreaInChildrenFromEntity(u){if(this.entity===u)return this;const i=this.children.find(l=>l.entity===u);return i||this.children.reduce((l,p)=>l||p.findAreaInChildrenFromEntity(u),null)}findAreaFromEntity(u){if(this.entity===u)return this;const i=this.calculationEntryPoint.children,a=i.find(p=>p.entity===u);return a||i.reduce((p,t)=>p||t.findAreaInChildrenFromEntity(u),null)}addParent(u){if(!this.parents.includes(u)){const i=ti.resolveIds(u,this.index);this.ids.push(...i),this.parents.push(u)}}static resolveIds(u,i){return u?u.ids.map(a=>`${a}-${i}`):[`${i}`]}getSortedChildren(){if(this.entity.collapsed){this.childEntities=[];return}const u=sn(this.entity,!0);if(this.entity.type===f.Project){const i=[],a=[],l=[];u.forEach(t=>{if(f.DefinitionEntity===t.type){a.push(t);return}else if(Ht.includes(t.type)){l.push(t);return}i.push(t)});const p=i.sort((t,y)=>{const v=!!Sy(t,y).length,T=sn(t),w=sn(y);return v?0:T.length&&!w.length?-1:!T.length&&w.length?1:0}).filter(t=>!Qa(t).length);this.childEntities=[...a,...l,...p]}else{const i=[],a=[],l=[],p=[],t=[];Rs.includes(this.entity.type)&&Zy(this.entity).forEach(T=>{if(st.includes(T.type)){l.push(T);return}const w=rr(T);i.push(w)}),wr.includes(this.entity.type)&&a.push(...this.entity.detachedChildren);const y=u.filter(v=>{const T=i.includes(v);return T||l.includes(v)||a.includes(v)?!1:st.includes(v.type)?(l.push(v),!1):ws.includes(v.type)&&!T?(p.push(v),!1):v.type===f.DefinitionEntity?(t.push(v),!1):!0});i.sort((v,T)=>il(v,T)?-1:0),p.sort((v,T)=>il(v,T)?-1:0),l.sort((v,T)=>CA(v,T)?1:CA(T,v)?-1:0),this.childEntities=[...t,...i,...p,...y,...l,...a]}}calculateCardSize(){const u=aF(this.entity);this.entityCardWidth=u.width,this.entityCardHeight=u.height}static getBoundriesOfTwoAreas(u,i){return{top:Math.min(u.top,i.top),left:Math.min(u.left,i.left),bottom:Math.max(u.bottom,i.bottom),right:Math.max(u.right,i.right)}}static getBoundriedOfCombinedAreas(u,i){const a=u.filter(p=>!i.includes(p));return a.reduce((p,t)=>i.includes(t)?p:ti.getBoundriesOfTwoAreas(p,t.fullBranchArea),a[0].fullBranchArea)}getFullAreaUntilAny(u){const i=this.ownEntityPlusBufferArea;return this.children.filter(t=>!u.includes(t)).map(t=>t.getFullAreaUntilAny(u)).reduce((t,y)=>ti.getBoundriesOfTwoAreas(t,y),i)}getFullAreaUntilAreaOrAnyChildren(u){const i=[u,...u.flattenChildren()],a=this.ownEntityPlusBufferArea;return this.children.filter(t=>i.includes(t)).map(t=>t.getFullAreaUntil(u)).reduce((t,y)=>ti.getBoundriesOfTwoAreas(t,y),a)}getFullAreaUntil(u){const i=this.ownEntityPlusBufferArea;return this.children.filter(p=>p!==u).map(p=>p.getFullAreaUntil(u)).reduce((p,t)=>ti.getBoundriesOfTwoAreas(p,t),i)}get fullBranchArea(){const u=this.ownEntityPlusBufferArea;return this.children.map(l=>l.fullBranchArea).reduce((l,p)=>ti.getBoundriesOfTwoAreas(l,p),u)}get ownEntityArea(){return{top:this.entity.y,left:this.entity.x,bottom:this.entity.y+this.entityCardHeight,right:this.entity.x+this.entityCardWidth}}get ownEntityPlusBufferArea(){const u=this.ownEntityArea;return{top:u.top,left:u.left,bottom:u.bottom+Ny,right:u.right+aA}}static filterOutRepeatedAreas(u){return u.filter((i,a)=>u.indexOf(i)===a)}getEarliestId(u,i){const a=u.split("-"),l=i.split("-");return a.length<l.length?u:a.length>l.length?i:a.reduce((t,y,v)=>y<l[v]?u:i,u)}getEarliestLevel(){return this.ids.reduce((a,l)=>this.getEarliestId(a,l),this.ids[0]).split("-").length}countColumns(){let u=0;if(this!==this.calculationEntryPoint)u++;else return u;if(!this.parents.length)return u;const a=this.parents.reduce((l,p)=>p.getEarliestLevel()>l.getEarliestLevel()?p:l,this.parents[0]).countColumns();return u+=a,u}getLatestId(u,i){if(u===i)return u;const a=u.split("-"),l=i.split("-");return a.length<l.length?i:a.length>l.length?u:a.reduce((t,y,v)=>y>l[v]?u:i,u)}getLatestLevel(){return this.ids.length===1?this.ids[0].split("-").length:this.ids.reduce((a,l)=>this.getLatestId(a,l),this.ids[0]).split("-").length}smoothPosition(){const u=this.flattenSiblings();if(!u.length&&this.parents.length<=1&&this.children.length){const i=this.centerHeaderVerticallyOverCombinedAllChildrenHeaderHeight();this.parents.forEach(a=>{a!==this.calculationEntryPoint&&a.shiftDownAlone(i)})}else if([...Ht].includes(this.entity.type)&&this.children.length)this.centerHeaderVerticallyOverCombinedAllChildrenHeaderHeight();else if(!this.children.length&&this.parents.length>1){const i=u.filter(a=>!this.parents.includes(a));i.length?i.every(l=>{const p=this.countColumns(),t=l.countColumns();return p>t})&&this.centerHeaderVerticallyOverCombinedAllParentsHeaderHeight():i.length||this.centerHeaderVerticallyOverCombinedAllParentsHeaderHeight()}}shiftDownUntilAny(u,i){if(u.includes(this))return u;this.move(this.entity,{y:this.entity.y+i});let a=[...u,this];return this.children.forEach(l=>{if(ti.getEarliestParentInChain(l)!==this)return;const t=e0e(a,l.entity.id);a=ti.filterOutRepeatedAreas([...a]),t||(a=a.filter(v=>v!==l));const y=l.shiftDownUntilAny(a,i);a.push(...y)}),a}shiftRightUntilAny(u,i){u.includes(this)||(this.move(this.entity,{x:this.entity.x+i}),this.children.forEach(a=>{const l=ti.filterOutRepeatedAreas([...this.flattenSiblings(),...u]);ti.getEarliestParentInChain(a)===this&&a.shiftRightUntilAny(l,i)}))}shiftRight(u){this.move(this.entity,{x:this.entity.x+u}),this.children.forEach(i=>{const l=i.flattenSiblings().filter(p=>p!==i);i.shiftRightUntilAny(l,u)})}shiftDownAlone(u){this.move(this.entity,{y:this.entity.y+u})}centerHeaderVerticallyOverCombinedAllParentsHeaderHeight(){const u=this.parents.reduce((l,p)=>{const t=p.ownEntityArea,y=t.top+Od,v={top:y,left:t.left,bottom:y,right:t.right};return ti.getBoundriesOfTwoAreas(l,v)},{top:1/0,left:1/0,bottom:-1/0,right:-1/0}),a=(u.bottom-u.top)/2-Od;this.shiftDownAlone(a)}centerHeaderVerticallyOverCombinedAllChildrenHeaderHeight(){const u=this.children.reduce((l,p)=>{const t=p.ownEntityArea,y=t.top+Od,v={top:y,left:t.left,bottom:y,right:t.right};return ti.getBoundriesOfTwoAreas(l,v)},{top:1/0,left:1/0,bottom:-1/0,right:-1/0}),a=(u.bottom-u.top)/2-Od;return this.shiftDownAlone(a),a}resolveChildrenOverlaps(){const u=this.flattenChildren();let i=[];u.forEach(a=>{const l=a.adjustVerticallyToAvoidOverlaps();i.push(...l)}),u.forEach(a=>{a.smoothPosition()})}static getEarliestParentInChain(u){let i=u.parents[0];return u.parents.length&&(i=u.parents.sort((a,l)=>{if(!a.ids.length)return-1;if(!l.ids.length)return 1;const p=a.ids.sort((y,v)=>y.length<v.length?-1:0),t=l.ids.sort((y,v)=>y.length<v.length?-1:0);return p[0].length-t[0].length})[0]),i}flattenEarlierSiblings(u=new Set){return u.add(this.entity.id),this.parents.reduce((a,l)=>{if(u.has(l.entity.id))return a;u.add(l.entity.id);const t=l.children.slice(0,l.children.indexOf(this)).reduce((y,v)=>[...y,v,...v.flattenChildren(u)],[]);return[...a,...t]},[])}flattenSiblings(u=new Set){return u.add(this.entity.id),this.parents.reduce((a,l)=>{if(u.has(l.entity.id))return a;u.add(l.entity.id);const t=l.children.filter(y=>y!==this).reduce((y,v)=>[...y,v,...v.flattenChildren(u)],[]);return[...a,...t]},[])}flattenChildren(u=new Set){return this.children.reduce((i,a)=>u.has(a.entity.id)?i:(u.add(a.entity.id),[...i,a,...a.flattenChildren(u)]),[])}flattenParents(u=new Set){return this.parents.reduce((a,l)=>u.has(l.entity.id)?a:(u.add(l.entity.id),[...a,l,...l.flattenParents(u)]),[])}getAreaIfRendered(u){return this.calculationEntryPoint.flattenChildren().find(l=>l.entity.id===u.id)||null}getLowerSiblings(){const u=this.parents.reduce((i,a)=>{const l=a.children.indexOf(this),p=a.children.slice(l+1);return[...i,...p]},[]);return oF(u)}getLowerAreas(){const u=this.getLowerSiblings(),i=this.parents.reduce((a,l)=>[...a,...l.getLowerAreas()],[]);return oF([...u,...i])}adjustVerticallyToAvoidOverlaps(u=[]){const a=ti.getEarliestParentInChain(this).children[this.index-1];if(!a)return u;const l=this.flattenEarlierSiblings(),p=this.flattenParents(),t=[...l,...p,a],T=R(t.flatMap(N=>Sy(this.entity,N.entity))).filter(N=>N.id!==this.entity.id).map(N=>this.findAreaFromEntity(N)).filter(N=>!!N),w=this.getFullAreaUntilAny(T),A=a.getFullAreaUntilAny(T),V=t.reduce((N,j)=>j===this||j.fullBranchArea.left!==w.left?N:Math.max(N,j.fullBranchArea.bottom),A.bottom);if(w.top<V){const N=V-w.top+Ny;return this.shiftDownUntilAny(u,N)}return u}move(u,i){(this.onlyEntities||[]).includes(u)&&u.metaSync(i,this.changeSet)}addChild(u){const i=this.childEntities[u];let a=null;i.x&&i.y?a=this.getAreaIfRendered(i):!i.x&&!i.y&&this.move(i,{x:this.entity.x,y:this.entity.y}),a||(a=new ti(i,u,this.calculationEntryPoint));const l=this.ownEntityPlusBufferArea;this.children.includes(a)||(this.children.push(a),a.addParent(this));const p=a.fullBranchArea;if(p.left<l.right){const t=l.right-p.left;a.shiftRight(t)}return a}flattenChildEntities(u=new Set){return this.children.reduce((i,a)=>u.has(a.entity.id)?i:(u.add(a.entity.id),[...i,a.entity,...a.flattenChildEntities(u)]),[])}next(u){const i=[];this.childEntities.forEach((a,l)=>{const p=this.addChild(l);p&&i.push(p)}),u(i)}}var Op=(d=>(d.Amazon="amazon",d.Google="google",d.Microsoft="microsoft",d))(Op||{}),$r=(d=>(d.RelationalDatabase="relational-database",d.CompiledLocalCodebase="compiled-local-codebase",d.CloudHostedCodebase="cloud-hosted-codebase",d.HttpApi="http-api",d.HttpEndpoint="http-endpoint",d.ServerlessFunction="serverless-function",d))($r||{}),uA=(d=>(d.Post="post",d.Get="get",d.Acknowledgement="acknowledgment",d.Progress="progress",d.Error="error",d.Complete="complete",d))(uA||{}),rl=(d=>(d.Queued="queued",d.Running="running",d.Success="success",d.Failed="failed",d.CleanedUp="cleaned-up",d.Skipped="skipped",d.AbortedByUser="aborted-by-user",d.UnrecoverableFailure="unrecoverable-failure",d.Reverted="reverted",d.UnpublishingStarted="unpublishing-started",d.Unpublished="unpublished",d))(rl||{}),cA=(d=>(d.Queued="queued",d.Running="running",d.Success="success",d.Failed="failed",d.CleanedUp="cleaned-up",d.UnrecoverableFailure="unrecoverable-failure",d.Reverted="reverted",d.UnpublishingStarted="unpublishing-started",d.Unpublished="unpublished",d))(cA||{}),Qe=(d=>(d.ProjectNotFound="project-not-found",d.ProjectPublishRequestAcknowledged="project-publish-request-acknowledged",d.PublicationStepFailedReasonUnknown="publication-step-failed-reason-unknown",d.DeploymentCompleted="deployment-completed",d.DeploymentStarted="deployment-started",d.DeploymentFailed="deployment-failed",d.AllInfrastructureSuccessfullyProvisioned="all-infrastucture-successfully-provisioned",d.RequestPayloadValidationFailed="request-payload-validation-failed",d.ProjectStateValidationFailedMissingName="project-state-validation-failed-missing-name",d.ProjectStateValidationFailedMissingAnyFunctionality="project-state-validation-failed-missing-any-functionality",d.ProjectAlreadyBeingPublished="project-already-being-published",d.BillingSubscriptionUpdateFailed="billing-subscription-update-failed",d.RelationalDatabaseDeploymentStarted="relational-database-deployment-started",d.RelationalDatabaseDeploymentCompleted="relational-database-deployment-completed",d.RelationalDatabaseDeploymentFailed="relational-database-deployment-failed",d.CreatingNewRelationalDatabase="creating-new-relational-database",d.WaitingForPreviousRelationalDatabaseDeployment="waiting-for-previous-relationa-database-deployment",d.RelationalDatabaseAlreadyExists="relational-database-already-exists",d.RelationalDatabaseDeletionStarted="relational-database-deletion-started",d.RelationalDatabaseDeletionCompleted="relational-database-deletion-completed",d.RelationalDatabaseDeletionFailed="relational-database-deletion-failed",d.WaitingForPreviousRelationalDatabaseDeletion="waiting-for-previous-relationa-database-deletion",d.HttpApiDeploymentStarted="http-api-deployment-started",d.HttpApiDeploymentCompleted="http-api-deployment-completed",d.HttpApiDeploymentFailed="http-api-deployment-failed",d.CreatingNewHttpApi="creating-new-http-api",d.HttpApiAlreadyExists="http-api-already-exists",d.HttpApiDeletionStarted="http-api-deletion-started",d.HttpApiDeletionCompleted="http-api-deletion-completed",d.HttpApiDeletionFailed="http-api-deletion-failed",d.WaitingForPreviousHttpApiDeletion="waiting-for-previous-http-api-deletion",d.BusinessLogicCodebaseDeploymentStarted="business-logic-codebase-deployment-started",d.BusinessLogicCodebaseDeploymentCompleted="business-logic-codebase-deployment-completed",d.BusinessLogicCodebaseDeploymentFailed="business-logic-codebase-deployment-failed",d.BundlingCodebaseForDownload="bundling-codebase-for-download",d.UploadingCodebaseToCloudStorage="uploading-codebase-to-cloud-storage",d.UploadingCodebaseToCloudStorageCompleted="uploading-codebase-to-cloud-storage-completed",d.UploadingCodebaseToCloudStorageFailed="uploading-codebase-to-cloud-storage-failed",d.InfrastructureValuesCodebaseInterpolationStarted="infrastructure-values-codebase-interpolation-started",d.InfrastructureValuesCodebaseInterpolationCompleted="infrastructure-values-codebase-interpolation-completed",d.InfrastructureValuesCodebaseInterpolationFailed="infrastructure-values-codebase-interpolation-failed",d.CodeCompilationStarted="code-compilation-started",d.CodeCompilationCompleted="code-compilation-completed",d.CodeCompilationFailed="code-compilation-failed",d.BundleCodebaseStarted="bundle-codebase-started",d.BundleCodebaseCompleted="bundle-codebase-completed",d.BundleCodebaseFailed="bundle-codebase-failed",d.InstallingCodebaseDependenciesStarted="installing-codebase-dependencies-started",d.InstallingCodebaseDependenciesCompleted="installing-codebase-dependencies-completed",d.InstallingCodebaseDependenciesFailed="installing-codebase-dependencies-failed",d.MigrateRelationalDatabaseStarted="migrate-relational-database-started",d.MigrateRelationalDatabaseCompleted="migrate-relational-database-completed",d.MigrateRelationalDatabaseFailed="migrate-relational-database-failed",d))(Qe||{}),rn=(d=>(d.CodeCompilation="code-compilation",d.RelationalDatabaseDeployment="relational-database-deployment",d.RelationalDatabaseDeletion="relational-database-deletion",d.HttpApiDeployment="http-api-deployment",d.HttpApiDeletion="http-api-deletion",d.InfrastructureValuesCodebaseInterpolation="infrastructure-values-codebase-interpolation",d.BundleCodebase="bundle-codebase",d.MigrateRelationalDatabase="migrate-relational-database",d.BusinessLogicCodebaseDeployment="business-logic-codebase-deployment",d.CodebaseCleanup="codebase-cleanup",d))(rn||{});$r.CloudHostedCodebase,$r.HttpApi,$r.RelationalDatabase,$r.CloudHostedCodebase,$r.CloudHostedCodebase,$r.RelationalDatabase,$r.CloudHostedCodebase,$r.CloudHostedCodebase;function lF(d){return`project-${d}-http-api`}function dF(d){return`entity-${d}-database`}class uF{constructor(u,i,a,l,p,t,y,v,T){D(this,"stepType");D(this,"id");D(this,"resourceType");D(this,"index");D(this,"dependency",[]);D(this,"lastEvent",null);D(this,"lasEventTimestamp",null);D(this,"status",rl.Queued);D(this,"publicationRun");D(this,"resource");this.stepType=u,this.id=i,this.resourceType=a,this.status=l,this.dependency=p,this.index=t,this.lasEventTimestamp=y,this.publicationRun=v,this.resource=T}toJSON(){return{stepType:this.stepType,id:this.id,resourceType:this.resourceType,index:this.index,status:this.status,dependency:this.dependency,lastEvent:this.lastEvent,resource:{resourceId:this.resource.resourceId,resourceType:this.resource.resourceType,provider:this.resource.provider,details:this.resource.details,status:this.resource.status,name:this.resource.name}}}async update(u){var i,a;this.status=u.status,this.dependency=u.dependency,this.index=u.index,this.stepType=u.stepType,this.resourceType=u.resourceType,this.lastEvent=u.lastEvent,this.id=u.id,(a=this.resource)==null||a.setDetails((i=u.resource)==null?void 0:i.details)}}var cF=(d=>(d.Ready="ready",d.Provisioning="provisioning",d.Queued="queued",d.ProvisioningFailed="provisioning-failed",d.Deleting="deleting",d.DeletingFailed="deleting-failed",d.Deleted="deleted",d))(cF||{});class pA{constructor(u,i,a){D(this,"provisionedBy");D(this,"publicationRun");D(this,"resourceType");D(this,"provider");D(this,"resourceId");D(this,"details",null);D(this,"name",null);D(this,"status","queued");this.publicationRun=u,this.resourceType=i,this.provider=a}setDetails(u){this.details=u}setStatus(u){this.status=u}setProvisionedBy(u){this.provisionedBy=u}}class fA extends pA{constructor(i,a,l,p){super(i,l,p);D(this,"resourceType");D(this,"owners",new Map);D(this,"details",null);D(this,"status","queued");a.forEach(t=>{this.owners.set(t.id,t)}),this.resolveDeterministicResourceId()}resolveDeterministicResourceId(){var i,a;return this.resourceType===$r.HttpApi?this.resourceId=lF(this.publicationRun.project.id):this.resourceType===$r.RelationalDatabase&&(this.resourceId=dF((a=(i=Array.from(this.owners.values()))==null?void 0:i[0])==null?void 0:a.id)),this.resourceId}}class hA extends pA{constructor(i,a,l){super(i,a,l);D(this,"resourceType");D(this,"details",null);D(this,"status","queued");this.resolveDeterministicResourceId()}resolveDeterministicResourceId(){return this.resourceType===$r.CompiledLocalCodebase?this.resourceId=`compiled-codebase--${this.publicationRun.project.id}--${this.publicationRun.project.version}--${this.publicationRun.id}`:this.resourceType===$r.CloudHostedCodebase&&(this.resourceId=`cloud-hosted-codebase--${this.publicationRun.project.id}--${this.publicationRun.project.version}`),this.resourceId}}class t0e{constructor(u,i){D(this,"id");D(this,"projectAutoIncrementPublicationCount");D(this,"projectPublishedSemanticVersion");D(this,"projectVersion");D(this,"projectId");D(this,"cloudProvider");D(this,"triggeredBy");D(this,"createdAt");D(this,"updatedAt");D(this,"status");D(this,"steps",[]);D(this,"editor");D(this,"explicitResources",new Map);D(this,"implicitGlobalResources",new Map);D(this,"finalGlobalEvent",null);D(this,"finalStatus",null);this.id=u.id,this.projectAutoIncrementPublicationCount=u.projectAutoIncrementPublicationCount,this.projectPublishedSemanticVersion=u.projectPublishedSemanticVersion,this.projectVersion=u.projectVersion,this.projectId=u.projectId,this.cloudProvider=u.cloudProvider,this.triggeredBy=u.triggeredBy,this.createdAt=u.createdAt,this.updatedAt=u.updatedAt,this.status=u.status,this.editor=i}get project(){return this.editor.project}getInfraTypes(u){return this.steps.filter(i=>u.includes(i.resourceType))}getStepsTypes(u){return this.steps.filter(i=>u.includes(i.stepType))}toIds(u){return u.map(i=>i.id)}getResourceForEntity(u){const i=Array.from(this.explicitResources.values()).find(a=>a.owners.has(u.id));return i||null}async init(){await this.initResources()}async initResources(){this.implicitGlobalResources.set($r.CompiledLocalCodebase,new hA(this,$r.CompiledLocalCodebase,Op.Amazon)),this.implicitGlobalResources.set($r.CloudHostedCodebase,new hA(this,$r.CloudHostedCodebase,Op.Amazon));const u=this.project.entities.filter(a=>Qi(a,Ce.HTTP_ENDPOINT)),i=this.project.entities.filter(a=>Qi(a,Ce.RELATIONAL_DATABASE));if(i.length&&i.forEach(a=>{const l=new fA(this,[a],$r.RelationalDatabase,Op.Amazon);this.explicitResources.set(l.resourceId,l)}),u.length){const a=new fA(this,u,$r.HttpApi,Op.Amazon);this.explicitResources.set(a.resourceId,a)}}setSteps(u,i){u.forEach(a=>{this.addStep(a,i)}),this.editor.events.emit(Qe.ProjectPublishRequestAcknowledged,{})}addStep(u,i){const a=u.dependency||[];if(a.length){const p=a.filter(t=>!this.steps.find(y=>y.id===t));if(p.length)throw new Error(`Missing dependencies: ${p.join(", ")}`)}if(!u.resource)throw new Error(`Resource not found for step ${u.stepType} (${u.id})`);if(!this.steps.find(p=>p.id===u.id)){const p=this.implicitGlobalResources.get(u.resourceType)||this.explicitResources.get(u.resource.resourceId),t=new uF(u.stepType,u.id,u.resourceType,u.status,a,u.index,i,this,p);this.steps.push(t)}}onUpdate(u){var i;if(console.log("onUpdate",u),(i=u.payload)!=null&&i.stepType){const a=this.steps.find(l=>{var p;return l.id===((p=u.payload)==null?void 0:p.id)});a&&L(u.emittedAt).isAfter(L(a.lasEventTimestamp))&&a.update(u.payload)}this.editor.events.emit("publication-updated",{}),u.type===uA.Error?(this.finalStatus=cA.Failed,this.finalGlobalEvent=u.event,this.editor.events.emit("project-publication-error",u)):u.type===uA.Complete&&(this.finalStatus=cA.Success,this.finalGlobalEvent=u.event,this.editor.events.emit("project-publication-completed",u))}}function r0e(d){switch(d){case rn.CodeCompilation:return"Code generation";case rn.RelationalDatabaseDeployment:return"Database creation";case rn.HttpApiDeployment:return"HTTP gateway creation";case rn.InfrastructureValuesCodebaseInterpolation:return"Link code with resources";case rn.BundleCodebase:return"Bundle code";case rn.MigrateRelationalDatabase:return"Database structure migration";case rn.BusinessLogicCodebaseDeployment:return"Update servers with new code";case rn.CodebaseCleanup:return"Code cleanup";case rn.HttpApiDeletion:return"HTTP gateway deletion";case rn.RelationalDatabaseDeletion:return"Database deletion";default:return"Publication finished"}}function i0e(d){switch(d){case Qe.DeploymentCompleted:return"Successfully published";case Qe.DeploymentStarted:return"Publication started";case Qe.DeploymentFailed:return"Publication failed";case Qe.AllInfrastructureSuccessfullyProvisioned:return"All infrastructure successfully provisioned";case Qe.RequestPayloadValidationFailed:return"Request payload validation failed";case Qe.ProjectStateValidationFailedMissingName:return"Project state validation failed: missing name";case Qe.ProjectStateValidationFailedMissingAnyFunctionality:return"Project state validation failed: missing any functionality";case Qe.RelationalDatabaseDeploymentStarted:return"Database creation started";case Qe.RelationalDatabaseDeploymentCompleted:return"Database creation completed";case Qe.RelationalDatabaseDeploymentFailed:return"Database creation failed";case Qe.CreatingNewRelationalDatabase:return"Creating new database (up to 5 mins)";case Qe.WaitingForPreviousRelationalDatabaseDeployment:return"Waiting for previous database creation";case Qe.RelationalDatabaseAlreadyExists:return"Database already exists";case Qe.HttpApiDeploymentStarted:return"HTTP gateway creation started";case Qe.HttpApiDeploymentCompleted:return"HTTP gateway creation completed";case Qe.HttpApiDeploymentFailed:return"HTTP gateway creation failed";case Qe.CreatingNewHttpApi:return"Creating new HTTP gateway";case Qe.HttpApiAlreadyExists:return"HTTP gateway already exists";case Qe.BusinessLogicCodebaseDeploymentStarted:return"Update servers with new code started";case Qe.BusinessLogicCodebaseDeploymentCompleted:return"Update servers with new code completed";case Qe.BusinessLogicCodebaseDeploymentFailed:return"Update servers with new code failed";case Qe.BundlingCodebaseForDownload:return"Bundling code for download";case Qe.UploadingCodebaseToCloudStorage:return"Uploading code to cloud storage";case Qe.InfrastructureValuesCodebaseInterpolationStarted:return"Linking code with resources started";case Qe.InfrastructureValuesCodebaseInterpolationCompleted:return"Linking code with resources completed";case Qe.InfrastructureValuesCodebaseInterpolationFailed:return"Linking code with resources failed";case Qe.CodeCompilationStarted:return"Code generation started";case Qe.CodeCompilationCompleted:return"Code generation completed";case Qe.CodeCompilationFailed:return"Code generation failed";case Qe.BundleCodebaseStarted:return"Code bundling started";case Qe.BundleCodebaseCompleted:return"Code bundling completed";case Qe.BundleCodebaseFailed:return"Code bundling failed";case Qe.InstallingCodebaseDependenciesStarted:return"Installing code dependencies";case Qe.InstallingCodebaseDependenciesCompleted:return"Installing code dependencies completed";case Qe.InstallingCodebaseDependenciesFailed:return"Installing code dependencies failed";case Qe.MigrateRelationalDatabaseStarted:return"Database structure migration started";case Qe.MigrateRelationalDatabaseCompleted:return"Database structure migration completed";case Qe.MigrateRelationalDatabaseFailed:return"Database structure migration failed";case Qe.ProjectAlreadyBeingPublished:return"Project already being published. You need to wait for the previous publication to complete";case Qe.ProjectPublishRequestAcknowledged:return"Project publish request acknowledged";case Qe.UploadingCodebaseToCloudStorageCompleted:return"Uploading code to cloud storage completed";case Qe.UploadingCodebaseToCloudStorageFailed:return"Uploading code to cloud storage failed";case Qe.BillingSubscriptionUpdateFailed:return"Billing subscription update failed";case Qe.ProjectNotFound:return"Project not found";case Qe.HttpApiDeletionCompleted:return"HTTP gateway deletion completed";case Qe.HttpApiDeletionFailed:return"HTTP gateway deletion failed";case Qe.HttpApiDeletionStarted:return"HTTP gateway deletion started";case Qe.PublicationStepFailedReasonUnknown:return"Publication step failed: reason unknown";case Qe.WaitingForPreviousHttpApiDeletion:return"Waiting for previous HTTP gateway deletion";case Qe.RelationalDatabaseDeletionStarted:return"Database deletion started";case Qe.RelationalDatabaseDeletionCompleted:return"Database deletion completed";case Qe.RelationalDatabaseDeletionFailed:return"Database deletion failed";case Qe.WaitingForPreviousRelationalDatabaseDeletion:return"Waiting for previous database deletion"}return"Unknown event"}var pF=(d=>(d.NO_LOGIC="NO_LOGIC",d.NO_NAME="NO_NAME",d.NO_CHANGES="NO_CHANGES",d.PROJECT_PUBLICATION_ALREADY_ONGOING="PROJECT_PUBLICATION_ALREADY_ONGOING",d))(pF||{});function s0e(d){switch(d){case"NO_LOGIC":return"This project has no logic";case"NO_NAME":return"This project has no name";case"NO_CHANGES":return"This version has already been published";case"PROJECT_PUBLICATION_ALREADY_ONGOING":return"This project is already being published";default:return"Publishing is currently not available. Try again later"}}function n0e(d){switch(d){case $r.RelationalDatabase:return"Relational database";case $r.HttpEndpoint:case $r.HttpApi:return"HTTP endpoints";case $r.ServerlessFunction:case $r.CloudHostedCodebase:return"Server code functions";default:return"Resources"}}function a0e(d){switch(d){case rl.Running:return"In progress";case rl.Failed:return"Failed";case rl.Success:return"Succeeded";case rl.Skipped:return"Skipped";case rl.Queued:default:return"Queued"}}function o0e(d,u){let i=null;const a=[];if(!d.id)i={...d,id:P.UUID.uuid()};else if(!MU(d.id)){const y=P.UUID.uuid();i={...d,id:y},a.push(new ee({id:`${d.id}--${q.InvalidUUIDStringFormat}`,message:`Entity with id "${d.id}" has an invalid UUID string format. The 'id' property must be a valid UUID string.
|
|
204
204
|
The 'id' has been changed to "${y}".`,severity:Z.Warning,code:q.InvalidUUIDStringFormat,issue:null}))}if(i={...d,id:(i==null?void 0:i.id)||d.id||""},!d.type)return{errors:[...a,new ee({id:`${i.id}--${q.MissingTypeProperty}`,message:`Entity with id "${i.id}" is missing a 'type' property.`,severity:Z.Error,code:q.MissingTypeProperty,issue:null})],modifiedData:i};if(d.type===f.GenericReference)return{errors:[...a,new ee({id:`${i.id}--${q.RootReference}`,message:`Generic reference entity with id "${i.id}". A generic reference cannot be generated as a standalone entity. Only in the body of another entity.`,severity:Z.Error,code:q.RootReference,issue:null})],modifiedData:i};const l=i,p=u.instances[l.id],t=u.builtInInstances[l.id];if(p&&!t&&l.type!==f.GenericReference){let y=`A previously generated entity with id "${l.id}" already exists in the project state.
|
|
205
205
|
Are you trying to update that entity?
|
|
206
206
|
If so, you should use the 'update' action for core mutable metadata properties, or 'delete' and then 'post' again to replace it.
|
|
@@ -397,7 +397,7 @@ All global 'function-declaration' entity ids are:
|
|
|
397
397
|
The project currently has no global 'function-declaration' entities that can be called as 'function-call' entities.`;p.push(new ee({id:`${l.id}--${q.InvalidReference}`,code:q.InvalidReference,severity:Z.Error,message:`Entity of type "${f.FunctionCall}" with id "${l.id}", has an invalid reference at the 'declaration' property. The 'declaration' property must be a valid reference to an 'function-declaration' entity.
|
|
398
398
|
References can either be an ID string or an object with exacly four properties: 'id', 'entityId', 'entityType', 'type'.${v}`,issue:null}))}return{errors:p,modifiedData:l}}validateGeneratedUpdate(i){const a=[];return i.parent&&a.push(new ee({id:`${this.id}--${q.InvalidParentUpdate}`,code:q.InvalidParentUpdate,severity:Z.Error,message:`Entity of type '${this.type}' with id '${this.id}' cannot have the 'parent' property updated. The 'parent' on a callable entity, is its scope. It scope is auto-calculated implicitly by the its caller.
|
|
399
399
|
If an entity is called by another, they must be in the same scope, which means they have the same parent.
|
|
400
|
-
You shouldn't have to manually update a 'parent' property. The equivalent result is to change its callers, the value writters of its inputs, or the value readers of its outputs.`,issue:null})),{errors:a,modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];if(a==="declaration"){const{updated:T,added:w,removed:A}=this.remove({ignoreUpstream:!1},l);p.push(...T),t.push(...w),y.push(...A)}if(a==="parent"){const{updated:T,added:w,removed:A}=this.remove({ignoreUpstream:!1},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];if(a==="declaration"){const{updated:T,added:w,removed:A}=this.restore({},l);p.push(...T),t.push(...w),y.push(...A)}if(a==="parent"){const{updated:T,added:w,removed:A}=this.restore({},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){var i;return(i=this.parent)==null||i.unsubscribeDependents([{entity:this,field:"parent"}]),this.declaration.unsubscribeDependents([{entity:this,field:"declaration"}]),this}subscribeToDependencies(){var i;return(i=this.parent)==null||i.subscribeDependents([{entity:this,field:"parent"}]),this.declaration.subscribeDependents([{entity:this,field:"declaration"}]),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new xt(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.inputs=[...this.inputs],i.outputs=[...this.outputs],i.error=this.error,i.successCalls=[...this.successCalls],i.errorCalls=[...this.errorCalls],i.process=this.process,i.declaration=this.declaration,i.calledBySuccess=[...this.calledBySuccess],i.calledByError=[...this.calledByError],i.calledByEntry=[...this.calledByEntry],i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new xt(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.inputs=y.inputs,this.outputs=y.outputs,this.error=y.error,this.successCalls=y.successCalls,this.errorCalls=y.errorCalls,this.process=y.process,this.declaration=y.declaration,this.calledBySuccess=y.calledBySuccess,this.calledByError=y.calledByError,this.calledByEntry=y.calledByEntry,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&this.removeFromParent(a),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.declaration){const l=J(i.declaration),p=this.project.get(l);p&&this.setDeclaration(p)}return i.calledByEntry.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addEntryCaller(t,a),t.addCall(this,a))}),[...this.calledByEntry].forEach(l=>{i.calledByEntry.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledBySuccess.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addSuccessCaller(t,a),t.addSuccessCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledByError.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addErrorCaller(t,a),t.addErrorCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(this.initialData.declaration){const t=J(this.initialData.declaration),y=this.project.get(t);y&&(this.setDeclaration(y),i.push(y))}return this.initialData.calledByEntry.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addEntryCaller(v,null)}),this.initialData.calledBySuccess.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addSuccessCaller(v,null)}),this.initialData.calledByError.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addErrorCaller(v,null)}),{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];this.initialized=!0;const{updated:y,added:v,removed:T}=this.syncInputs(i),{updated:w,added:A,removed:V}=this.syncOutputs(i);return a.push(...y,...w),l.push(...v,...A),p.push(...T,...V),this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){var y;const a=[this],l=[],p=[],t=[];return this.parent===this.project&&this.project.addFunctionCall(this),(y=this.process)==null||y.writesValues.forEach(v=>{v.setValueWriter(this.process,i),a.push(v)}),this.successCalls.forEach(v=>{v.addSuccessCaller(this,i),a.push(v)}),this.errorCalls.forEach(v=>{v.addErrorCaller(this,i),a.push(v)}),this.calledBySuccess.forEach(v=>{v.addSuccessCall(this,i),a.push(v)}),this.calledByError.forEach(v=>{v.addErrorCall(this,i),a.push(v)}),this.calledByEntry.forEach(v=>{v.addCall(this,i),a.push(v)}),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}get calledBy(){return[...this.calledByEntry,...this.calledBySuccess,...this.calledByError]}removeInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-input"))){const l=this.inputs.findIndex(p=>p.id===i.id);return l>-1&&(this.inputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-input",this.id),this}addInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-input"))){return this.inputs.includes(i)?(a==null||a.attemptAutoclose("add-input",this.id),this):(this.inputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-input",this.id),this)}addOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-output"))){return this.outputs.includes(i)?(a==null||a.attemptAutoclose("add-output",this.id),this):(this.outputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-output",this.id),this)}removeOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-output"))){const l=this.outputs.findIndex(p=>p.id===i.id);return l>-1&&(this.outputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-output",this.id),this}addValueReader(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-value-reader"))){var l;return this.process&&!this.process.writesValues.includes(i)&&((l=this.process)==null||l.addValueReader(i,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-value-reader",this.id),this}removeValueReader(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-value-reader"))){var l;return this.process&&this.process.writesValues.includes(i)&&((l=this.process)==null||l.removeValueReader(i,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("remove-value-reader",this.id),this}addSuccessCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-caller")),l=!1){return this.calledBySuccess.find(p=>p.id===i.id)||(this.calledBySuccess.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-success-caller",this.id),this}addErrorCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-caller")),l=!1){return this.calledByError.find(p=>p.id===i.id)||(this.calledByError.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-error-caller",this.id),this}addEntryCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-entry-caller")),l=!1){return this.calledByEntry.find(p=>p.id===i.id)||(this.calledByEntry.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-entry-caller",this.id),this}addErrorCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-call")),l=!1){return this.errorCalls.find(p=>p.id===i.id)||(this.errorCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-error-call",this.id),this}addSuccessCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-call")),l=!1){return this.successCalls.find(p=>p.id===i.id)||(this.successCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-success-call",this.id),this}removeCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-call")),l=!1){const p=this.successCalls.findIndex(y=>y.id===i.id);p>-1&&(this.successCalls.splice(p,1),a==null||a.add(this,K.Affected));const t=this.errorCalls.findIndex(y=>y.id===i.id);return t>-1&&(this.errorCalls.splice(t,1),a==null||a.add(this,K.Affected)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-call",this.id),this}removeCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-caller")),l=!1){return this.calledBySuccess=this.calledBySuccess.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByError=this.calledByError.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByEntry=this.calledByEntry.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-caller",this.id),this}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}setDeclaration(i){return this.declaration=i,this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){if(this.initialized||this.startedInitialization)return this;if(this.startedInitialization=!0,this.initialData.declaration.type===f.FunctionDeclaration){const a=te(this.initialData.declaration,this.project);this.declaration=a}else{const a=J(this.initialData.declaration),l=this.project.get(a);this.declaration=l}return this.successCalls=this.initialData.successCalls.map(a=>{const l=te(a,this.project);if(l.addSuccessCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.errorCalls=this.initialData.errorCalls.map(a=>{const l=te(a,this.project);if(l.addErrorCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.inputs=this.initialData.inputs.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.initialData.process&&(this.process=te(this.initialData.process,this.project),this.process.setParent(this,null),this.process.initChildren(i)),this.initialData.error&&(this.error=te(this.initialData.error,this.project),this.error.setParent(this,null),this.error.initChildren(i)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.x=i.x||p.x,this.y=i.y||p.y,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await xt.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await xt.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await xt.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await xt.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await xt.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await xt.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){const a=[],l=[],p=[],t=[];return this.parent.type===f.Project?(this.parent.removeFunctionCall(this),t.push(this.parent)):this.parent.detachedChildren.includes(this)&&this.parent.unsubscribeDetachedChild(this),i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){var v;const l=[],p=[],t=[],y=[];if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(T=>{const{updated:w,removed:A,added:V}=T.entity.onDetachedDependencyRemoved(this,T.field,a);l.push(...w),p.push(...A),t.push(...V)}),this.process){const{updated:T,removed:w}=(v=this.process)==null?void 0:v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(this.inputs.forEach(T=>{const{updated:w,removed:A}=T.remove({ignoreUpstream:!0},a);l.push(...w),p.push(...A)}),this.outputs.forEach(T=>{const{updated:w,removed:A}=T.remove({ignoreUpstream:!0},a);l.push(...w),p.push(...A)}),this.error){const{updated:T,removed:w}=this.error.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(this.successCalls.forEach(T=>{l.push(T),T.removeCaller(this,a)}),this.errorCalls.forEach(T=>{l.push(T),T.removeCaller(this,a)}),!i){const T=this.removeFromParent(a);t.push(...T.added),l.push(...T.updated),p.push(...T.removed),y.push(...T.affected),this.calledBy.forEach(w=>{l.push(w),w.removeCall(this,a)})}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){const a=[],l=[],p=[],t=[];if(i!=null&&i.hasAdded(this.id))return i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(y=>{const{updated:v,removed:T,added:w}=y.entity.onDetachedDependencyRestored(this,y.field,i);l.push(...v),p.push(...T),a.push(...w)}),this.process){const{updated:y}=this.process.restore({},i);l.push(...y)}return this.inputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.outputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.successCalls.forEach(y=>{l.push(y),y.addSuccessCaller(this,i)}),this.errorCalls.forEach(y=>{l.push(y),y.addErrorCaller(this,i)}),this.calledBySuccess.forEach(y=>{l.push(y),y.addSuccessCall(this,i)}),this.calledByError.forEach(y=>{l.push(y),y.addErrorCall(this,i)}),this.calledByEntry.forEach(y=>{l.push(y),y.addCall(this,i)}),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this}}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.successCalls.flatMap(l=>l.toFlat(i)),...this.errorCalls.flatMap(l=>l.toFlat(i)),...this.inputs.flatMap(l=>l.toFlat(i)),...this.outputs.flatMap(l=>l.toFlat(i)),...this.process?this.process.toFlat(i):[],...this.error?this.error.toFlat(i):[],...this.calledBy.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.successCalls.flatMap(l=>l.toFlatIds(i)),...this.errorCalls.flatMap(l=>l.toFlatIds(i)),...this.inputs.flatMap(l=>l.toFlatIds(i)),...this.outputs.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,x:this.x,y:this.y,type:this.type}}toJSON(i=new Set){var a,l;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,successCalls:this.successCalls.map(p=>p.toJSON(i)),errorCalls:this.errorCalls.map(p=>p.toJSON(i)),calledBySuccess:this.calledBySuccess.map(p=>p.toReference()),calledByError:this.calledByError.map(p=>p.toReference()),calledByEntry:this.calledByEntry.map(p=>p.toReference()),process:(a=this.process)==null?void 0:a.toJSON(i),declaration:this.declaration.toJSON(i),inputs:this.inputs.map(p=>p.toJSON(i)),outputs:this.outputs.map(p=>p.toJSON(i)),parent:this.parent.toReference(),error:(l=this.error)==null?void 0:l.toJSON(i)})}toJSONClone(i=Le){var l,p,t,y,v,T,w;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),previousVersion:null,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,successCalls:this.successCalls.map(A=>A.toJSONClone({...i,newId:null})),errorCalls:this.errorCalls.map(A=>A.toJSONClone({...i,newId:null})),calledBySuccess:this.calledBySuccess.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByError:this.calledByError.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByEntry:this.calledByEntry.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),process:(T=this.process)==null?void 0:T.toJSONClone({...i,newId:null}),declaration:this.declaration.toJSONClone({...i,newId:null}),inputs:this.inputs.map(A=>A.toJSONClone({...i,newId:null})),outputs:this.outputs.map(A=>A.toJSONClone({...i,newId:null})),error:(w=this.error)==null?void 0:w.toJSONClone({...i,newId:null}),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,process:this.process?this.process.toReference(i):null,inputs:this.inputs.map(p=>p.toReference(i)),outputs:this.outputs.map(p=>p.toReference(i)),declaration:this.declaration.toReference(i),successCalls:this.successCalls.map(p=>p.toReference(i)),errorCalls:this.errorCalls.map(p=>p.toReference(i)),calledBySuccess:this.calledBySuccess.map(p=>p.toReference(i)),calledByError:this.calledByError.map(p=>p.toReference(i)),calledByEntry:this.calledByEntry.map(p=>p.toReference(i)),error:this.error?this.error.toReference(i):null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.successCalls.flatMap(l=>l.toFlatJSON(i)),...this.errorCalls.flatMap(l=>l.toFlatJSON(i)),...this.inputs.flatMap(l=>l.toFlatJSON(i)),...this.outputs.flatMap(l=>l.toFlatJSON(i)),...this.process?this.process.toFlatJSON(i):[],...this.error?this.error.toFlatJSON(i):[]])}toGenerationTarget(){const i=this.parent.type===f.Project?void 0:this.parent.id;return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,calledByEntry:this.calledByEntry.map(a=>a.id),calledBySuccess:this.calledBySuccess.map(a=>a.id),calledByError:this.calledByError.map(a=>a.id),declaration:this.declaration.id,parent:i}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.successCalls.flatMap(l=>l.toFlatGenerationTarget(i)),...this.errorCalls.flatMap(l=>l.toFlatGenerationTarget(i)),...this.inputs.flatMap(l=>l.toFlatGenerationTarget(i)),...this.outputs.flatMap(l=>l.toFlatGenerationTarget(i)),...this.process?this.process.toFlatGenerationTarget(i):[],...this.error?this.error.toFlatGenerationTarget(i):[]])}clearErrors(){var i,a;return this.errors=[],this.inputs.forEach(l=>l.clearErrors()),this.outputs.forEach(l=>l.clearErrors()),this.successCalls.forEach(l=>l.clearErrors()),this.errorCalls.forEach(l=>l.clearErrors()),(i=this.process)==null||i.clearErrors(),(a=this.error)==null||a.clearErrors(),this}validate(){const i=gF(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.inputs.flatMap(a=>a.getErrors()),...this.outputs.flatMap(a=>a.getErrors()),...this.error?this.error.getErrors():[],...this.process?this.process.getErrors():[]]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var j,k;let t=gr(a,this);const y=this.toJSON(),v=l||P.UUID.uuid();y.inputs=[];const T=v.split("-id"),w=T[T.length-1||0]||v;y.id=v,y.version=P.UUID.uuid(),y.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),y.author=(i==null?void 0:i.author)||"1",y.previousVersion=null,y.deleted=!1;const A=St(y,t);a?A.setParent(a,null):A.setParent(this.parent,null),p&&A.subscribe(),A.initChildren(i),i==null||i.add(A,K.Added);const V=(j=this.inputs)==null?void 0:j.map((S,W)=>S.clone(i,A,w+"-input-map-"+W+"-id",p));A.inputs=V;const N=(k=this.outputs)==null?void 0:k.map((S,W)=>S.clone(i,A,w+"-output-map-"+W+"-id",p));return A.outputs=N,this.error&&(A.error=this.error.clone(i,A,w+"-error-map-id",p)),this.process&&(A.process=this.process.clone(i,A,w+"-process-id",p)),i==null||i.attemptAutoclose("clone-entity",this.id),A}removeUnrecognizedInputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-unrecognized-inputs"))){const a=[],l=[],p=[],t=[];return this.inputs.forEach(v=>{if(!this.declaration.inputs.find(w=>{var A;return w.id===((A=v.declaration)==null?void 0:A.id)})){const w=v.remove({ignoreUpstream:!1},i);p.push(...w.removed),a.push(...w.updated)}}),this.inputs.filter((v,T)=>{const w=this.inputs.findIndex(V=>V.declaration===v.declaration&&V!==v);if(w===-1)return!1;const A=this.inputs[w];return L(A==null?void 0:A.createdAt).isSame(L(v.createdAt))?T>w:!!L(A==null?void 0:A.createdAt).isAfter(v.createdAt)}).forEach(v=>{const T=v.remove({ignoreUpstream:!1},i);p.push(...T.removed),a.push(...T.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-inputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}removeUnrecognizedOutputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-unrecognized-outputs"))){const a=[],l=[],p=[],t=[];return this.outputs.forEach(v=>{if(!this.declaration.getUniqueReturnDeclarations().find(w=>{var A;return w.id===((A=v.declaration)==null?void 0:A.id)})){const w=v.remove({ignoreUpstream:!1},i);p.push(...w.removed),a.push(...w.updated)}}),this.outputs.filter((v,T)=>{const w=this.outputs.findIndex(V=>V.declaration===v.declaration&&V!==v);if(w===-1)return!1;const A=this.outputs[w];return L(A==null?void 0:A.createdAt).isSame(L(v.createdAt))?T>w:!!L(A==null?void 0:A.createdAt).isAfter(v.createdAt)}).forEach(v=>{const T=v.remove({ignoreUpstream:!1},i);p.push(...T.removed),a.push(...T.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-outputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncInputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-missing-fixed-inputs"))){const a=[],l=[],p=[],t=[],y=this.declaration.inputs.filter(A=>!this.inputs.find(V=>V.declaration.id===A.id));this.inputs.sort((A,V)=>A.index-V.index),y.forEach(A=>{this.inputs.forEach(j=>{j.index>=A.index&&j.metaSync({index:j.index+1},i)});const V={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,declaration:A.toJSON(),readsValue:null,defaultValue:null,index:A.index,name:null,codeName:null,description:null,parent:this.toReference()},N=te(V,this.project);N.setParent(this,i),N.initChildren(i),i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N)}),this.inputs.sort((A,V)=>A.index-V.index);const{updated:v,added:T,removed:w}=this.removeUnrecognizedInputs(i);return a.push(...v),l.push(...T),p.push(...w),i==null||i.attemptAutoclose("sync-missing-fixed-inputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncOutputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-missing-fixed-outputs"))){const a=[],l=[],p=[],t=[],y=[];this.outputs=this.initialData.outputs.reduce((V,N)=>{if(N.type===f.GenericReference){const k=Ri(N,this.project);return k?[...V,k]:V}const j=te(N,this.project);return y.push(j.index),j.setParent(this,null),j.initChildren(i),[...V,j]},[]);const v=this.declaration.getUniqueReturnDeclarations().filter(V=>!this.outputs.find(N=>N.declaration.id===V.id));this.outputs.sort((V,N)=>V.index-N.index),v.forEach((V,N)=>{this.outputs.forEach(W=>{W.index>=V.index&&W.index++});const j=y.includes(V.index)?this.outputs.length-1+N:V.index,k={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.OutputMap,declaration:V.toJSON(),defaultValue:null,writesValues:[],index:j,parent:this.toReference()},S=te(k,this.project);S.setParent(this,i),S.initChildren(i),i==null||i.add(S,K.Added),S.addSelfToProject(i)}),this.outputs.sort((V,N)=>V.index-N.index);const{updated:T,added:w,removed:A}=this.removeUnrecognizedOutputs(i);return a.push(...T),l.push(...w),p.push(...A),i==null||i.attemptAutoclose("sync-missing-fixed-outputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}getUnusedInputs(){return this.inputs.filter(i=>i.suggestion||!i.readsValue&&!i.defaultValue)}getUnusedOutputs(){return this.outputs.filter(i=>i.suggestion||!i.writesValues.length)}getUsedInputs(){return this.inputs.filter(i=>!i.suggestion&&(i.readsValue||i.defaultValue))}getUsedOutputs(){return this.outputs.filter(i=>!i.suggestion&&i.writesValues.length)}};D(xt,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(xt,"type",f.FunctionCall),D(xt,"USER_MANAGED_PARENT_TYPES",[...wr,f.Project]),D(xt,"PARENT_TYPES",[...xt.USER_MANAGED_PARENT_TYPES]),D(xt,"MUTABLE_BASE_PROPERTIES",[]),D(xt,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),D(xt,"BASE_PROPERTIES",[...xt.MUTABLE_BASE_PROPERTIES,...xt.INMUTABLE_BASE_PROPERTIES]),D(xt,"MUTABLE_META_PROPERTIES",["x","y"]),D(xt,"INMUTABLE_META_PROPERTIES",[...xt.INMUTABLE_BASE_PROPERTIES]),D(xt,"META_PROPERTIES",[...xt.MUTABLE_META_PROPERTIES,...xt.INMUTABLE_META_PROPERTIES]),D(xt,"MUTABLE_UPSTREAM_PROPERTIES",["calledBySuccess","calledByError","calledByEntry"]),D(xt,"INMUTABLE_UPSTREAM_PROPERTIES",["declaration","parent"]),D(xt,"UPSTREAM_PROPERTIES",[...xt.MUTABLE_UPSTREAM_PROPERTIES,...xt.INMUTABLE_UPSTREAM_PROPERTIES]),D(xt,"MUTABLE_DOWNSTREAM_PROPERTIES",["successCalls","errorCalls","writesValues","inputs","outputs","error"]),D(xt,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(xt,"DOWNSTREAM_PROPERTIES",[...xt.MUTABLE_DOWNSTREAM_PROPERTIES,...xt.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(xt,"PROPERTIES",[...xt.META_PROPERTIES,...xt.UPSTREAM_PROPERTIES,...xt.DOWNSTREAM_PROPERTIES]);let Xa=xt;function gA(d){return d&&typeof d.then=="function"}function A0e(d){const u=new Cn(d[0]),i=d.map(l=>l.id),a={};return d.forEach(l=>{a[l.id]=l}),u.order=i,u.flatRecord=a,u.orderEntities(),u.order.map(l=>u.flatRecord[l])}function I0e(d){const u=new Cn(Object.values(d)[0]),i=Object.keys(d);return u.order=i,u.flatRecord=d,u.orderEntities(),u.order}class Cn{constructor(u){D(this,"order",[]);D(this,"flatRecord",{});D(this,"allBuiltInEntityIds",Vs());D(this,"onGoingVisits",{});u&&(this.flatten(u),this.orderEntities())}flatten(u){const i=new Set(Vs()),a=R(ye(u,i,{ignoreBuiltInBaseEntities:!0})),l=new Set;for(const p of a)this.flatRecord[p.id]=p,l.add(p.id);this.order=Array.from(l)}moveEntityAfterDependencies(u){const{upstream:i}=$d(u,this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds});for(const a of Object.keys(i)){const l=this.order.indexOf(a),p=this.order.indexOf(u.id);if(l>p)return this.order.splice(p,1),this.order.splice(l,0,u.id),!0}return!1}orderEntities(){let u=!1;for(let i=0;i<this.order.length;i++){const a=this.order[i],l=this.flatRecord[a];if(l||console.warn(`Entity with id ${a} not found in flatRecord. Skipping...`),this.moveEntityAfterDependencies(l)){u=!0;break}}u&&this.orderEntities()}getUpstreamOngoingDependenciesVisits(u,i){const{upstream:a}=$d(this.flatRecord[u],this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds}),l={};return Object.entries(this.onGoingVisits[i]||{}).forEach(([p,t])=>{Object.keys(a).includes(p)&&(l[p]=t)}),l}getDownstreamOngoingDependenciesVisits(u,i){const a=Object.keys(this.onGoingVisits[i]||{}),l=new Set(a.flatMap(t=>Object.keys($d(this.flatRecord[t],this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds}).downstream))),p={};return Array.from(l).forEach(t=>{t===u&&(p[t]=this.onGoingVisits[i][t])}),p}async settlePromises(u,i){const a=Object.values(u);a.length&&await Promise.all(a),Object.keys(u).forEach(l=>{delete this.onGoingVisits[i][l]})}visit(u){const i=this.order;for(const a of i)u(this.flatRecord[a],this.flatRecord);return this}reverseVisit(u){const i=this.order.slice().reverse();for(const a of i)u(this.flatRecord[a],this.flatRecord);return this}async visitAsync(u){const i=this.order,a=Math.random().toString(36).substring(7);this.onGoingVisits[a]={};for(const l of i){const p=this.getUpstreamOngoingDependenciesVisits(l,a);Object.keys(p).length&&await this.settlePromises(p,a);const t=u(this.flatRecord[l],this.flatRecord);gA(t)&&(this.onGoingVisits[a][l]=t)}return await this.settlePromises(this.onGoingVisits[a],a),this.onGoingVisits[a]={},this}async reverseVisitAsync(u){const i=this.order.slice().reverse(),a=Math.random().toString(36).substring(7);this.onGoingVisits[a]={};for(const l of i){const p=this.getDownstreamOngoingDependenciesVisits(l,a);Object.keys(p).length&&await this.settlePromises(p,a);const t=u(this.flatRecord[l],this.flatRecord);gA(t)&&(this.onGoingVisits[a][l]=t)}return await this.settlePromises(this.onGoingVisits[a],a),this.onGoingVisits[a]={},this}}function DF(d,u){switch(d.id){case ve["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.id:{const i=d.project.entities.filter(v=>!!v.implements.find(T=>T.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id)),a=i.find(v=>{const T=v.properties.find(V=>V.implements&&V.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),w=T==null?void 0:T.getDefaultValue();return(w==null?void 0:w.value)===!0});if(!a&&i.length){const T=i[0].properties.find(A=>A.implements&&A.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),w=T==null?void 0:T.defaultValue;if(w)w.metaSync({value:!0},u);else if(T!=null&&T.dataType){const A={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(u==null?void 0:u.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.LiteralValue,standaloneParent:null,name:Q.EntityTemplate,autogeneration:null,value:!0,valueAsTypeSingle:null,valueAsTypeList:null,parent:T==null?void 0:T.toReference()},V=te(A,d.project);return V.setParent(T,u),V.initChildren(u),u==null||u.add(V,K.Added),V.addSelfToProject(u),{newEntities:[V]}}return{newEntities:[]}}else if(a)return{newEntities:[]};const l=d.project.get(ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id),p=Ky(l,"Main database",u);if(p.errors.length>0)return{newEntities:[]};const t=p.properties.find(v=>v.implements&&v.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),y=t==null?void 0:t.defaultValue;if(y)y.metaSync({value:!0},u);else if(t!=null&&t.dataType){const v={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(u==null?void 0:u.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.LiteralValue,standaloneParent:null,name:Q.EntityTemplate,autogeneration:null,value:!0,valueAsTypeSingle:null,valueAsTypeList:null,parent:t==null?void 0:t.toReference()},T=te(v,d.project);T.setParent(t,u),T.initChildren(u),u==null||u.add(T,K.Added),T.addSelfToProject(u)}return{newEntities:[p]}}}return{newEntities:[]}}function OF(d,u){const i=[],a=[],l=[],p=[];return d.implements.filter(y=>y.type===f.BuiltInBaseEntity).forEach(y=>{var v;switch(y.id){case ve["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.id:{const T=d.project.entities.filter(N=>N.implements.find(j=>j.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id));let w=T.find(N=>!!N.properties.find(j=>{var k;return j.implements&&j.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id&&((k=j.getDefaultValue())==null?void 0:k.value)===!0}));if(!w&&T.length)w=T[0];else if(!w&&!T.length){w=d.project.getBuiltIn(ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id).implement("Relational database",u);const j=w.properties.find(k=>{var S;return((S=k.implements)==null?void 0:S.id)===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id});(v=j==null?void 0:j.defaultValue)==null||v.metaSync({value:!0},u),a.push(w)}const A=d.properties.find(N=>N.implements&&N.implements.id===ve["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.properties.database.id),V=A==null?void 0:A.defaultValue;if(A&&!V){const N={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(u==null?void 0:u.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.LiteralValue,standaloneParent:null,name:Q.EntityTemplate,autogeneration:null,value:null,valueAsTypeSingle:(w==null?void 0:w.toJSON())||null,valueAsTypeList:null,parent:A==null?void 0:A.toReference()},j=te(N,d.project);j.hydrateAncestors(),j.setParent(A,u),j.addSelfToProject(u),j.initChildren(u),u==null||u.add(j,K.Added),a.push(j);return}else V&&!V.valueAsTypeSingle&&V.setValueAsTypeSingle(w||null,u);return}}}),{self:d,updated:R(i),added:R(a),removed:R(l),affected:R(p)}}function Ky(d,u,i,a){const l=a||P.UUID.uuid(),p=P.UUID.uuid(),t={id:l,version:p,createdAt:(i==null?void 0:i.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:u,type:f.DefinitionEntity,codeName:null,description:null,static:d.static,abstract:!1,properties:[],methods:[],abstractMethods:[],extends:[],implements:[d.toJSON()],x:0,y:0,parent:d.project.toReference()};DF(d,i);const y=te(t,d.project);return y.hydrateAncestors(),i==null||i.add(y,K.Added),y.addSelfToProject(i),y.addImplementation(d),y.setParent(d.project,i),y.initChildren(i),OF(y,i),y}function _A(d,u){return u.entities.find(l=>{const p=l.properties,t=p.map(A=>A.name),y=d.every(A=>t.includes(A)),v=t.filter(A=>!d.includes(A)),T=p.every(A=>!v.includes(A.name)||!A.required);return y&&T})||null}function CF(d,u,i,a=Yr.OrDataTypeGroup){const l=[],p=[],t=[],y=[],T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:null,implementationChooseOne:!1,entity:d.toJSON(),isList:!1,asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:null,interactiveEntities:null,actionEntities:null,like:!0,inferred:!1,parentRelationType:a,parent:u.toReference()},w=te(T,d.project);return p.push(w),w.setParent(u,i),w.initChildren(i),i==null||i.add(w,K.Added),w.setEntity(d,i),w.addSelfToProject(i),{updated:R(l),added:R(p),removed:R(t),affected:R(y),self:w}}function DA(d,u,i,a,l){var T,w,A,V,N,j,k,S;const p=[],t=[],y=[],v=[];switch(typeof d){case"string":let W=!1;const ne=new Date(d);if(ne instanceof Date&&!isNaN(ne.valueOf())&&(W=!0),W){const re=u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Date].id);u.setEntity(re,a);break}else{const re=u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.String].id);u.setEntity(re,a);break}case"number":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Number].id),a);break;case"boolean":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Boolean].id),a);break;case"object":if(d===null){u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Null].id),a);break}else if(Array.isArray(d))if(u.metaSync({isList:!0},a),d.length>0){const re=d.slice(0,5).filter(se=>se!==void 0);if(re.every(se=>typeof se==typeof re[0])&&(typeof re[0]!="object"||re[0]===null))switch(typeof re[0]){case"string":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.String].id),a);break;case"number":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Number].id),a);break;case"boolean":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Boolean].id),a);break;case"object":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Null].id),a);break}else{const se=[];let he=!1;re.forEach(z=>{var ce,H,de,Te;if(Array.isArray(z)&&(he=!0),typeof z=="object"&&!Array.isArray(z)&&z!==null){const Ne=ky(z,u.project,{...i,id:P.UUID.uuid()},a,l);Ne.hasCreated&&se.push((ce=Ne.changeSet)==null?void 0:ce.self),p.push(...(H=Ne.changeSet)==null?void 0:H.updated),t.push(...(de=Ne.changeSet)==null?void 0:de.added),y.push(...(Te=Ne.changeSet)==null?void 0:Te.removed)}});const X=R(se);if(!X.length&&!he){re.forEach(z=>{const ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:null,implementationChooseOne:!1,entity:null,isList:!1,asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:!1,interactiveEntities:!0,actionEntities:!1,like:!0,inferred:!1,parentRelationType:Yr.OrDataTypeGroup,parent:u.toReference()},H=te(ce,u.project);switch(H.setParent(u,a),H.initChildren(a),a==null||a.add(H,K.Added),H.addSelfToProject(a),typeof z){case"string":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.String].id),a);break;case"number":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Number].id),a);break;case"boolean":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Boolean].id),a);break;case"object":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Null].id),a);break}});break}else X.length===1&&!he?u.setEntity(X[0],a):re.forEach(z=>{if(typeof z=="object"&&!Array.isArray(z)&&z!==null){const ce=_A(Object.keys(z),u.project);if(ce){const H=CF(ce||X[0],u,a,Yr.OrDataTypeGroup);p.push(...H.updated),t.push(...H.added),y.push(...H.removed)}}else{const ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:null,implementationChooseOne:!1,entity:null,isList:Array.isArray(z),asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:!1,interactiveEntities:!0,actionEntities:!1,like:!0,inferred:!1,parentRelationType:Yr.OrDataTypeGroup,parent:u.toReference()},H=te(ce,u.project);H.setParent(u,a),H.initChildren(a),a==null||a.add(H,K.Added),H.addSelfToProject(a);const de=DA(z,H,{...i,id:P.UUID.uuid()},a,l);p.push(...de.updated),t.push(...de.added),y.push(...de.removed)}})}}else{const re=ky(d[0],u.project,{...i},a,l);u.setEntity((T=re.changeSet)==null?void 0:T.self,a),p.push(...(w=re.changeSet)==null?void 0:w.updated),t.push(...(A=re.changeSet)==null?void 0:A.added),y.push(...(V=re.changeSet)==null?void 0:V.removed);break}else{const re=ky(d,u.project,{...i},a,l);u.setEntity((N=re.changeSet)==null?void 0:N.self,a),p.push(...(j=re.changeSet)==null?void 0:j.updated),t.push(...(k=re.changeSet)==null?void 0:k.added),y.push(...(S=re.changeSet)==null?void 0:S.removed);break}}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:u}}function ky(d,u,i,a,l){const p=[],t=[],y=[],v=[],T=Object.keys(d),w=_A(T,u);if(w)return{hasCreated:!1,changeSet:{updated:[],added:[],removed:[],affected:[],self:w}};const A=l?i.name+" of "+l.name:i.name,N={id:i.id||P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:A,codeName:null,type:f.DefinitionEntity,description:i.description||null,static:i.static||!1,abstract:i.abstract||!1,properties:[],methods:[],abstractMethods:[],extends:[],implements:[],x:0,y:0,parent:u.toReference()},j=te(N,u);return j.setParent(u,a),j.initChildren(a),a==null||a.add(j,K.Added),j.addSelfToProject(a),t.push(j),T.forEach((k,S)=>{const ne={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:k,type:f.Property,codeName:k,description:null,static:!1,abstract:!1,defaultValue:null,constant:!1,interactive:!0,dataType:null,implements:null,extends:null,index:S,hidden:!1,private:!1,required:!0,parent:j.toReference()},re=te(ne,u);re.setParent(j,a),re.initChildren(a),a==null||a.add(re,K.Added),re.addSelfToProject(a),t.push(re);const pe=d[k],he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,parentRelationType:null,options:null,implementationChooseOne:!1,entity:null,isList:!1,asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:!1,interactiveEntities:!0,actionEntities:!1,like:!0,inferred:!1,parent:re.toReference()},X=te(he,u);X.setParent(re,a),X.initChildren(a),a==null||a.add(X,K.Added),X.addSelfToProject(a),t.push(X);const z=DA(pe,X,{...i,name:k,id:P.UUID.uuid()},a,l||j);p.push(...z.updated),t.push(...z.added),y.push(...z.removed)}),{hasCreated:!0,changeSet:{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:j}}}function ma(d,u,i,a){const l=[];return!d.length||!u.length?{errors:l,overlap:!1}:(d.length>u.length?d.forEach(p=>{const t=u.find(v=>v.name===p.name),y=u.find(v=>{var T,w;return!!p.implements&&((T=v.implements)==null?void 0:T.id)===((w=p.implements)==null?void 0:w.id)});if(t){const v=new Zt({id:p.id+"--"+t.id+"--"+a,message:`Entity of type ${p.type} named "${p.name}" with id "${p.id}" overrides a base ${t.type} ${t.name} with id "${t.id}" that has the same name`,issue:null,severity:Z.Error,code:a,entity:p,firstRelationship:t});l.push(v)}if(y){const v=new Zt({id:p.id+"--"+y.id+"--"+i,message:`Entity of type ${p.type} named "${p.name}" with id "${p.id}" overrides a base ${y.type} ${y.name} with id "${y.id}" that implements the same base descriptor`,issue:null,severity:Z.Error,code:i,entity:p,firstRelationship:y});l.push(v)}}):u.forEach(p=>{var v;const t=d.find(T=>T.name===p.name),y=d.find(T=>{var w,A;return!!T.implements&&((w=T.implements)==null?void 0:w.id)===((A=p.implements)==null?void 0:A.id)});if(t){const T=new Zt({id:t.id+"--"+p.id+"--"+a,message:`Entity of type ${t.type} named "${t.name}" with id "${t.id}" overrides a base entity ${p.name} with id "${p.id}" that has the same name`,issue:null,severity:Z.Error,code:a,entity:t,firstRelationship:p});l.push(T)}if(y){const T=new Zt({id:y.id+"--"+p.id+"--"+i,message:`Entity of type ${y.type} named "${y.name}" with id "${y.id}" overrides a base entity ${p.name} with id "${p.id}" that implements the same base ${(v=y==null?void 0:y.implements)==null?void 0:v.type}`,issue:null,severity:Z.Error,code:i,entity:y,firstRelationship:p});l.push(T)}}),{errors:l,overlap:!!l.length})}function w0e(d,u){return d.abstract||(d.properties.forEach(a=>{a.abstract||a.metaSync({abstract:!0},u)}),Object.values(d.detachedDependents).forEach(a=>{a.field===Ib.Entity&&a.entity.remove({ignoreUpstream:!1},u)}),d.metaSync({abstract:!0},u)),d}function R0e(d,u){return d.abstract&&(d.properties.forEach(a=>{a.abstract&&a.metaSync({abstract:!1},u)}),Object.values(d.detachedDependents).forEach(a=>{(a.field===tm.Implements||a.field===tm.Extends)&&a.entity.onDetachedDependencyRemoved(d,a.field,u)}),d.metaSync({abstract:!1},u)),d}function g0e(d,u){return d.static||(d.properties.forEach(a=>{a.static||a.metaSync({static:!0},u)}),d.metaSync({static:!0},u)),d}function _0e(d,u){return d.static&&d.metaSync({static:!1},u),d}var $F=(d=>(d.StringValueMustNotHaveSpaces="string-value-must-not-have-spaces",d.StringValueMustNotHaveDashes="string-value-must-not-have-dashes",d))($F||{});function PF(d,u){const i=[],a=u;if(!a)return{errors:i,override:u};if(typeof a!="string")return{errors:[],override:u};if(a.includes(" ")){const l=new Zt({id:d.id+"--string-value-must-not-have-spaces",message:`Entity of type ${d.type} with id "${d.id}" has an invalid value "${u}". The value cannot contain spaces.`,issue:null,severity:Z.Error,code:"string-value-must-not-have-spaces",entity:d});i.push(l)}return{errors:i,override:a.replace(/\s/g,"-")}}function VF(d,u){const i=[],a=u;if(!a)return{errors:i,override:u};if(typeof a!="string")return{errors:[],override:u};if(a.includes(" ")){const l=new Zt({id:d.id+"--string-value-must-not-have-spaces",message:`Entity of type ${d.type} with id "${d.id}" has an invalid value "${u}". The value cannot contain spaces or dashes.`,issue:null,severity:Z.Error,code:"string-value-must-not-have-spaces",entity:d});i.push(l)}if(a.includes("-")){const l=new Zt({id:d.id+"--string-value-must-not-have-dashes",message:`Entity of type ${d.type} with id "${d.id}" has an invalid value "${u}". The value cannot contain spaces or dashes.`,issue:null,severity:Z.Error,code:"string-value-must-not-have-dashes",entity:d});i.push(l)}return{errors:i,override:a.replace(/\s|-/g,"_")}}function OA(d,u){var i;if(d.type===f.LiteralValue){let a=(i=d.value)==null?void 0:i.toString();try{a=JSON.stringify(d.value,null,2)}catch{}return`${d.type}: ${d.id} (${ie(d,u)}) = ${a}`}if(d.type===f.DataType){if(d instanceof Yi||d.increaseVersion)return`${d.type}: ${d.id} (${Td(d)})`;try{const a=Td(d);return`${d.type}: ${d.id} (${a})`}catch{}}return`${d.type}: ${d.id} (${ie(d,u)})`}function Cd(d,u){const i=Qa(d);if(i.length===0)return{list:[],last:null};let a=null;return{list:i.flatMap(p=>{if(p===u)return a=p,[p];const t=Cd(p,u);return t.last&&(a=t.last),[p,...t.list]}),last:a}}function Pp(d){const u=d.calledBy;if(u.length===0)return d.project;const i=u.reduce((a,l)=>{const p=wi(l,d.project);return d.parent.id==="variable-instance-id"&&(console.log("caller: ",l.id+" - "+l.type+" - "+l.name),console.log("caller scope owner: ",(p==null?void 0:p.id)+" - "+(p==null?void 0:p.type)+" - "+p.name)),!p||p.type===f.Project?a:a.type===f.Project||Cd(p,a).last?p:(Cd(a,p).last,a)},d.project);return i.type===f.FunctionDeclaration&&i.parent.type===f.Loop?i.parent:i}function xe(d,u){let i=Pp(d);if(d.type===f.InternalCall)if(d.parent.type===f.VariableInstance){const l=Ns(i,d.parent.declaration,d.project);!l.compatible&&l.type!=="b-is-global-a-is-not"?d.parent.remove({ignoreUpstream:!1},u):(d.parent.setParent(i,u),d.parent.addSelfToProject(u))}else d.parent.setParent(i,u),d.parent.addSelfToProject(u);else if((d.type===f.ContinueStatement||d.type===f.BreakStatement)&&i.type!==f.Loop){d.remove({ignoreUpstream:!1},u);return}else if(d.type===f.ReturnStatement&&!wr.includes(i.type)){d.remove({ignoreUpstream:!1},u);return}else if(st.includes(d.type)){const l=d.usedInternalCalls[0];if(l)if(i=Pp(l),d.type===f.VariableInstance){const p=Ns(i,d.declaration,d.project);!p.compatible&&p.type!=="b-is-global-a-is-not"?d.remove({ignoreUpstream:!1},u):(d.setParent(i,u),d.addSelfToProject(u))}else d.setParent(i,u),d.addSelfToProject(u);else if(d.type===f.VariableInstance){const p=Ns(i,d.declaration,d.project);!p.compatible&&p.type!=="b-is-global-a-is-not"?d.remove({ignoreUpstream:!1},u):(d.setParent(i,u),d.addSelfToProject(u))}else d.setParent(i,u),d.addSelfToProject(u)}else d.setParent(i,u),d.addSelfToProject(u);if(nr.includes(d.type))return;pt(d).forEach(l=>{let p=Pp(l);if(l.type===f.InternalCall)if(l.parent.type===f.VariableInstance){const t=Ns(p,l.parent.declaration,d.project);!t.compatible&&t.type!=="b-is-global-a-is-not"?l.parent.remove({ignoreUpstream:!1},u):(l.parent.setParent(p,u),l.parent.addSelfToProject(u))}else l.parent.setParent(p,u),l.parent.addSelfToProject(u);else if((l.type===f.ContinueStatement||l.type===f.BreakStatement)&&p.type!==f.Loop){l.remove({ignoreUpstream:!1},u);return}else if(l.type===f.ReturnStatement&&!wr.includes(p.type)){l.remove({ignoreUpstream:!1},u);return}else if(st.includes(l.type)){const t=l.usedInternalCalls[0];if(t)if(p=Pp(t),l.type===f.VariableInstance){const y=Ns(p,l.declaration,d.project);!y.compatible&&y.type!=="b-is-global-a-is-not"?l.remove({ignoreUpstream:!1},u):(l.setParent(p,u),l.addSelfToProject(u))}else l.setParent(p,u),l.addSelfToProject(u);else if(l.type===f.VariableInstance){const y=Ns(p,l.declaration,d.project);!y.compatible&&y.type!=="b-is-global-a-is-not"?l.remove({ignoreUpstream:!1},u):(l.setParent(p,u),l.addSelfToProject(u))}else l.setParent(p,u),l.addSelfToProject(u)}else l.setParent(p,u),l.addSelfToProject(u)})}function Sy(d,u,i=new Set){const a=sn(d),l=sn(u),p=a.filter(v=>!l.includes(v)),t=a.filter(v=>l.includes(v)),y=p.reduce((v,T)=>i.has(T.id)?v:(i.add(T.id),R([...v,...Sy(T,u,i)])),[]);return R([...t,...y])}function il(d,u){const i=Cd(d,u);return i.last===u&&i.list.length>0&&i.list[0]!==u}function CA(d,u){return!!Cd(d,u).last}function D0e(d){if(Ht.includes(d.type))return d;if([...ws,f.VariableDeclaration].includes(d.type)){const u=d.parent;return Ht.includes(u.type)?u:null}return null}function $A(d,u){if(!d||!u)throw new Error("Both entities must be defined to find a common ancestor");if(d===u)return d;const i=d.parent;if(i){if(i===u)return u;if(i.type===f.Project)return null}else return null;const a=u.parent;if(a){if(a===d)return d;if(a.type===f.Project)return null}else return null;return $A(i,a)}function rr(d){if(Bf.includes(d.type)){if(d.type===f.FunctionDeclaration){const u=d.parent;if(u.type===f.DefinitionEntity)return rr(u);if(u.type===f.Loop)return u}return d.type===f.DefinitionEntity&&d.parent.type===f.DataType?rr(d.parent):d}else{const u=d.parent;return u?rr(u):null}}function qy(d,u){const i=Vp(d,u);if(!i)return null;if(Bf.includes(i.type)){if(i.type===f.FunctionDeclaration){const a=Vp(i.parent,u);if(a){if(a.type===f.DefinitionEntity)return a;if(a.type===f.Loop)return a}}return i}else{const a=i.parent?Vp(i.parent,u):null;return a?qy(a,u):null}}function NF(d){if(!d)return null;if(ws.includes(d.type))return d;const u=d.parent;return u?NF(u):null}function LF(d){if(!d)return null;if(er.includes(d.type))return d;const u=d.parent;return u?LF(u):null}function BF(d){if(!d)return null;if(Rs.includes(d.type))return d;const u=d.parent;return u?BF(u):null}function O0e(d){return d.type===f.VariableDeclaration?[d]:er.includes(d.type)?[...d.inputs,...d.outputs||[]]:nr.includes(d.type)?d.outputs:Pl.includes(d.type)||d.type===f.FunctionDeclaration?d.inputs:[]}function C0e(d){const u=sn(d),i=[],a=[];o1.includes(d.type)&&i.push(...Zy(d));const l=u.filter(p=>{const t=i.includes(p);return t?!1:ws.includes(p.type)&&!t?(a.push(p),!1):!0});return i.sort((p,t)=>il(t,p)?-1:0),a.sort((p,t)=>il(t,p)?-1:0),[...i,...a,...l]}function MF(d){return[...d].sort((u,i)=>il(i,u)?-1:0)}function $0e(d){const u=MF(d),i=[];return u.forEach(a=>{const l=i[i.length-1];if(l){const p=l[l.length-1];il(a,p)?i.push([a]):l.push(a)}else i.push([a])}),i}function ci(d){const u=d.map(i=>rr(i));return R(u)}function Zy(d){return er.includes(d.type)?[...ci(d.successCalls),...ci(d.errorCalls)]:Ht.includes(d.type)?ci(d.calls):[]}function P0e(d,u){return Zy(d).includes(u)}function PA(d){return d.writesValues||[]}function V0e(d,u){return PA(d).includes(u)}function UF(d){var u;return st.includes((u=d==null?void 0:d.readsValue)==null?void 0:u.type)?d.readsValue:null}function N0e(d){return d.writesValues}function jF(d=[]){return d.map(UF).filter(u=>!!u)}function Jy(d=[]){return d.map(u=>u.writesValues).flat().filter(u=>st.includes(u.type))}function xF(d=[]){return d.map(u=>u.readsValue).filter(u=>!!u&&st.includes(u.type))}function FF(d){return st.includes(d.type)?d:null}function GF(d){return d.writesValues.map(FF).filter(u=>!!u)}function KF(d=[]){return d.reduce((u,i)=>i.type===f.OutputMap?[...u,...GF(i)]:u,[])}function pt(d){return d.type===f.Loop?R([...Ps(ci(d.successCalls)),...Ps(ci(d.errorCalls)),...d.body?pt(d.body):[]]):er.includes(d.type)?R([...Ps(ci(d.successCalls)),...Ps(ci(d.errorCalls))]):Ht.includes(d.type)?R(Ps(ci(d.calls))):[]}function L0e(d){return er.includes(d.type)?[...Ps(ci(d.successCalls)),...Ps(ci(d.errorCalls))]:Ht.includes(d.type)?Ps(ci(d.calls)):[]}function kF(d,u=new Set){return d.writesValues.filter(a=>st.includes(a.type)&&!u.has(a.id)).reduce((a,l)=>u.has(l.id)?a:[...a,...Xt(l,u)],[])}function SF(d,u=new Set){var a;return(((a=d.readsValue)==null?void 0:a.writesValues)||[]).filter(l=>st.includes(l.type)&&!u.has(l.id)).reduce((l,p)=>u.has(p.id)?l:[...l,...Xt(p,u)],[])}function Xt(d,u=new Set){if(u.has(d.id))return[];if(d.type===f.ReturnStatement)return xF(d.outputs).reduce((a,l)=>[...a,...Xt(l,u)],[]);if(d.type===f.FunctionCall||d.type===f.Operation||d.type===f.Condition)return[...pt(d).reduce((p,t)=>{const y=rr(t);return[...p,...Xt(y||t,u)]},[]),...jF(d.inputs),...KF(d.outputs)].reduce((p,t)=>[...p,...Xt(t,u)],[]);if(Pl.includes(d.type)){const i=Jy(d.inputs),l=pt(d).reduce((p,t)=>{const y=rr(t);return[...p,...Xt(y||t,u)]},[]);return i.push(...l),i.reduce((p,t)=>[...p,...Xt(t,u)],[])}if(d.type===f.FunctionDeclaration){const i=[...Jy(d.inputs)],l=pt(d).reduce((p,t)=>{const y=rr(t);return[...p,...Xt(y||t,u)]},[]);return i.push(...l),i.reduce((p,t)=>[...p,...Xt(t)],[])}if(st.includes(d.type)){u.add(d.id);const a=pt(d).reduce((l,p)=>{const t=rr(p);return[...l,...Xt(t||p,u)]},[]);return[d,...a,...SF(d,u),...kF(d,u)]}return[]}function Xi(d,u=new Set){return u.has(d.id)?[]:(u.add(d.id),[...sn(d).reduce((l,p)=>[...l,p,...Xi(p,u)],[])])}function Ps(d){return d.reduce((u,i)=>i.type===f.ReturnStatement||i.type===f.ContinueStatement||i.type===f.BreakStatement?[...u,i]:[...u,i,...pt(i)],[])}function qF(d){const u=d.entities||[],i=[...u,...d.functions||[],...d.events||[],...d.projects||[]],a=u.reduce((v,T)=>[...v,...T.properties],[]),l=u.reduce((v,T)=>[...v,...T.methods],[]),p=l.reduce((v,T)=>[...v,...Jy(T.inputs),...Ps(ci(T.calls)),...T.returnStatements],[]),t=d.functions.reduce((v,T)=>[...v,...Ps(ci(T.calls)),...T.returnStatements],[]),y=d.events.reduce((v,T)=>[...v,...Ps(ci(T.calls)),...T.returnStatements],[]);return[...i,...a,...l,...p,...t,...y]}function ZF(d,u){return u.filter(a=>{if(!a)return!1;switch(a.type){case f.FunctionCall:return a.inputs.find(l=>l.id===d.id)!==void 0||a.outputs.find(l=>l.id===d.id)!==void 0;case f.Condition:return a.successCalls.find(l=>l.id===d.id)!==void 0||a.errorCalls.find(l=>l.id===d.id)!==void 0||a.inputs.find(l=>l.id===d.id)!==void 0;case f.Operation:return a.outputs.find(l=>l.id===d.id)!==void 0;case f.VariableDeclaration:return er.includes(d.type)?A6(d).find(p=>{var t;return((t=p.readsValue)==null?void 0:t.id)===a.id})!==void 0:!1;case f.DefinitionEntity:return a.properties.find(l=>l.id===d.id)!==void 0||a.methods.find(l=>l.id===d.id)!==void 0;case f.FunctionDeclaration:return a.inputs.find(l=>l.id===d.id)!==void 0||(a.returnStatements.map(l=>l.outputs).flat()||[]).find(l=>l.id===d.id)!==void 0;default:return!1}})}function B0e(d){const u=qF(d.project);return ZF(d,u)}function Vp(d,u){return d?typeof d=="string"?u[d]:d.type===f.GenericReference?u[d.entityId]:u[d.id]?u[d.id]:null:null}function JF(d={},u){const i={};return Object.keys(d).forEach(a=>{const l=u.get(a)||a,p=d[a];i[l]=p}),i}function $d(d,u={},i={}){const a={ignoreBuiltInBaseEntities:!1,allBuiltInEntityIds:[],entityMaps:new Map,...i};if(a.ignoreBuiltInBaseEntities&&(ki.includes(d.type)||(a.allBuiltInEntityIds||[]).includes(d.id)))return{upstream:{},downstream:{}};const l=d,p=d,t=d,y=d,v=d,T=d,w=d,A=d,V=d,N=d,j=d,k=d,S=d,W=[...S.readsValue?[S.readsValue]:[],...S.declaration?[S.declaration]:[],...(k.calledByEntry||[]).flatMap(se=>se),...(k.calledBySuccess||[]).flatMap(se=>se),...(k.calledByError||[]).flatMap(se=>se),...N.parent?[N.parent]:[]];Array.isArray(t.implements)?W.push(...t.implements.flatMap(se=>se)):V.implements&&W.push(V.implements),Array.isArray(t.extends)?W.push(...t.extends.flatMap(se=>se)):V.extends&&W.push(V.extends),v.valueAsTypeList&&Array.isArray(v.valueAsTypeList)&&W.push(...v.valueAsTypeList.flatMap(se=>se)),v.valueAsTypeSingle&&W.push(v.valueAsTypeSingle),(S.internalCalls||[]).forEach(se=>{const he=J(se);if(he&&u[he]){const X=u[he];[...X.calledByEntry||[],...X.calledBySuccess||[],...X.calledByError||[]].forEach(z=>{const ce=J(z);ce&&u[ce]&&W.push(u[ce])})}});const ne=[...(l.inputs||[]).flatMap(se=>se),...(j.inputsDeclarations||[]).flatMap(se=>se),...(l.outputs||[]).flatMap(se=>se),...(j.outputsDeclarations||[]).flatMap(se=>se),...(S.internalCalls||[]).flatMap(se=>se),...S.writesValues||[],...k.dataType?[k.dataType]:[],...T.body?[T.body]:[],...k.defaultValue?[k.defaultValue]:[],...(k.successCalls||[]).flatMap(se=>se),...(k.errorCalls||[]).flatMap(se=>se),...(t.properties||[]).flatMap(se=>se),...(t.methods||[]).flatMap(se=>se),...(t.abstractMethods||[]).flatMap(se=>se),...w.error?[w.error]:[],...w.process?[w.process]:[],...N.throws?[N.throws]:[],...(p.andChildrenGroup||[]).flatMap(se=>se),...(p.orChildrenGroup||[]).flatMap(se=>se),...(A.entities||[]).flatMap(se=>se),...(A.functions||[]).flatMap(se=>se),...(A.functionCalls||[]).flatMap(se=>se),...(A.events||[]).flatMap(se=>se),...(A.conditions||[]).flatMap(se=>se),...(A.operations||[]).flatMap(se=>se),...(A.loops||[]).flatMap(se=>se),...(A.variableDeclarations||[]).flatMap(se=>se),...(A.variableInstances||[]).flatMap(se=>se),...(A.searches||[]).flatMap(se=>se),...(A.projects||[]).flatMap(se=>se),...(y.calls||[]).flatMap(se=>se)];d.type===f.DataType&&(p.entity&&u[J(p.entity)]&&u[J(p.entity)].parent&&J(u[J(p.entity)].parent)===d.id?ne.push(p.entity):p.entity&&W.push(p.entity)),(S.internalCalls||[]).forEach(se=>{const he=J(se);if(he&&u[he]){const X=u[he];[...X.successCalls||[],...X.errorCalls||[]].forEach(z=>{const ce=J(z);ce&&u[ce]&&ne.push(u[ce])})}});const re={},pe={};return W.forEach(se=>{var z;const he=J(se);if(he&&a.ignoreBuiltInBaseEntities&&(ki.includes(se.type)||(a.allBuiltInEntityIds||[]).includes(he)))return;const X=se.version;if(he){const ce=((z=a.entityMaps)==null?void 0:z.get(he))||he;re[ce]=X}}),ne.forEach(se=>{var z;const he=J(se);if(he&&a.ignoreBuiltInBaseEntities&&(ki.includes(se.type)||(a.allBuiltInEntityIds||[]).includes(he)))return;const X=se.version;if(he){const ce=((z=a.entityMaps)==null?void 0:z.get(he))||he;pe[ce]=X}}),{upstream:re,downstream:pe}}function M0e(d,u){const i=[];if(ws.includes(d.type)){ys(d).forEach(p=>{const t=qy(p,u);t&&i.push(t)});const l=[...d.inputs||[],...d.outputs||[]].map(p=>{const t=Vp(p,u);return t?w6(t,u):null}).filter(p=>p!==null);i.push(...R(l))}if(st.includes(d.type)){const a=Wy(d);a&&i.push(a)}return R(i)}function Qa(d){const u=[];if(ws.includes(d.type)){d.calledBy.forEach(l=>{const p=rr(l);p&&u.push(p)});const a=[...d.inputs||[],...d.outputs||[]].map(l=>Wy(l)).filter(l=>l!==null);u.push(...R(a))}if(st.includes(d.type)){const i=Wy(d);i&&u.push(i)}return R(u)}function ys(d){return[...d.calledByEntry||[],...d.calledByError||[],...d.calledBySuccess||[]].filter(u=>u.type!==f.GenericReference)}function WF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ActionDescriptor)throw new Error("Entity must be an action descriptor to be flattened");return[d,...d.inputs.flatMap(a=>ye(a,u,i)),...d.outputs.flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function HF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ArgumentDeclaration)throw new Error("Entity must be an argument declaration to be flattened");return[d,...d.defaultValue?ye(d.defaultValue,u):[],...d.writesValues.flatMap(a=>ye(a,u,i)),...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function YF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.BreakStatement)throw new Error("Entity must be a break statement to be flattened");return[d,...d.outputs.flatMap(a=>ye(a,u,i)),...d.throws?ye(d.throws,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function zF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.BuiltInBaseEntity)throw new Error("Entity must be a built-in base entity to be flattened");return[d,...(d.properties||[]).flatMap(a=>ye(a,u,i)),...(d.methods||[]).flatMap(a=>ye(a,u,i)),...(d.abstractMethods||[]).flatMap(a=>ye(a,u,i)),...(d.extends||[]).flatMap(a=>ye(a,u,i))]}function XF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Condition)throw new Error("Entity must be a condition to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function QF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ContinueStatement)throw new Error("Entity must be a continue statement to be flattened");return[d,...d.outputs.flatMap(a=>ye(a,u,i)),...d.throws?ye(d.throws,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function e6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.DefinitionEntity)throw new Error("Entity must be a definition entity to be flattened");return[d,...(d.extends||[]).flatMap(a=>ye(a,u,i)),...(d.implements||[]).flatMap(a=>ye(a,u,i)),...(d.properties||[]).flatMap(a=>ye(a,u,i)),...(d.methods||[]).flatMap(a=>ye(a,u,i)),...(d.abstractMethods||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function t6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.DataType)throw new Error("Entity must be a data type to be flattened");return[d,...(d.andChildrenGroup||[]).flatMap(a=>ye(a,u,i)),...(d.orChildrenGroup||[]).flatMap(a=>ye(a,u,i)),...d.entity?ye(d.entity,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function r6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.FunctionCall)throw new Error("Entity must be a function call to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function i6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.FunctionDeclaration)throw new Error("Entity must be a function declaration to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.calls||[]).flatMap(a=>ye(a,u,i)),...d.implements?ye(d.implements,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function s6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.GlobalEvent)throw new Error("Entity must be a global event to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.calls||[]).flatMap(a=>ye(a,u,i)),...d.implements?ye(d.implements,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function n6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.InputMap)throw new Error("Entity must be an input map to be flattened");return[d,...d.readsValue?ye(d.readsValue,u,i):[],...d.declaration?ye(d.declaration,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function a6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.InstalledProject)throw new Error("Entity must be an installed project to be flattened");return[d,...(d.functions||[]).flatMap(a=>ye(a,u,i)),...(d.events||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function o6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.InternalCall)throw new Error("Entity must be an internal call to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function l6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.LiteralValue)throw new Error("Entity must be a literal value to be flattened");return[d,...d.valueAsTypeSingle?ye(d.valueAsTypeSingle,u,i):[],...d.valueAsTypeList&&Array.isArray(d.valueAsTypeList)?d.valueAsTypeList.flatMap(a=>ye(a,u,i)):[],...d.parent?ye(d.parent,u,i):[]]}function d6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Loop)throw new Error("Entity must be a loop to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...d.body?ye(d.body,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function u6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Operation)throw new Error("Entity must be an operation to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function c6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.OutputMap)throw new Error("Entity must be an output map to be flattened");return[d,...(d.writesValues||[]).flatMap(a=>ye(a,u,i)),...d.declaration?ye(d.declaration,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function p6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.PrimitiveEntity)throw new Error("Entity must be a primitive entity to be flattened");return[d,...(d.properties||[]).flatMap(a=>ye(a,u,i)),...(d.methods||[]).flatMap(a=>ye(a,u,i)),...(d.abstractMethods||[]).flatMap(a=>ye(a,u,i))]}function f6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Project)throw new Error("Entity must be a project to be flattened");return[d,...(d.entities||[]).flatMap(a=>ye(a,u,i)),...(d.functions||[]).flatMap(a=>ye(a,u,i)),...(d.events||[]).flatMap(a=>ye(a,u,i)),...(d.projects||[]).flatMap(a=>ye(a,u,i)),...(d.variableDeclarations||[]).flatMap(a=>ye(a,u,i)),...(d.variableInstances||[]).flatMap(a=>ye(a,u,i)),...(d.operations||[]).flatMap(a=>ye(a,u,i)),...(d.conditions||[]).flatMap(a=>ye(a,u,i)),...(d.functionCalls||[]).flatMap(a=>ye(a,u,i)),...(d.projects||[]).flatMap(a=>ye(a,u,i)),...(d.loops||[]).flatMap(a=>ye(a,u,i)),...(d.searches||[]).flatMap(a=>ye(a,u,i))]}function h6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Property)throw new Error("Entity must be a property to be flattened");return[d,...d.defaultValue?ye(d.defaultValue,u,i):[],...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function y6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ReturnDeclaration)throw new Error("Entity must be a return declaration to be flattened");return[d,...d.readsValue?ye(d.readsValue,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function m6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ReturnStatement)throw new Error("Entity must be a return statement to be flattened");return[d,...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.throws?ye(d.throws,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function v6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Search)throw new Error("Entity must be a search to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputsDeclarations||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputsDeclarations||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function E6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ValueDescriptor)throw new Error("Entity must be a value descriptor to be flattened");return[d,...d.defaultValue?ye(d.defaultValue,u,i):[],...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function T6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.VariableDeclaration)throw new Error("Entity must be a variable declaration to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(d.internalCalls||[]).flatMap(a=>ye(a,u,i)),...(d.writesValues||[]).flatMap(a=>ye(a,u,i)),...d.readsValue?ye(d.readsValue,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function b6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.VariableInstance)throw new Error("Entity must be a variable instance to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(d.internalCalls||[]).flatMap(a=>ye(a,u,i)),...(d.writesValues||[]).flatMap(a=>ye(a,u,i)),...d.readsValue?ye(d.readsValue,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.declaration?ye(d.declaration,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function Vs(){const d=new Set,u=QN.flatMap(i=>ye(i,d)).map(i=>i.id);if(!u.includes("http-request-error-return-delaration-id"))throw new Error("Built-in base entities must be included in the list");return u}function ye(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(!d)throw new Error("Entity must be defined to be flattened");if(d.type===f.GenericReference)return[];if(i.ignoreBuiltInBaseEntities&&(ki.includes(d.type)||Vs().includes(d.id)))return[];if(u.has(d.id))return[];switch(d.type){case f.FunctionCall:return r6(d,u,i);case f.Operation:return u6(d,u,i);case f.Condition:return XF(d,u,i);case f.Loop:return d6(d,u,i);case f.Search:return v6(d,u,i);case f.GlobalEvent:return s6(d,u,i);case f.ReturnStatement:return m6(d,u,i);case f.ContinueStatement:return QF(d,u,i);case f.BreakStatement:return YF(d,u,i);case f.VariableDeclaration:return T6(d,u,i);case f.DefinitionEntity:return e6(d,u,i);case f.FunctionDeclaration:return i6(d,u,i);case f.Project:return f6(d,u,i);case f.ActionDescriptor:return WF(d,u,i);case f.ArgumentDeclaration:return HF(d,u,i);case f.ReturnDeclaration:return y6(d,u,i);case f.ValueDescriptor:return E6(d,u,i);case f.InputMap:return n6(d,u,i);case f.OutputMap:return c6(d,u,i);case f.DataType:return t6(d,u,i);case f.InstalledProject:return a6(d,u,i);case f.InternalCall:return o6(d,u,i);case f.LiteralValue:return l6(d,u,i);case f.Property:return h6(d,u,i);case f.VariableInstance:return b6(d,u,i);case f.BuiltInBaseEntity:return i.ignoreBuiltInBaseEntities?[]:zF(d,u,i);case f.PrimitiveEntity:return i.ignoreBuiltInBaseEntities?[]:p6(d,u,i)}return[]}function VA(d){return d.type===f.FunctionCall||d.type===f.InternalCall||[f.Operation,f.Condition,f.Loop].includes(d.type)?d.declaration.inputs:d.type===f.FunctionDeclaration||Pl.includes(d.type)?d.inputs:d.type===f.Search?d.inputsDeclarations:[]}function U0e(d,u){return u.type===f.Condition?u.inputs.find(i=>i.declaration.id===d.id):u.type===f.FunctionCall||u.type===f.Operation?u.inputs.find(i=>i.declaration.id===d.id):null}function A6(d){return er.includes(d.type)?d.inputs:[]}function I6(d){var u;return d.type===f.FunctionCall?((u=d.declaration.returnStatements[0])==null?void 0:u.outputs)||[]:[f.Operation,f.Condition,f.Loop].includes(d.type)?d.declaration.outputs:d.type===f.Search?d.outputsDeclarations:nr.includes(d.type)?d.outputs:[]}function j0e(d,u){return u.type===f.Condition?null:u.type===f.FunctionCall||u.type===f.Operation?u.outputs.find(i=>i.declaration.id===d.id):null}function x0e(d){return d.type===f.Condition?[]:er.includes(d.type)?d.outputs:[]}function Wy(d){const u=d.readsValue;return u?rr(u):null}function w6(d,u){const i=d.readsValue;return i?qy(i,u):null}function R6(d){const u=d.internalCalls||[];return R(ci(R(u.flatMap(i=>[...i.successCalls,...i.errorCalls]))))}function Pd(d){const u=PA(d),i=[];return u.forEach(a=>{if(st.includes(a.type))i.push(a);else if(Wn.includes(a.type)){const l=a.parent;i.push(l)}}),i}function R(d){const u=new Set;return d.filter(i=>!i||u.has(i.id)?!1:(u.add(i.id),!0))}function sn(d,u=!1){const i=[];if(d.type===f.Project&&i.push(...(d==null?void 0:d.entities)||[],...(d==null?void 0:d.functions)||[],...(d==null?void 0:d.variableDeclarations)||[],...(d==null?void 0:d.variableInstances)||[],...(d==null?void 0:d.searches)||[],...(d==null?void 0:d.loops)||[],...(d==null?void 0:d.operations)||[],...(d==null?void 0:d.conditions)||[],...(d==null?void 0:d.functionCalls)||[],...(d==null?void 0:d.events)||[],...(d==null?void 0:d.projects)||[]),wr.includes(d.type)&&i.push(...(d==null?void 0:d.detachedChildren)||[]),d.type===f.DefinitionEntity){const a=[...d.suggestedMethods,...d.methods].flatMap(l=>l.collapsed&&u?[]:sn(l));i.push(...a)}if(d.type===f.Condition){const a=d.successCalls.map(p=>rr(p)),l=d.errorCalls.map(p=>rr(p));i.push(...a,...l)}if(Pl.includes(d.type)){if(d.collapsed&&u)return[];const a=d.inputs.map(p=>Pd(p)).flat(),l=d.calls.map(p=>rr(p));i.push(...R(a),...l)}if(er.includes(d.type)&&d.type!==f.Condition&&d.type!==f.Loop){const a=d==null?void 0:d.outputs.map(t=>Pd(t)).flat(),l=d.successCalls.map(t=>rr(t)),p=d.errorCalls.map(t=>rr(t));i.push(...R(a),...l,...p)}if(st.includes(d.type)){const a=Pd(d),l=R6(d);i.push(...a,...l)}if(d.type===f.Loop){const a=d.outputs.map(t=>Pd(t)).flat();if(d.body){const t=sn(d.body,u);i.push(...t)}const l=d.errorCalls.map(t=>rr(t)),p=d.successCalls.map(t=>rr(t));i.push(...R(a),...p,...l)}if(d.type===f.FunctionDeclaration){if(d.collapsed&&u)return[];const a=d.inputs.map(p=>Pd(p)).flat(),l=d.calls.map(p=>rr(p));i.push(...R(a),...l)}return R(i)}function Hy(d,u=!1){const i=sn(d,u),a=[...i,...i.reduce((l,p)=>[...l,...Hy(p,u)],[])];return R(a)}function g6(d){const u=Qa(d),i=[...u,...u.reduce((a,l)=>[...a,...g6(l)],[])];return R(i)}function Np(d){return d.implements.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,f.DefinitionEntity,...Np(i),...Lp(i)]:[...u,i.name],[])}function Lp(d){return d.extends.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,f.DefinitionEntity,...Lp(i),...Np(i)]:[...u,i.name],[])}function NA(d){return d.extends.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,i,...NA(i),...LA(i)]:[...u,i],[])}function LA(d){return d.implements.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,i,...LA(i),...NA(i)]:[...u,i],[])}function Vd(d){return[...Lp(d),...Np(d)].filter((i,a,l)=>l.indexOf(i)===a)}function BA(d){return d.implements.length===0&&d.extends.length===0?null:d.implements.find(a=>a.type===f.BuiltInBaseEntity&&a.name===Ce.PERSISTED_ENTITY)?d:[...d.implements,...d.extends].reduce((a,l)=>{if(l.type===f.DefinitionEntity){const p=BA(l);if(p)return p}return a},null)}function F0e(d){const u=d.extends.find(i=>i.type===f.BuiltInBaseEntity);return u&&u.type===f.BuiltInBaseEntity?u:null}function G0e(d){const u=d.implements.find(i=>i.type===f.BuiltInBaseEntity);return u&&u.type===f.BuiltInBaseEntity?u:null}function Yy(d){const u=d.extends.find(i=>i.type===f.DefinitionEntity);return u&&u.type===f.DefinitionEntity?u:null}function Ii(d){if(d.type===f.BuiltInBaseEntity)return[d];const u=[...d.implements,...d.extends].reduce((i,a)=>a.type===f.BuiltInBaseEntity?[...i,a]:a.type===f.DefinitionEntity?[...i,...Ii(a)]:i,[]);return R(u)}function Bp(d){return d.type===f.PrimitiveEntity?!0:d.type===f.BuiltInBaseEntity?d.interactive:!Ii(d).find(a=>!a.interactive)}function K0e(d){return d.parent===d.project&&d.project.variableDeclarations.includes(d)}function MA(d){return d.parent!==d.project?!1:f.VariableDeclaration===d.type?d.project.variableDeclarations.includes(d):f.VariableInstance===d.type?d.project.variableInstances.includes(d):f.FunctionCall===d.type?d.project.functionCalls.includes(d):f.Condition===d.type?d.project.conditions.includes(d):f.Operation===d.type?d.project.operations.includes(d):f.Loop===d.type?d.project.loops.includes(d):f.Search===d.type?d.project.searches.includes(d):!1}function _6(d){if([...Ht,f.DefinitionEntity,f.InstalledProject,f.Project].includes(d.type)||MA(d))return!1;const u=Qa(d);return u.length===0?!0:u.some(i=>_6(i))}function UA(d){return[...Ht,f.DefinitionEntity,f.InstalledProject,f.Project].includes(d.type)||MA(d)?!1:Qa(d).length===0}function D6(d,u=0){if(UA(d)){const i=Qa(d);return i.length===0?d:i.map(l=>D6(l,u+1)).reduce((l,p)=>l?p&&p.x<l.x?p:l:p,null)}return null}function O6(d){const u=[];if(UA(d))u.push(d);else return[];return Qa(d).forEach(a=>{u.push(...O6(a))}),u}function jA(d){return d.type===f.FunctionDeclaration&&d.parent!==d.project&&!![f.DefinitionEntity,f.Loop,f.InstalledProject].includes(d.parent.type)}function k0e(d,u){const i=new Map;return d.forEach(a=>{i.set(a.id,a)}),u.forEach(a=>{i.set(a.id,a)}),Array.from(i.values())}function Mp(d){switch(d){case f.DefinitionEntity:return va;case f.FunctionDeclaration:return Ma;case f.VariableDeclaration:return Ka;case f.VariableInstance:return Ga;case f.FunctionCall:return Xa;case f.Operation:return Ua;case f.Condition:return Fa;case f.ReturnStatement:return ja;case f.Loop:return bi;case f.Search:return ka;case f.InputMap:return $s;case f.OutputMap:return Xs;case f.ArgumentDeclaration:return fa;case f.ReturnDeclaration:return Ni;case f.Property:return ca;case f.InstalledProject:return Sa;case f.Project:return P;case f.DataType:return Yi;case f.GlobalEvent:return xa;case f.InternalCall:return qa;case f.ValueDescriptor:return Qs;case f.BuiltInBaseEntity:return $n;case f.PrimitiveEntity:return Li;case f.ActionDescriptor:return dt;case f.LiteralValue:return Ti;case f.ContinueStatement:return ui;case f.BreakStatement:return Za;default:return null}}function wi(d,u,i=null){const a=d!=null&&d.parent?J(d==null?void 0:d.parent):null;let l=a?u.get(a):null,p=i||d;if((d==null?void 0:d.id)===(u==null?void 0:u.id))return u;if(d.type===f.ReturnStatement)return Lr(d,u,p);if(d.type===f.FunctionDeclaration&&(l==null?void 0:l.type)===f.Loop)return l;if(Ht.includes(d.type))return d;if(d.type===f.Loop)return p.id===d.id?l:d;if(ki.includes(d.type))return null;const t=d.parent;if(!t)return null;if(t.type===f.GenericReference){const y=J(t);if(!y)return null;const v=u.get(y);return v?wi(v,u,p):null}else return t===u?u:wi(t,u,p)}function Lr(d,u,i=null){const a=d!=null&&d.parent?J(d==null?void 0:d.parent):null;let l=a?u.get(a):null,p=i||d;if(d.type===f.FunctionDeclaration&&(l==null?void 0:l.type)===f.Loop)return Lr(l.parent,u,p);if(Ht.includes(d.type))return d;if(ki.includes(d.type))return null;const t=d.parent;if(!t)return null;if(t.type===f.GenericReference){const y=J(t);if(!y)return null;const v=u.get(y);return v?Lr(v,u,p):null}else return t===u?u:Lr(t,u,p)}function Up(d,u){if(ki.includes(d.type)||u.getBuiltIn(d.id))return null;const i=Ri(d.parent,u);return i?i===u?wr.includes(d.type)?d:null:i.type===f.DefinitionEntity?d:Up(i,u):null}function zy(d,u,i){if(d===u||u===i||d===i||!d||!u)return!1;const a=wi(u.parent,i);return a===i?!1:a===d?!0:zy(a,u,i)}var Xy=(d=>(d.SameBothLocal="same-both-local",d.AInB="a-in-b",d.BInA="b-in-a",d.ParallelInCommonParent="parallel-in-common-parent",d.ParallelInProject="parallel-in-project",d.AIsGlobalBIsNot="a-is-global-b-is-not",d.BIsGlobalAIsNot="b-is-global-a-is-not",d.SameBothGlobal="same-both-global",d))(Xy||{});function Ns(d,u,i){const a=wi(d,i),l=wi(u,i);if(!a)throw new Error("Could not find scope owner for the entity: "+d.id);if(!l)throw new Error("Could not find scope owner for the entity: "+u.id);if(a===l&&a.type!==f.Project)return{compatible:!0,type:"same-both-local",commonAncestorScope:a};if(a===l&&a.type===f.Project)return{compatible:!0,type:"same-both-global",commonAncestorScope:a};if(a.type===f.Project&&l.type!==f.Project)return{compatible:!1,type:"a-is-global-b-is-not",commonAncestorScope:a};if(a.type!==f.Project&&l.type===f.Project)return{compatible:!1,type:"b-is-global-a-is-not",commonAncestorScope:l};if(zy(a,l,i))return{compatible:!0,type:"b-in-a",commonAncestorScope:a};if(zy(l,a,i))return{compatible:!0,type:"a-in-b",commonAncestorScope:l};const y=$A(a,l);return y===i?{compatible:!1,type:"parallel-in-project",commonAncestorScope:y}:y?{compatible:!1,type:"parallel-in-common-parent",commonAncestorScope:wi(y,i)}:{compatible:!1,type:"parallel-in-project",commonAncestorScope:i}}function C6(d,u,i){const a=Ns(d,u,i);if(!a.compatible||a.type!=="same-both-local")return null;if(d===u)return d;let l=wi(d.parent,i);if(l){if(l===u)return u;if(l.type===f.Project)return d}else return d;for(;l;){if(l){if(l===u)return u;if(l.type===f.Project)return d}else return d;l=wi(l.parent,i)}let p=wi(u.parent,i);if(p){if(p===d)return d;if(p.type===f.Project)return u}else return u;for(;p;){if(p){if(p===d)return d;if(p.type===f.Project)return u}else return u;p=wi(p.parent,i)}return null}function $6(d){return d.length===0?null:d.length===1?d[0]:d.reduce((i,a)=>{const l=C6(i,a,a.project);return!l||l===a?i:a},d[0])}function Ri(d,u){if(!d)return null;let i;return typeof d=="string"?i=d:d.type===f.GenericReference?i=J(d):i=d.id,i===u.id?u:u.get(i)}function eo(d){if(!d)return null;if(ki.includes(d.type))return d;if(d.type===f.Project)return null;if(d.project.getBuiltIn(d.id))return d;const u=d.parent;return!u||u.type===f.Project?null:eo(u)}function jp(d){const u=[];function i(p,t){return u.some(y=>y.blockedByCaller===p&&y.blockedByCalling===t)}function a(p,t){i(p,t)||u.push({blockedByCaller:p,blockedByCalling:t})}const l=Up(d,d.project);return d.calledBySuccess.forEach(p=>{[...p.successCalls||[]].forEach(v=>{nr.includes(v.type)&&v!==d&&(pt(d).find(A=>A===v)||a(p,v))});let y;if(er.includes(p.type)&&(y=p),y){const v=jp(y);v.reachable||pt(d).find(A=>A===p)||v.blocks.forEach(A=>{a(p,A.blockedByCalling)})}}),d.calledByError.forEach(p=>{[...p.errorCalls||[]].forEach(v=>{nr.includes(v.type)&&v!==d&&(pt(d).find(A=>A===v)||a(p,v))});let y;if(er.includes(p.type)&&(y=p),y){const v=jp(y);v.reachable||pt(d).find(A=>A===p)||v.blocks.forEach(A=>{a(p,A.blockedByCalling)})}}),d.calledByEntry.forEach(p=>{if([...p.calls||[]].forEach(v=>{nr.includes(v.type)&&v!==d&&(pt(d).find(A=>A===v)||a(p,v))}),p===l)return;let y;if(p.type===f.FunctionDeclaration){const v=rr(p);if(v.type===f.DefinitionEntity)return;v.type===f.Loop&&(y=v)}if(y){const v=jp(y);v.reachable||v.blocks.forEach(T=>{a(p,T.blockedByCalling)})}}),{reachable:u.length===0,entryPoint:l,blocks:u}}function S0e(d){return Bf.includes(d.type)?d.type===f.FunctionDeclaration?!jA(d):!0:!1}function q0e(d){if(f.ActionDescriptor===d.type){if(d.project.operationDeclarations.find(p=>p.id===d.id))return f.Operation;if(d.project.globalEventActionDescriptors.find(p=>p.id===d.id))return f.GlobalEvent;if(d.project.loopDeclarations.find(p=>p.id===d.id))return f.Loop;if(d.project.conditionDeclarations.find(p=>p.id===d.id))return f.Condition}return d.type}function Qy(d,u){return d.type===f.BuiltInBaseEntity?d.name===u:!!Lp(d).includes(u)}function Z0e(d,u){return d.type===f.BuiltInBaseEntity?d.name===u:!!Np(d).includes(u)}function Qi(d,u){return d.type===f.BuiltInBaseEntity?d.name===u:!!Vd(d).includes(u)}function J0e(d){const u=[];return d.entities.forEach(i=>{if(Qy(i,Ce.PERSISTED_ENTITY)){u.push(i);return}}),R(u)}function W0e(d){const u=[];return d.entities.forEach(i=>{if(Qy(i,Ce.RELATIONAL_DATABASE)){u.push(i);return}}),R(u)}function H0e(d){return d.type!==f.DefinitionEntity||d.abstract||!Qy(d,Ce.PERSISTED_ENTITY)?null:(d==null?void 0:d.properties.find(i=>{var a;return((a=i.implements)==null?void 0:a.id)===ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.primaryKey.id&&!i.abstract}))||null}function P6(d){var a;const u=BA(d);if(!u)return null;const i=u.properties.find(l=>{var p;return((p=l.implements)==null?void 0:p.id)===ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.database.id});return i?(a=i.getDefaultValue())==null?void 0:a.valueAsType:null}function Nd(d){if(d.type!==f.DefinitionEntity)return[];if(d.abstract)return[];if(!Qi(d,Ce.PERSISTED_ENTITY))return[];const u=[],i=d.properties.filter(a=>{var l;return((l=a.implements)==null?void 0:l.id)!==ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.database.id&&!a.abstract});return u.push(...i),u}function Y0e(d){var i;if(!d||d.type!==f.DefinitionEntity||!Qi(d,Ce.PERSISTED_ENTITY))return null;const u=d.properties.find(a=>{var l;return((l=a.implements)==null?void 0:l.id)===ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.database.id});return(i=u==null?void 0:u.getDefaultValue())==null?void 0:i.valueAsTypeSingle}function gr(d,u){var a;if(!u1.includes(u.type)||!d)return u.project||null;let i=u.project;return d.type===f.Project?i=d:((a=u.project)==null?void 0:a.id)!==d.project.id&&(i=d.project),i}function z0e(d){switch(d){case f.Project:return P;case f.InstalledProject:return Sa;case f.DefinitionEntity:return va;case f.FunctionDeclaration:return Ma;case f.GlobalEvent:return xa;case f.VariableInstance:return Ga;case f.VariableDeclaration:return Ka;case f.InputMap:return $s;case f.OutputMap:return Xs;case f.Condition:return Fa;case f.Operation:return Ua;case f.FunctionCall:return Xa;case f.ReturnDeclaration:return Ni;case f.ArgumentDeclaration:return fa;case f.PrimitiveEntity:return Li;case f.DataType:return Yi;case f.Property:return ca;case f.ActionDescriptor:return dt;case f.ReturnStatement:return ja;case f.ContinueStatement:return ui;case f.BreakStatement:return Za;case f.Loop:return bi;case f.Search:return ka;case f.ValueDescriptor:return Qs;case f.InternalCall:return qa;case f.LiteralValue:return Ti}return null}function X0e(d){const u={added:{},updated:{},removed:{},affected:[],seenEntities:[],self:d==null?void 0:d.self};return d==null||d.added.forEach(i=>{u.added[i.id]=i}),d==null||d.updated.forEach(i=>{u.updated[i.id]=i}),d==null||d.removed.forEach(i=>{u.removed[i.id]=i}),u.affected=Array.from(new Set(d==null?void 0:d.affected.map(i=>i.id))),u}function Ar(d,u){const i=Mp(d.type);return i?!i.MUTABLE_META_PROPERTIES.every(l=>{const p=d[l],t=u[l];return t===void 0||p===t?!0:Array.isArray(p)&&Array.isArray(t)?p.length!==t.length?!1:p.every((y,v)=>y===t[v]):!1}):!1}function em(d,u={}){if(d.type===f.Project)return[];if(!d.parent)return[];const i=J(d.parent);if(!i)return[];const a=u[i];return a?[a.id,...em(a,u)]:[]}function Q0e(d){const u=[],i=new Set;return[...d.listAdded,...d.listUpdated,...d.listAffected].forEach(a=>{const l=rr(a);!l||i.has(l.id)||(i.add(l.id),u.push(l))}),R(u)}function eve(d){if(d.type===f.Condition)return null;if(d.type===f.Search)return d.project.getBuiltIn(ve["value-descriptor"][Vl.SearchErrorOutputDescriptor].id)||null;if(d.type===f.Operation)return d.declaration.error;if(d.type===f.FunctionCall){const i=d.declaration.returnStatements.find(a=>!!a.throws);return(i==null?void 0:i.throws)||null}return null}function V6(d){const u=d.entities.filter(l=>!!l.implements.find(p=>p.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id)),i=u.find(l=>{const p=l.properties.find(v=>v.implements&&v.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),t=p==null?void 0:p.getDefaultValue();return(t==null?void 0:t.value)===!0});return i||u[0]||null}function xA(d,u){const i=Array.from(new Set([...u.getAllBuiltInIds(),...Vs()]));return!!(i.includes(d.id)||!em(d,{...u.instances,...u.builtInInstances}).every(p=>!i.includes(p)))}function N6(d){if(!d)return null;if(d.type===f.Project)return d.id;const u=d.parent;return u?N6(u):d.id}function xp(d){if(d.declaration&&d.declaration.type===f.Property){if(d.declaration.interactive){if(d.declaration.implements&&!d.declaration.implements.interactive)return!1;if(d.declaration.extends&&!d.declaration.extends.interactive)return!1}else return!1;if(d.declaration.private){const u=rr(d),i=Up(u,d.project);if((i==null?void 0:i.type)===f.FunctionDeclaration&&(i==null?void 0:i.parent.type)===f.DefinitionEntity&&(i==null?void 0:i.parent.id)!==d.declaration.parent.id)return!1}}return!0}function FA(d){if(d.interactive){if(d.implements&&!d.implements.interactive)return!1;if(d.extends&&!d.extends.interactive)return!1}else return!1;if(d.private){const u=rr(d),i=Up(u,d.project);if((i==null?void 0:i.type)===f.FunctionDeclaration&&(i==null?void 0:i.parent.type)===f.DefinitionEntity&&(i==null?void 0:i.parent.id)!==d.parent.id)return!1}return!0}function tve(d,u,i){const a=u,l=i,p=!!i,t=[];return a.forEach(y=>{var v;if(p){const T=Ns(l,y,d);if(!T.compatible&&T.type!=="b-is-global-a-is-not")return;t.push(y)}else{if(((v=y.parent)==null?void 0:v.type)!==f.Project)return;t.push(y)}}),R(t)}function L6(d){const u=cpe(),i=d.toJSON();u.safeParse(i).success;const l=d.implements.flatMap(w=>rve(d,w)),p=d.extends.flatMap(w=>ive(d,w)),t=nve(d),y=sve(d);d.methods.flatMap(w=>w.validate());const v=[...l,...p,...t,...y,...U6(d)];return Qt(d.errors,v)}function B6(d,u){const i=u.properties.filter(p=>p.abstract),a=[];let l=[...d.properties];return i.forEach(p=>{const t=l.find(y=>{var v;return((v=y.implements)==null?void 0:v.id)===p.id});t?l=l.filter(y=>y.id!==t.id):a.push(p)}),a}function M6(d,u){const i=u.abstractMethods,a=[];let l=[...d.methods];return i.forEach(p=>{const t=l.find(y=>{var v;return((v=y.implements)==null?void 0:v.id)===p.id});t?l=l.filter(y=>y.id!==t.id):a.push(p)}),a}function rve(d,u){const i=[];if(!u.abstract){const w=He({id:d.id+"--"+oe.ImplementingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is implementing a non-abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.ImplementingNonAbstractEntity,entity:d});return i.push(w.error),i}const a=u.properties.filter(w=>w.abstract),l=[];let p=[...d.properties];a.forEach(w=>{const A=p.find(V=>{var N;return((N=V.implements)==null?void 0:N.id)===w.id});A?p=p.filter(V=>V.id!==A.id):l.push(w)}),l.length&&l.forEach(w=>{const A=He({id:d.id+"--"+oe.MissingPropertyImplementation+"--"+w.id,message:`Property "${w.name}" with id "${w.id}" of entity "${u.name}" with id "${u.id}" is not implemented when entity "${d.name}" with id "${d.id}" implements it`,issue:null,severity:Z.Error,code:oe.MissingPropertyImplementation,entity:d});i.push(A.error)});const t=[];let y=[...d.methods];u.abstractMethods.forEach(w=>{const A=y.find(V=>{var N;return((N=V.implements)==null?void 0:N.id)===w.id});A?y=y.filter(V=>V.id!==A.id):t.push(w)}),t.length&&t.forEach(w=>{const A=He({id:d.id+"--"+oe.MissingMethodImplementation+"--"+w.id,message:`Method "${w.name}" with id "${w.id}" of entity "${u.name}" with id "${u.id}" is not implemented when entity "${d.name}" with id "${d.id}" implements it`,issue:null,severity:Z.Error,code:oe.MissingMethodImplementation,entity:d});i.push(A.error)});const v=[];u.properties.forEach(w=>{const A=p.find(V=>V.name===w.name);A&&v.push([A,w])}),v.length&&v.forEach(([w])=>{const A=He({id:d.id+"--"+ae.PropertyOverwritesOtherSiblingWithSameName+"--"+w.id,message:`Property "${w.name}" with id "${w.id}" of entity "${d.name}" with id "${d.id}" overwrites the property with the same name from the base entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.PropertyOverwritesOtherSiblingWithSameName,entity:d});i.push(A.error)});const T=[];return u.methods.forEach(w=>{const A=y.find(V=>V.name===w.name);A&&T.push([A,w])}),T.length&&T.forEach(([w])=>{const A=He({id:d.id+"--"+ae.MethodOverwritesOtherSiblingWithSameName+"--"+w.id,message:`Method "${w.name}" with id "${w.id}" of entity "${d.name}" with id "${d.id}" overwrites the method with the same name from the base entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.MethodOverwritesOtherSiblingWithSameName,entity:d});i.push(A.error)}),i}function ive(d,u){const i=[],a=[];if(!d.abstract&&u.abstract){const p=He({id:d.id+"--"+u.id+"--"+oe.NonAbstractExtendingAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is not-abstract but is extending an abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonAbstractExtendingAbstractEntity,entity:d,firstRelationship:u});return i.push(p.error),i}if(d.abstract&&!u.abstract){const p=He({id:d.id+"--"+u.id+"--"+oe.AbstractExtendingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is abstract but is extending an non-abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.AbstractExtendingNonAbstractEntity,entity:d,firstRelationship:u});return i.push(p.error),i}d.properties.forEach(p=>{var y;const t=u.properties.find(v=>{var T;return v.name===p.name&&((T=p.extends)==null?void 0:T.id)!==v.id});((y=p.implements)==null?void 0:y.id)!==(t==null?void 0:t.id)&&t&&a.push(p)}),a.length&&a.forEach(p=>{const t=He({id:d.id+"--"+ae.PropertyOverwritesOtherSiblingWithSameName,message:`Property "${p.name}" with id "${p.id}" of entity "${d.name}" with id "${d.id}" overwrites the property with the same name from the extended entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.PropertyOverwritesOtherSiblingWithSameName,entity:d});i.push(t.error)});const l=[];return d.methods.forEach(p=>{var y;const t=u.methods.find(v=>{var T;return v.name===p.name&&((T=p.extends)==null?void 0:T.id)!==v.id});((y=p.implements)==null?void 0:y.id)!==(t==null?void 0:t.id)&&t&&l.push(p)}),l.length&&l.forEach(p=>{const t=He({id:d.id+"--"+ae.MethodOverwritesOtherSiblingWithSameName,message:`Method "${p.name}" with id "${p.id}" of entity "${d.name}" with id "${d.id}" overwrites the method with the same name from the extended entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.MethodOverwritesOtherSiblingWithSameName,entity:d});i.push(t.error)}),i}function sve(d){const u=[];if(!d.properties.length){const i=He({id:d.id+"--"+oe.NoProperties,message:"No properties implemented",issue:null,severity:Z.Warning,code:oe.NoProperties,entity:d});u.push(i.error)}return d.properties.forEach(i=>{i.validate()}),u}function nve(d){const u=[];if(d.abstract){if(d.methods.length){const i=He({id:d.id+"--"+oe.AbstractEntityWithNonAbstractMethods,message:`Entity "${d.name}" with id "${d.id}" is marked as abstract but has non-abstract methods`,issue:null,severity:Z.Error,code:oe.AbstractEntityWithNonAbstractMethods,entity:d});u.push(i.error)}if(d.properties.some(i=>!i.abstract)){const i=He({id:d.id+"--"+oe.AbstractEntityWithNonAbstractProperties,message:`Entity "${d.name}" with id "${d.id}" is marked as abstract but has non-abstract properties`,issue:null,severity:Z.Error,code:oe.AbstractEntityWithNonAbstractProperties,entity:d});u.push(i.error),d.properties.forEach(a=>{if(!a.abstract){const l=He({id:d.id+"--"+oe.StaticEntityWithNonStaticProperties+"--"+a.id,message:`Property "${a.name}" with id "${a.id}" of entity "${d.name}" with id "${d.id}" is not marked as abstract but the entity is marked as abstract`,issue:null,severity:Z.Error,code:oe.StaticEntityWithNonStaticProperties,entity:d});u.push(l.error)}})}}else{if(d.abstractMethods.length){const i=He({id:d.id+"--"+oe.AbstractPropertyInNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is not marked as abstract but has abstract methods`,issue:null,severity:Z.Error,code:oe.AbstractPropertyInNonAbstractEntity,entity:d});u.push(i.error)}d.properties.some(i=>i.abstract)&&d.properties.forEach(i=>{if(i.abstract){const a=He({id:d.id+"--"+oe.AbstractPropertyInNonAbstractEntity+"--"+i.id,message:`Property "${i.name}" with id "${i.id}" of entity "${d.name}" with id "${d.id}" is marked as abstract but the entity is not marked as abstract`,issue:null,severity:Z.Error,code:oe.AbstractPropertyInNonAbstractEntity,entity:d,firstRelationship:i});u.push(a.error)}})}return d.static&&d.properties.some(i=>!i.static)&&d.properties.forEach(i=>{if(!i.static){const a=He({id:d.id+"--"+oe.NonStaticPropertyInStaticEntity+"--"+i.id,message:`Property "${i.name}" with id "${i.id}" of entity "${d.name}" with id "${d.id}" is not marked as static but the entity is marked as static`,issue:null,severity:Z.Error,code:oe.NonStaticPropertyInStaticEntity,entity:d,firstRelationship:i});u.push(a.error)}}),u}function ave(d,u){const i=[],a=Ii(u);if(!u.abstract){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.ImplementingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is implementing a non-abstract built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.ImplementingNonAbstractEntity,entity:d,firstRelationship:u});i.push(t)}const l=d.implements.filter(t=>t.id!==u.id);if(d.abstract){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.AbstractEntityImplements,message:`Entity "${d.name}" with id "${d.id}" is marked as abstract and cannot implement built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.AbstractEntityImplements,entity:d,firstRelationship:u});i.push(t)}if(d.static&&!u.static){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.StaticImplementingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is marked as static and cannot implement non-static built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.StaticImplementingNonStaticEntity,entity:d,firstRelationship:u});i.push(t)}if(!d.static&&u.static){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.NonStaticImplementingStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is not marked as static and cannot implement static built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonStaticImplementingStaticEntity,entity:d,firstRelationship:u});i.push(t)}return l.length&&l.forEach(t=>{if(t.type===f.BuiltInBaseEntity){const y=a.filter(v=>v.id!==t.id);y.length&&y.forEach(v=>{if(v.id!==t.id){const T=new Zt({id:d.id+"--"+v.id+"--"+t.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${v.name}" with id "${v.id}" but also implements entity "${t.name}" with id "${t.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:v,secondRelationship:t});i.push(T)}})}else{Ii(t).forEach(w=>{const A=a.filter(V=>V.id!==w.id);A.length&&A.forEach(V=>{if(V.id!==w.id){const N=new Zt({id:d.id+"--"+V.id+"--"+w.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${V.name}" with id "${V.id}" but also implements entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:V,secondRelationship:w});i.push(N)}})});const v=ma(u.ownDeclaredProperties,t.ownDeclaredProperties,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameImplementation,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameName);i.push(...v.errors);const T=ma(u.abstractMethods,[...t.abstractMethods,...t.methods],ae.MethodOverwritesOtherImplementedEntitysMethodWithSameImplementation,ae.MethodOverwritesOtherImplementedEntitysMethodWithSameName);i.push(...T.errors)}}),R(d.extends.flatMap(t=>Ii(t))).forEach(t=>{if(!a.find(y=>y.id===t.id)){const y=new Zt({id:d.id+"--"+u.id+"--"+t.id+"--"+oe.ExtendsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${u.name}" with id "${u.id}" but also extends entity "${t.name}" with id "${t.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ExtendsIncompatibleEntities,entity:d,firstRelationship:u,secondRelationship:t});i.push(y)}}),i}function ove(d,u,i=!1){const a=[],l=Ii(u);if(!d.abstract&&u.abstract){const w=He({id:d.id+"--"+u.id+"--"+oe.NonAbstractExtendingAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is not-abstract but is extending an abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonAbstractExtendingAbstractEntity,entity:d,firstRelationship:u});a.push(w.error)}if(d.abstract&&!u.abstract){const w=He({id:d.id+"--"+u.id+"--"+oe.AbstractExtendingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is abstract but is extending an non-abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.AbstractExtendingNonAbstractEntity,entity:d,firstRelationship:u});a.push(w.error)}if(!d.static&&u.static){const w=He({id:d.id+"--"+u.id+"--"+oe.NonStaticExtendingStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is not static but is extending a static entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonStaticExtendingStaticEntity,entity:d,firstRelationship:u});a.push(w.error)}if(d.static&&!u.static){const w=He({id:d.id+"--"+u.id+"--"+oe.StaticExtendingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is static but is extending an non-static entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.StaticExtendingNonStaticEntity,entity:d,firstRelationship:u});a.push(w.error)}if(!Bp(u)){const w=He({id:d.id+"--"+u.id+"--"+oe.ExtendingNonInteractiveEntity,message:`Entity "${d.name}" with id "${d.id}" is extending an non-interactive entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.ExtendingNonInteractiveEntity,entity:d,firstRelationship:u});a.push(w.error)}const t=d.extends.filter(w=>w.id!==u.id);t.length&&t.forEach(w=>{if(w.type===f.BuiltInBaseEntity){const A=l.filter(V=>V.id!==w.id);A.length&&A.forEach(V=>{if(V.id!==w.id){const N=He({id:d.id+"--"+V.id+"--"+w.id+"--"+oe.ExtendsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is extending built-in entity "${V.name}" with id "${V.id}" but also extends entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ExtendsIncompatibleEntities,entity:d,firstRelationship:V,secondRelationship:w});a.push(N.error)}})}else{Ii(w).forEach(W=>{const ne=l.filter(re=>re.id!==W.id);ne.length&&ne.forEach(re=>{if(re.id!==W.id){const pe=new Zt({id:d.id+"--"+re.id+"--"+W.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is extending built-in entity "${re.name}" with id "${re.id}" but also extends or implements entity "${W.name}" with id "${W.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:re,secondRelationship:W});a.push(pe)}})});const V=!!Ii(w).find(W=>W.id===u.id);let N=[...w.properties];V&&(N=N.filter(W=>!u.properties.find(ne=>{var re;return ne.id===W.id||ne.name===W.name||ne.id===((re=W.implements)==null?void 0:re.id)})));let j=[...w.methods];V&&(j=j.filter(W=>!u.methods.find(ne=>{var re;return ne.id===W.id||ne.name===W.name||ne.id===((re=W.implements)==null?void 0:re.id)})));const k=ma(u.ownDeclaredProperties,N,ae.PropertyOverwritesOtherExtendedEntitysPropertyWithSameImplementation,ae.PropertyOverwritesOtherExtendedEntitysPropertyWithSameName);a.push(...k.errors);const S=ma(u.abstractMethods,j,ae.MethodOverwritesOtherExtendedEntitysMethodWithSameImplementation,ae.MethodOverwritesOtherExtendedEntitysMethodWithSameName);a.push(...S.errors)}}),i&&console.log("self.implements.length",d.implements.length),d.implements.length&&d.implements.forEach(w=>{if(w.type===f.BuiltInBaseEntity){const A=l.filter(V=>V.id!==w.id);A.length&&A.forEach(V=>{if(V.id!==w.id){const N=new Zt({id:d.id+"--"+V.id+"--"+w.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${V.name}" with id "${V.id}" but also implements entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:V,secondRelationship:w});a.push(N)}})}else{Ii(w).forEach(j=>{const k=l.filter(S=>S.id!==j.id);k.length&&k.forEach(S=>{if(S.id!==j.id){const W=new Zt({id:d.id+"--"+S.id+"--"+j.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${S.name}" with id "${S.id}" but also implements entity "${j.name}" with id "${j.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:S,secondRelationship:j});a.push(W)}})});const V=ma(u.ownDeclaredProperties,w.ownDeclaredProperties,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameImplementation,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameName);a.push(...V.errors);const N=ma(u.abstractMethods,[...w.abstractMethods,...w.methods],ae.MethodOverwritesOtherImplementedEntitysMethodWithSameImplementation,ae.MethodOverwritesOtherImplementedEntitysMethodWithSameName);a.push(...N.errors)}});const y=ma(d.ownDeclaredProperties,u.ownDeclaredProperties,ae.PropertyOverwritesOtherSiblingWithSameImplementation,ae.PropertyOverwritesOtherSiblingWithSameName);a.push(...y.errors);const v=ma(u.methods,u.abstractMethods,ae.MethodOverwritesOtherSiblingWithSameImplementation,ae.MethodOverwritesOtherSiblingWithSameName);return a.push(...v.errors),R(d.extends.flatMap(w=>Ii(w))).forEach(w=>{if(!l.find(A=>A.id===w.id)){const A=new Zt({id:d.id+"--"+u.id+"--"+w.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is extending built-in entity "${u.name}" with id "${u.id}" but also extends entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:u,secondRelationship:w});a.push(A)}}),a}function lve(d){const u=[];return d.implements.forEach(i=>{if(!i.static){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.StaticImplementingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is static but implements entity "${i.name}" with id "${i.id}" which is non-static`,issue:null,severity:Z.Error,code:oe.StaticImplementingNonStaticEntity,entity:d,firstRelationship:i});u.push(a)}}),d.extends.forEach(i=>{if(!i.static){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.StaticExtendingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is static but extends entity "${i.name}" with id "${i.id}" which is non-static`,issue:null,severity:Z.Error,code:oe.StaticExtendingNonStaticEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function dve(d){const u=[];if(d.implements.length){const i=new Zt({id:d.id+"--"+oe.AbstractEntityImplements,message:`Entity "${d.name}" with id "${d.id}" cannot be marked as abstract because it implements other entities`,issue:null,severity:Z.Error,code:oe.AbstractEntityImplements,entity:d});u.push(i)}return d.extends.forEach(i=>{if(!i.abstract){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.AbstractExtendingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is abstract but extends entity "${i.name}" with id "${i.id}" which is non-abstract`,issue:null,severity:Z.Error,code:oe.AbstractExtendingNonAbstractEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function uve(d){const u=[];return d.extends.forEach(i=>{if(i.static){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.NonStaticExtendingStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is non-static but extends entity "${i.name}" with id "${i.id}" which is static`,issue:null,severity:Z.Error,code:oe.NonStaticExtendingStaticEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function cve(d){const u=[];return d.extends.forEach(i=>{if(i.abstract){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.NonAbstractExtendingAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is non-abstract but extends entity "${i.name}" with id "${i.id}" which is abstract`,issue:null,severity:Z.Error,code:oe.NonAbstractExtendingAbstractEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function U6(d){const u=[],i=d.name;if(!i){const V=He({id:`${d.id}--${ae.EmptyName}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" does not have a name. Entities of type ${d.type} must have valid names.`,issue:null,severity:Z.Error,code:ae.EmptyName,entity:d});return u.push(V.error),u}const l=[...d.project.functions,...d.project.entities.flatMap(V=>V.methods)].filter(V=>V.id!==d.id),p=i.trim(),t=!l.some(V=>V.name===i||V.name===p);if(!t){const V=He({id:`${d.id}--${ae.NameNotUniqueInScope}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" does not have a unique name. Entities of type ${d.type} must have valid names among all other entities of its type.`,issue:null,severity:Z.Error,code:ae.NameNotUniqueInScope,entity:d});u.push(V.error)}const y=Tr(i);if(!!l.some(V=>Tr(V.name)===y)&&t){const V=He({id:`${d.id}--${ae.NameAsResolvedCodeNameNotUniqueInScope}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" does not have a unique name once it is resolved as it will appear in code: "${y}". Entities of type ${d.type} must have valid names including their code name form.`,issue:null,severity:Z.Error,code:ae.NameAsResolvedCodeNameNotUniqueInScope,entity:d});u.push(V.error)}if(!/^[a-zA-Z_]/.test(i)){const V=He({id:`${d.id}--${ae.NameMustStartWithLetterOrUnderscore}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" has a name that does not start with a letter or underscore.`,issue:null,severity:Z.Error,code:ae.NameMustStartWithLetterOrUnderscore,entity:d});u.push(V.error)}const w=i.substring(1);if(!/^[a-zA-Z0-9_ ]*$/.test(w)){const V=He({id:`${d.id}--${ae.NameCanOnlyContainLettersNumbersUnderscoreAndSpaces}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" has a name that contains invalid characters. It can only contain letters, numbers, underscores and spaces.`,issue:null,severity:Z.Error,code:ae.NameCanOnlyContainLettersNumbersUnderscoreAndSpaces,entity:d});u.push(V.error)}return u}const pve=Object.freeze(Object.defineProperty({__proto__:null,getBaseMethodsNotImplemented:M6,getBasePropertiesNotImplemented:B6,validate:L6,validateCanBecomeAbstract:dve,validateCanBecomeNonAbstract:cve,validateCanBecomeNonStatic:uve,validateCanBecomeStatic:lve,validateCanExtendEntity:ove,validateCanImplementEntity:ave,validateDefinitionEntityName:U6},Symbol.toStringTag,{value:"Module"}));function fve(d,u){const i=[];if(d.parent)if(d.id===d.parent)i.push(new ee({id:`${d.id}--${d.parent}--${q.SelfReference}`,code:q.SelfReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has a reference to itself at 'parent'. This is not allowed. Change the reference string or the 'entityId' property of the reference object.`,issue:null}));else{const a=u.get(d.parent);a?[f.Project,f.DataType].includes(a.type)||i.push(new ee({id:`${d.id}--${d.parent}--${q.InvalidParentReference}`,code:q.InvalidParentReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has a parent reference that isn't pointing to an entity of type 'project' or 'data-type'.`,issue:null})):i.push(new ee({id:`${d.id}--${d.parent}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", is referencing an entity with id "${d.parent}" that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,issue:null}))}return d.implements&&Array.isArray(d.implements)?d.implements.forEach(a=>{if(d.id===a){i.push(new ee({id:`${d.id}--${a}--${q.SelfReference}`,code:q.SelfReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has a reference to itself at one of the 'implements' references. This is not allowed. Change the reference string or the 'entityId' property of the reference object.`,issue:null}));return}const l=u.get(a);l?[f.DefinitionEntity,f.BuiltInBaseEntity].includes(l.type)?l.abstract||i.push(new ee({id:`${d.id}--${a}--${q.InvalidImplementsReference}`,code:q.InvalidImplementsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'implements' reference that isn't pointing to an abstract entity.`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.InvalidImplementsReference}`,code:q.InvalidImplementsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'implements' reference that isn't pointing to an entity of type 'definition-entity' or 'built-in-base-entity'.`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", is referencing an entity with id "${a}" that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,issue:null}))}):i.push(new ee({id:`${d.id}--${ae.InvalidObjectStructure}`,code:ae.InvalidObjectStructure,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'implements' property that isn't an array.`,issue:null})),d.extends&&Array.isArray(d.extends)&&d.extends.forEach(a=>{const l=u.get(a);l?[f.DefinitionEntity,f.BuiltInBaseEntity].includes(l.type)?l.abstract&&i.push(new ee({id:`${d.id}--${a}--${q.InvalidExtendsReference}`,code:q.InvalidExtendsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'extends' reference that isn't pointing to a non-abstract entity. Did you want to use the property 'implements', which holds a list of references to absract entities, instead?`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.InvalidExtendsReference}`,code:q.InvalidExtendsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'extends' reference that isn't pointing to an entity of type 'definition-entity' or 'built-in-base-entity'.`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", is referencing an entity with id "${a}" that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,issue:null}))}),i}var tm=(d=>(d.Extends="extends",d.Implements="implements",d))(tm||{});const Vt=class Vt extends mr{constructor(i,a){super(i);D(this,"initialData");D(this,"id");D(this,"name");D(this,"codeName",null);D(this,"description",null);D(this,"x");D(this,"y");D(this,"static");D(this,"abstract");D(this,"type",f.DefinitionEntity);D(this,"properties",[]);D(this,"methods",[]);D(this,"abstractMethods",[]);D(this,"extends",[]);D(this,"implements",[]);D(this,"project");D(this,"errors",[]);D(this,"parent");D(this,"detachedDependents",{});D(this,"knownVersions",null);D(this,"activeVersion",!1);D(this,"initialized",!1);D(this,"startedInitialization",!1);D(this,"suggestedProperties",[]);D(this,"suggestedMethods",[]);this.initialData=i,this.project=a,this.id=i.id,this.name=i.name,this.description=i.description,this.x=i.x,this.y=i.y,this.codeName=i.codeName,this.static=i.static,this.abstract=i.abstract}static new(i=null){return{id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:(i==null?void 0:i.author)||P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DefinitionEntity,name:"",codeName:null,description:"",static:!1,abstract:!1,properties:[],methods:[],abstractMethods:[],extends:[],implements:[],x:0,y:0,parent:null}}static fromGenerationTarget(i,a){let l=a;if(i.parent){const T=J(i.parent);l=a.get(T)}const p=[];i.implements&&i.implements.forEach(T=>{p.push(a.get(T)||a.getBuiltIn(T))});const t=[];i.extends&&i.extends.forEach(T=>{t.push(a.get(T)||a.getBuiltIn(T))});const y={id:i.id,version:P.UUID.uuid(),createdAt:L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:i.name,type:f.DefinitionEntity,codeName:i.codeName||null,description:i.description,static:i.static,abstract:i.abstract,properties:[],methods:[],abstractMethods:[],extends:t,implements:p,x:0,y:0,parent:l},v=te(y,a);return v.setParent(l,null),v}static validateGenerationTarget(i,a){let l=JSON.parse(JSON.stringify(i));const p=[],t=fve(l,a),y=ub(l,a);p.push(...t,...y,...br(l));const v=l.parent?a.get(l.parent):null;if(v&&v.type===f.DataType){const T=v;T.entity&&p.push(new ee({id:`${i.id}--${q.NewEntityWouldOverriteExisting}`,code:q.NewEntityWouldOverriteExisting,severity:Z.Error,message:`The entity of type '${i.type}' with id '${i.id}' can't be added to the 'parent' entity with id '${T.id}' because it already has an 'entity' child. Data type entities can only have one 'entity' as children.
|
|
400
|
+
You shouldn't have to manually update a 'parent' property. The equivalent result is to change its callers, the value writters of its inputs, or the value readers of its outputs.`,issue:null})),{errors:a,modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];if(a==="declaration"){const{updated:T,added:w,removed:A}=this.remove({ignoreUpstream:!1},l);p.push(...T),t.push(...w),y.push(...A)}if(a==="parent"){const{updated:T,added:w,removed:A}=this.remove({ignoreUpstream:!1},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];if(a==="declaration"){const{updated:T,added:w,removed:A}=this.restore({},l);p.push(...T),t.push(...w),y.push(...A)}if(a==="parent"){const{updated:T,added:w,removed:A}=this.restore({},l);p.push(...T),t.push(...w),y.push(...A)}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){var i;return(i=this.parent)==null||i.unsubscribeDependents([{entity:this,field:"parent"}]),this.declaration.unsubscribeDependents([{entity:this,field:"declaration"}]),this}subscribeToDependencies(){var i;return(i=this.parent)==null||i.subscribeDependents([{entity:this,field:"parent"}]),this.declaration.subscribeDependents([{entity:this,field:"declaration"}]),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new xt(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.inputs=[...this.inputs],i.outputs=[...this.outputs],i.error=this.error,i.successCalls=[...this.successCalls],i.errorCalls=[...this.errorCalls],i.process=this.process,i.declaration=this.declaration,i.calledBySuccess=[...this.calledBySuccess],i.calledByError=[...this.calledByError],i.calledByEntry=[...this.calledByEntry],i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new xt(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.inputs=y.inputs,this.outputs=y.outputs,this.error=y.error,this.successCalls=y.successCalls,this.errorCalls=y.errorCalls,this.process=y.process,this.declaration=y.declaration,this.calledBySuccess=y.calledBySuccess,this.calledByError=y.calledByError,this.calledByEntry=y.calledByEntry,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&this.removeFromParent(a),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.declaration){const l=J(i.declaration),p=this.project.get(l);p&&this.setDeclaration(p)}return i.calledByEntry.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addEntryCaller(t,a),t.addCall(this,a))}),[...this.calledByEntry].forEach(l=>{i.calledByEntry.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledBySuccess.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addSuccessCaller(t,a),t.addSuccessCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),i.calledByError.forEach(l=>{const p=J(l),t=this.project.get(p);t&&(this.addErrorCaller(t,a),t.addErrorCall(this,a))}),[...this.calledBySuccess].forEach(l=>{i.calledBySuccess.find(t=>J(t)===l.id)||(this.removeCaller(l,a),l.removeCall(this,a))}),this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(this.initialData.declaration){const t=J(this.initialData.declaration),y=this.project.get(t);y&&(this.setDeclaration(y),i.push(y))}return this.initialData.calledByEntry.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addEntryCaller(v,null)}),this.initialData.calledBySuccess.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addSuccessCaller(v,null)}),this.initialData.calledByError.forEach(t=>{const y=J(t),v=this.project.get(y);v&&this.addErrorCaller(v,null)}),{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];this.initialized=!0;const{updated:y,added:v,removed:T}=this.syncInputs(i),{updated:w,added:A,removed:V}=this.syncOutputs(i);return a.push(...y,...w),l.push(...v,...A),p.push(...T,...V),this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){var y;const a=[this],l=[],p=[],t=[];return this.parent===this.project&&this.project.addFunctionCall(this),(y=this.process)==null||y.writesValues.forEach(v=>{v.setValueWriter(this.process,i),a.push(v)}),this.successCalls.forEach(v=>{v.addSuccessCaller(this,i),a.push(v)}),this.errorCalls.forEach(v=>{v.addErrorCaller(this,i),a.push(v)}),this.calledBySuccess.forEach(v=>{v.addSuccessCall(this,i),a.push(v)}),this.calledByError.forEach(v=>{v.addErrorCall(this,i),a.push(v)}),this.calledByEntry.forEach(v=>{v.addCall(this,i),a.push(v)}),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}get calledBy(){return[...this.calledByEntry,...this.calledBySuccess,...this.calledByError]}removeInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-input"))){const l=this.inputs.findIndex(p=>p.id===i.id);return l>-1&&(this.inputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-input",this.id),this}addInput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-input"))){return this.inputs.includes(i)?(a==null||a.attemptAutoclose("add-input",this.id),this):(this.inputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-input",this.id),this)}addOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-output"))){return this.outputs.includes(i)?(a==null||a.attemptAutoclose("add-output",this.id),this):(this.outputs.push(i),a==null||a.add(this,K.Affected),a==null||a.attemptAutoclose("add-output",this.id),this)}removeOutput(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-output"))){const l=this.outputs.findIndex(p=>p.id===i.id);return l>-1&&(this.outputs.splice(l,1),a&&(a==null||a.add(this,K.Affected))),a==null||a.attemptAutoclose("remove-output",this.id),this}addValueReader(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-value-reader"))){var l;return this.process&&!this.process.writesValues.includes(i)&&((l=this.process)==null||l.addValueReader(i,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-value-reader",this.id),this}removeValueReader(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-value-reader"))){var l;return this.process&&this.process.writesValues.includes(i)&&((l=this.process)==null||l.removeValueReader(i,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("remove-value-reader",this.id),this}addSuccessCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-caller")),l=!1){return this.calledBySuccess.find(p=>p.id===i.id)||(this.calledBySuccess.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-success-caller",this.id),this}addErrorCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-caller")),l=!1){return this.calledByError.find(p=>p.id===i.id)||(this.calledByError.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-error-caller",this.id),this}addEntryCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-entry-caller")),l=!1){return this.calledByEntry.find(p=>p.id===i.id)||(this.calledByEntry.push(i),a==null||a.add(this,K.Updated),l&&xe(this,a)),a==null||a.attemptAutoclose("add-entry-caller",this.id),this}addErrorCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-error-call")),l=!1){return this.errorCalls.find(p=>p.id===i.id)||(this.errorCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-error-call",this.id),this}addSuccessCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-success-call")),l=!1){return this.successCalls.find(p=>p.id===i.id)||(this.successCalls.push(i),l&&xe(this,a),a==null||a.add(this,K.Affected)),a==null||a.attemptAutoclose("add-success-call",this.id),this}removeCall(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-call")),l=!1){const p=this.successCalls.findIndex(y=>y.id===i.id);p>-1&&(this.successCalls.splice(p,1),a==null||a.add(this,K.Affected));const t=this.errorCalls.findIndex(y=>y.id===i.id);return t>-1&&(this.errorCalls.splice(t,1),a==null||a.add(this,K.Affected)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-call",this.id),this}removeCaller(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-caller")),l=!1){return this.calledBySuccess=this.calledBySuccess.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByError=this.calledByError.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),this.calledByEntry=this.calledByEntry.filter(p=>p.id!==i.id?!0:(a==null||a.add(this,K.Updated),a==null||a.add(p,K.Affected),!1)),l&&xe(this,a),a==null||a.attemptAutoclose("remove-caller",this.id),this}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}setDeclaration(i){return this.declaration=i,this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){if(this.initialized||this.startedInitialization)return this;if(this.startedInitialization=!0,this.initialData.declaration.type===f.FunctionDeclaration){const a=te(this.initialData.declaration,this.project);this.declaration=a}else{const a=J(this.initialData.declaration),l=this.project.get(a);this.declaration=l}return this.successCalls=this.initialData.successCalls.map(a=>{const l=te(a,this.project);if(l.addSuccessCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.errorCalls=this.initialData.errorCalls.map(a=>{const l=te(a,this.project);if(l.addErrorCaller(this),[f.BreakStatement,f.ContinueStatement].includes(l.type))l.setParent(this.parent.parent,null),l.initChildren(i);else if(l.type===f.ReturnStatement){const p=Lr(this,this.project);l.setParent(p,null),l.initChildren(i)}else l.type!==f.InternalCall&&(l.setParent(this.parent,null),l.initChildren(i));return l}),this.inputs=this.initialData.inputs.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.initialData.process&&(this.process=te(this.initialData.process,this.project),this.process.setParent(this,null),this.process.initChildren(i)),this.initialData.error&&(this.error=te(this.initialData.error,this.project),this.error.setParent(this,null),this.error.initChildren(i)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.x=i.x||p.x,this.y=i.y||p.y,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await xt.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await xt.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await xt.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await xt.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await xt.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await xt.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){const a=[],l=[],p=[],t=[];return this.parent.type===f.Project?(this.parent.removeFunctionCall(this),t.push(this.parent)):this.parent.detachedChildren.includes(this)&&this.parent.unsubscribeDetachedChild(this),i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){var v;const l=[],p=[],t=[],y=[];if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(T=>{const{updated:w,removed:A,added:V}=T.entity.onDetachedDependencyRemoved(this,T.field,a);l.push(...w),p.push(...A),t.push(...V)}),this.process){const{updated:T,removed:w}=(v=this.process)==null?void 0:v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(this.inputs.forEach(T=>{const{updated:w,removed:A}=T.remove({ignoreUpstream:!0},a);l.push(...w),p.push(...A)}),this.outputs.forEach(T=>{const{updated:w,removed:A}=T.remove({ignoreUpstream:!0},a);l.push(...w),p.push(...A)}),this.error){const{updated:T,removed:w}=this.error.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}if(this.successCalls.forEach(T=>{l.push(T),T.removeCaller(this,a)}),this.errorCalls.forEach(T=>{l.push(T),T.removeCaller(this,a)}),!i){const T=this.removeFromParent(a);t.push(...T.added),l.push(...T.updated),p.push(...T.removed),y.push(...T.affected),this.calledBy.forEach(w=>{l.push(w),w.removeCall(this,a)})}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){const a=[],l=[],p=[],t=[];if(i!=null&&i.hasAdded(this.id))return i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(y=>{const{updated:v,removed:T,added:w}=y.entity.onDetachedDependencyRestored(this,y.field,i);l.push(...v),p.push(...T),a.push(...w)}),this.process){const{updated:y}=this.process.restore({},i);l.push(...y)}return this.inputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.outputs.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.successCalls.forEach(y=>{l.push(y),y.addSuccessCaller(this,i)}),this.errorCalls.forEach(y=>{l.push(y),y.addErrorCaller(this,i)}),this.calledBySuccess.forEach(y=>{l.push(y),y.addSuccessCall(this,i)}),this.calledByError.forEach(y=>{l.push(y),y.addErrorCall(this,i)}),this.calledByEntry.forEach(y=>{l.push(y),y.addCall(this,i)}),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this}}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.successCalls.flatMap(l=>l.toFlat(i)),...this.errorCalls.flatMap(l=>l.toFlat(i)),...this.inputs.flatMap(l=>l.toFlat(i)),...this.outputs.flatMap(l=>l.toFlat(i)),...this.process?this.process.toFlat(i):[],...this.error?this.error.toFlat(i):[],...this.calledBy.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.successCalls.flatMap(l=>l.toFlatIds(i)),...this.errorCalls.flatMap(l=>l.toFlatIds(i)),...this.inputs.flatMap(l=>l.toFlatIds(i)),...this.outputs.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,x:this.x,y:this.y,type:this.type}}toJSON(i=new Set){var a,l;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,successCalls:this.successCalls.map(p=>p.toJSON(i)),errorCalls:this.errorCalls.map(p=>p.toJSON(i)),calledBySuccess:this.calledBySuccess.map(p=>p.toReference()),calledByError:this.calledByError.map(p=>p.toReference()),calledByEntry:this.calledByEntry.map(p=>p.toReference()),process:(a=this.process)==null?void 0:a.toJSON(i),declaration:this.declaration.toJSON(i),inputs:this.inputs.map(p=>p.toJSON(i)),outputs:this.outputs.map(p=>p.toJSON(i)),parent:this.parent.toReference(),error:(l=this.error)==null?void 0:l.toJSON(i)})}toJSONClone(i=Le){var l,p,t,y,v,T,w;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),previousVersion:null,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,successCalls:this.successCalls.map(A=>A.toJSONClone({...i,newId:null})),errorCalls:this.errorCalls.map(A=>A.toJSONClone({...i,newId:null})),calledBySuccess:this.calledBySuccess.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByError:this.calledByError.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),calledByEntry:this.calledByEntry.map(A=>A.toReference({seenEntityMaps:i.seenEntityMaps})),process:(T=this.process)==null?void 0:T.toJSONClone({...i,newId:null}),declaration:this.declaration.toJSONClone({...i,newId:null}),inputs:this.inputs.map(A=>A.toJSONClone({...i,newId:null})),outputs:this.outputs.map(A=>A.toJSONClone({...i,newId:null})),error:(w=this.error)==null?void 0:w.toJSONClone({...i,newId:null}),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,x:this.x,y:this.y,process:this.process?this.process.toReference(i):null,inputs:this.inputs.map(p=>p.toReference(i)),outputs:this.outputs.map(p=>p.toReference(i)),declaration:this.declaration.toReference(i),successCalls:this.successCalls.map(p=>p.toReference(i)),errorCalls:this.errorCalls.map(p=>p.toReference(i)),calledBySuccess:this.calledBySuccess.map(p=>p.toReference(i)),calledByError:this.calledByError.map(p=>p.toReference(i)),calledByEntry:this.calledByEntry.map(p=>p.toReference(i)),error:this.error?this.error.toReference(i):null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.successCalls.flatMap(l=>l.toFlatJSON(i)),...this.errorCalls.flatMap(l=>l.toFlatJSON(i)),...this.inputs.flatMap(l=>l.toFlatJSON(i)),...this.outputs.flatMap(l=>l.toFlatJSON(i)),...this.process?this.process.toFlatJSON(i):[],...this.error?this.error.toFlatJSON(i):[]])}toGenerationTarget(){const i=this.parent.type===f.Project?void 0:this.parent.id;return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,calledByEntry:this.calledByEntry.map(a=>a.id),calledBySuccess:this.calledBySuccess.map(a=>a.id),calledByError:this.calledByError.map(a=>a.id),declaration:this.declaration.id,parent:i}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.successCalls.flatMap(l=>l.toFlatGenerationTarget(i)),...this.errorCalls.flatMap(l=>l.toFlatGenerationTarget(i)),...this.inputs.flatMap(l=>l.toFlatGenerationTarget(i)),...this.outputs.flatMap(l=>l.toFlatGenerationTarget(i)),...this.process?this.process.toFlatGenerationTarget(i):[],...this.error?this.error.toFlatGenerationTarget(i):[]])}clearErrors(){var i,a;return this.errors=[],this.inputs.forEach(l=>l.clearErrors()),this.outputs.forEach(l=>l.clearErrors()),this.successCalls.forEach(l=>l.clearErrors()),this.errorCalls.forEach(l=>l.clearErrors()),(i=this.process)==null||i.clearErrors(),(a=this.error)==null||a.clearErrors(),this}validate(){const i=gF(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.inputs.flatMap(a=>a.getErrors()),...this.outputs.flatMap(a=>a.getErrors()),...this.error?this.error.getErrors():[],...this.process?this.process.getErrors():[]]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var j,k;let t=gr(a,this);const y=this.toJSON(),v=l||P.UUID.uuid();y.inputs=[];const T=v.split("-id"),w=T[T.length-1||0]||v;y.id=v,y.version=P.UUID.uuid(),y.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),y.author=(i==null?void 0:i.author)||"1",y.previousVersion=null,y.deleted=!1;const A=St(y,t);a?A.setParent(a,null):A.setParent(this.parent,null),p&&A.subscribe(),A.initChildren(i),i==null||i.add(A,K.Added);const V=(j=this.inputs)==null?void 0:j.map((S,W)=>S.clone(i,A,w+"-input-map-"+W+"-id",p));A.inputs=V;const N=(k=this.outputs)==null?void 0:k.map((S,W)=>S.clone(i,A,w+"-output-map-"+W+"-id",p));return A.outputs=N,this.error&&(A.error=this.error.clone(i,A,w+"-error-map-id",p)),this.process&&(A.process=this.process.clone(i,A,w+"-process-id",p)),i==null||i.attemptAutoclose("clone-entity",this.id),A}removeUnrecognizedInputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-unrecognized-inputs"))){const a=[],l=[],p=[],t=[];return this.inputs.forEach(v=>{if(!this.declaration.inputs.find(w=>{var A;return w.id===((A=v.declaration)==null?void 0:A.id)})){const w=v.remove({ignoreUpstream:!1},i);p.push(...w.removed),a.push(...w.updated)}}),this.inputs.filter((v,T)=>{const w=this.inputs.findIndex(V=>V.declaration===v.declaration&&V!==v);if(w===-1)return!1;const A=this.inputs[w];return L(A==null?void 0:A.createdAt).isSame(L(v.createdAt))?T>w:!!L(A==null?void 0:A.createdAt).isAfter(v.createdAt)}).forEach(v=>{const T=v.remove({ignoreUpstream:!1},i);p.push(...T.removed),a.push(...T.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-inputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}removeUnrecognizedOutputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-unrecognized-outputs"))){const a=[],l=[],p=[],t=[];return this.outputs.forEach(v=>{if(!this.declaration.getUniqueReturnDeclarations().find(w=>{var A;return w.id===((A=v.declaration)==null?void 0:A.id)})){const w=v.remove({ignoreUpstream:!1},i);p.push(...w.removed),a.push(...w.updated)}}),this.outputs.filter((v,T)=>{const w=this.outputs.findIndex(V=>V.declaration===v.declaration&&V!==v);if(w===-1)return!1;const A=this.outputs[w];return L(A==null?void 0:A.createdAt).isSame(L(v.createdAt))?T>w:!!L(A==null?void 0:A.createdAt).isAfter(v.createdAt)}).forEach(v=>{const T=v.remove({ignoreUpstream:!1},i);p.push(...T.removed),a.push(...T.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-outputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncInputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-missing-fixed-inputs"))){const a=[],l=[],p=[],t=[],y=this.declaration.inputs.filter(A=>!this.inputs.find(V=>V.declaration.id===A.id));this.inputs.sort((A,V)=>A.index-V.index),y.forEach(A=>{this.inputs.forEach(j=>{j.index>=A.index&&j.metaSync({index:j.index+1},i)});const V={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.InputMap,declaration:A.toJSON(),readsValue:null,defaultValue:null,index:A.index,name:null,codeName:null,description:null,parent:this.toReference()},N=te(V,this.project);N.setParent(this,i),N.initChildren(i),i==null||i.add(N,K.Added),N.addSelfToProject(i),l.push(N)}),this.inputs.sort((A,V)=>A.index-V.index);const{updated:v,added:T,removed:w}=this.removeUnrecognizedInputs(i);return a.push(...v),l.push(...T),p.push(...w),i==null||i.attemptAutoclose("sync-missing-fixed-inputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncOutputs(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-missing-fixed-outputs"))){const a=[],l=[],p=[],t=[],y=[];this.outputs=this.initialData.outputs.reduce((V,N)=>{if(N.type===f.GenericReference){const k=Ri(N,this.project);return k?[...V,k]:V}const j=te(N,this.project);return y.push(j.index),j.setParent(this,null),j.initChildren(i),[...V,j]},[]);const v=this.declaration.getUniqueReturnDeclarations().filter(V=>!this.outputs.find(N=>N.declaration.id===V.id));this.outputs.sort((V,N)=>V.index-N.index),v.forEach((V,N)=>{this.outputs.forEach(W=>{W.index>=V.index&&W.index++});const j=y.includes(V.index)?this.outputs.length-1+N:V.index,k={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.OutputMap,declaration:V.toJSON(),defaultValue:null,writesValues:[],index:j,parent:this.toReference()},S=te(k,this.project);S.setParent(this,i),S.initChildren(i),i==null||i.add(S,K.Added),S.addSelfToProject(i)}),this.outputs.sort((V,N)=>V.index-N.index);const{updated:T,added:w,removed:A}=this.removeUnrecognizedOutputs(i);return a.push(...T),l.push(...w),p.push(...A),i==null||i.attemptAutoclose("sync-missing-fixed-outputs",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}getUnusedInputs(){return this.inputs.filter(i=>i.suggestion||!i.readsValue&&!i.defaultValue)}getUnusedOutputs(){return this.outputs.filter(i=>i.suggestion||!i.writesValues.length)}getUsedInputs(){return this.inputs.filter(i=>!i.suggestion&&(i.readsValue||i.defaultValue))}getUsedOutputs(){return this.outputs.filter(i=>!i.suggestion&&i.writesValues.length)}};D(xt,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(xt,"type",f.FunctionCall),D(xt,"USER_MANAGED_PARENT_TYPES",[...wr,f.Project]),D(xt,"PARENT_TYPES",[...xt.USER_MANAGED_PARENT_TYPES]),D(xt,"MUTABLE_BASE_PROPERTIES",[]),D(xt,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),D(xt,"BASE_PROPERTIES",[...xt.MUTABLE_BASE_PROPERTIES,...xt.INMUTABLE_BASE_PROPERTIES]),D(xt,"MUTABLE_META_PROPERTIES",["x","y"]),D(xt,"INMUTABLE_META_PROPERTIES",[...xt.INMUTABLE_BASE_PROPERTIES]),D(xt,"META_PROPERTIES",[...xt.MUTABLE_META_PROPERTIES,...xt.INMUTABLE_META_PROPERTIES]),D(xt,"MUTABLE_UPSTREAM_PROPERTIES",["calledBySuccess","calledByError","calledByEntry"]),D(xt,"INMUTABLE_UPSTREAM_PROPERTIES",["declaration","parent"]),D(xt,"UPSTREAM_PROPERTIES",[...xt.MUTABLE_UPSTREAM_PROPERTIES,...xt.INMUTABLE_UPSTREAM_PROPERTIES]),D(xt,"MUTABLE_DOWNSTREAM_PROPERTIES",["successCalls","errorCalls","writesValues","inputs","outputs","error"]),D(xt,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(xt,"DOWNSTREAM_PROPERTIES",[...xt.MUTABLE_DOWNSTREAM_PROPERTIES,...xt.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(xt,"PROPERTIES",[...xt.META_PROPERTIES,...xt.UPSTREAM_PROPERTIES,...xt.DOWNSTREAM_PROPERTIES]);let Xa=xt;function gA(d){return d&&typeof d.then=="function"}function A0e(d){const u=new Cn(d[0]),i=d.map(l=>l.id),a={};return d.forEach(l=>{a[l.id]=l}),u.order=i,u.flatRecord=a,u.orderEntities(),u.order.map(l=>u.flatRecord[l])}function I0e(d){const u=new Cn(Object.values(d)[0]),i=Object.keys(d);return u.order=i,u.flatRecord=d,u.orderEntities(),u.order}class Cn{constructor(u){D(this,"order",[]);D(this,"flatRecord",{});D(this,"allBuiltInEntityIds",Vs());D(this,"onGoingVisits",{});u&&(this.flatten(u),this.orderEntities())}flatten(u){const i=new Set(Vs()),a=R(ye(u,i,{ignoreBuiltInBaseEntities:!0})),l=new Set;for(const p of a)this.flatRecord[p.id]=p,l.add(p.id);this.order=Array.from(l)}moveEntityAfterDependencies(u){const{upstream:i}=$d(u,this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds});for(const a of Object.keys(i)){const l=this.order.indexOf(a),p=this.order.indexOf(u.id);if(l>p)return this.order.splice(p,1),this.order.splice(l,0,u.id),!0}return!1}orderEntities(){let u=!1;for(let i=0;i<this.order.length;i++){const a=this.order[i],l=this.flatRecord[a];if(l||console.warn(`Entity with id ${a} not found in flatRecord. Skipping...`),this.moveEntityAfterDependencies(l)){u=!0;break}}u&&this.orderEntities()}getUpstreamOngoingDependenciesVisits(u,i){const{upstream:a}=$d(this.flatRecord[u],this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds}),l={};return Object.entries(this.onGoingVisits[i]||{}).forEach(([p,t])=>{Object.keys(a).includes(p)&&(l[p]=t)}),l}getDownstreamOngoingDependenciesVisits(u,i){const a=Object.keys(this.onGoingVisits[i]||{}),l=new Set(a.flatMap(t=>Object.keys($d(this.flatRecord[t],this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds}).downstream))),p={};return Array.from(l).forEach(t=>{t===u&&(p[t]=this.onGoingVisits[i][t])}),p}async settlePromises(u,i){const a=Object.values(u);a.length&&await Promise.all(a),Object.keys(u).forEach(l=>{delete this.onGoingVisits[i][l]})}visit(u){const i=this.order;for(const a of i)u(this.flatRecord[a],this.flatRecord);return this}reverseVisit(u){const i=this.order.slice().reverse();for(const a of i)u(this.flatRecord[a],this.flatRecord);return this}async visitAsync(u){const i=this.order,a=Math.random().toString(36).substring(7);this.onGoingVisits[a]={};for(const l of i){const p=this.getUpstreamOngoingDependenciesVisits(l,a);Object.keys(p).length&&await this.settlePromises(p,a);const t=u(this.flatRecord[l],this.flatRecord);gA(t)&&(this.onGoingVisits[a][l]=t)}return await this.settlePromises(this.onGoingVisits[a],a),this.onGoingVisits[a]={},this}async reverseVisitAsync(u){const i=this.order.slice().reverse(),a=Math.random().toString(36).substring(7);this.onGoingVisits[a]={};for(const l of i){const p=this.getDownstreamOngoingDependenciesVisits(l,a);Object.keys(p).length&&await this.settlePromises(p,a);const t=u(this.flatRecord[l],this.flatRecord);gA(t)&&(this.onGoingVisits[a][l]=t)}return await this.settlePromises(this.onGoingVisits[a],a),this.onGoingVisits[a]={},this}}function DF(d,u){switch(d.id){case ve["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.id:{const i=d.project.entities.filter(v=>!!v.implements.find(T=>T.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id)),a=i.find(v=>{const T=v.properties.find(V=>V.implements&&V.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),w=T==null?void 0:T.getDefaultValue();return(w==null?void 0:w.value)===!0});if(!a&&i.length){const T=i[0].properties.find(A=>A.implements&&A.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),w=T==null?void 0:T.defaultValue;if(w)w.metaSync({value:!0},u);else if(T!=null&&T.dataType){const A={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(u==null?void 0:u.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.LiteralValue,standaloneParent:null,name:Q.EntityTemplate,autogeneration:null,value:!0,valueAsTypeSingle:null,valueAsTypeList:null,parent:T==null?void 0:T.toReference()},V=te(A,d.project);return V.setParent(T,u),V.initChildren(u),u==null||u.add(V,K.Added),V.addSelfToProject(u),{newEntities:[V]}}return{newEntities:[]}}else if(a)return{newEntities:[]};const l=d.project.get(ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id),p=Ky(l,"Main database",u);if(p.errors.length>0)return{newEntities:[]};const t=p.properties.find(v=>v.implements&&v.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),y=t==null?void 0:t.defaultValue;if(y)y.metaSync({value:!0},u);else if(t!=null&&t.dataType){const v={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(u==null?void 0:u.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.LiteralValue,standaloneParent:null,name:Q.EntityTemplate,autogeneration:null,value:!0,valueAsTypeSingle:null,valueAsTypeList:null,parent:t==null?void 0:t.toReference()},T=te(v,d.project);T.setParent(t,u),T.initChildren(u),u==null||u.add(T,K.Added),T.addSelfToProject(u)}return{newEntities:[p]}}}return{newEntities:[]}}function OF(d,u){const i=[],a=[],l=[],p=[];return d.implements.filter(y=>y.type===f.BuiltInBaseEntity).forEach(y=>{var v;switch(y.id){case ve["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.id:{const T=d.project.entities.filter(N=>N.implements.find(j=>j.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id));let w=T.find(N=>!!N.properties.find(j=>{var k;return j.implements&&j.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id&&((k=j.getDefaultValue())==null?void 0:k.value)===!0}));if(!w&&T.length)w=T[0];else if(!w&&!T.length){w=d.project.getBuiltIn(ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id).implement("Relational database",u);const j=w.properties.find(k=>{var S;return((S=k.implements)==null?void 0:S.id)===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id});(v=j==null?void 0:j.defaultValue)==null||v.metaSync({value:!0},u),a.push(w)}const A=d.properties.find(N=>N.implements&&N.implements.id===ve["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.properties.database.id),V=A==null?void 0:A.defaultValue;if(A&&!V){const N={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(u==null?void 0:u.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.LiteralValue,standaloneParent:null,name:Q.EntityTemplate,autogeneration:null,value:null,valueAsTypeSingle:(w==null?void 0:w.toJSON())||null,valueAsTypeList:null,parent:A==null?void 0:A.toReference()},j=te(N,d.project);j.hydrateAncestors(),j.setParent(A,u),j.addSelfToProject(u),j.initChildren(u),u==null||u.add(j,K.Added),a.push(j);return}else V&&!V.valueAsTypeSingle&&V.setValueAsTypeSingle(w||null,u);return}}}),{self:d,updated:R(i),added:R(a),removed:R(l),affected:R(p)}}function Ky(d,u,i,a){const l=a||P.UUID.uuid(),p=P.UUID.uuid(),t={id:l,version:p,createdAt:(i==null?void 0:i.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:u,type:f.DefinitionEntity,codeName:null,description:null,static:d.static,abstract:!1,properties:[],methods:[],abstractMethods:[],extends:[],implements:[d.toJSON()],x:0,y:0,parent:d.project.toReference()};DF(d,i);const y=te(t,d.project);return y.hydrateAncestors(),i==null||i.add(y,K.Added),y.addSelfToProject(i),y.addImplementation(d),y.setParent(d.project,i),y.initChildren(i),OF(y,i),y}function _A(d,u){return u.entities.find(l=>{const p=l.properties,t=p.map(A=>A.name),y=d.every(A=>t.includes(A)),v=t.filter(A=>!d.includes(A)),T=p.every(A=>!v.includes(A.name)||!A.required);return y&&T})||null}function CF(d,u,i,a=Yr.OrDataTypeGroup){const l=[],p=[],t=[],y=[],T={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:null,implementationChooseOne:!1,entity:d.toJSON(),isList:!1,asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:null,interactiveEntities:null,actionEntities:null,like:!0,inferred:!1,parentRelationType:a,parent:u.toReference()},w=te(T,d.project);return p.push(w),w.setParent(u,i),w.initChildren(i),i==null||i.add(w,K.Added),w.setEntity(d,i),w.addSelfToProject(i),{updated:R(l),added:R(p),removed:R(t),affected:R(y),self:w}}function DA(d,u,i,a,l){var T,w,A,V,N,j,k,S;const p=[],t=[],y=[],v=[];switch(typeof d){case"string":let W=!1;const ne=new Date(d);if(ne instanceof Date&&!isNaN(ne.valueOf())&&(W=!0),W){const re=u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Date].id);u.setEntity(re,a);break}else{const re=u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.String].id);u.setEntity(re,a);break}case"number":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Number].id),a);break;case"boolean":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Boolean].id),a);break;case"object":if(d===null){u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Null].id),a);break}else if(Array.isArray(d))if(u.metaSync({isList:!0},a),d.length>0){const re=d.slice(0,5).filter(se=>se!==void 0);if(re.every(se=>typeof se==typeof re[0])&&(typeof re[0]!="object"||re[0]===null))switch(typeof re[0]){case"string":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.String].id),a);break;case"number":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Number].id),a);break;case"boolean":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Boolean].id),a);break;case"object":u.setEntity(u.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Null].id),a);break}else{const se=[];let he=!1;re.forEach(z=>{var ce,H,de,Te;if(Array.isArray(z)&&(he=!0),typeof z=="object"&&!Array.isArray(z)&&z!==null){const Ne=ky(z,u.project,{...i,id:P.UUID.uuid()},a,l);Ne.hasCreated&&se.push((ce=Ne.changeSet)==null?void 0:ce.self),p.push(...(H=Ne.changeSet)==null?void 0:H.updated),t.push(...(de=Ne.changeSet)==null?void 0:de.added),y.push(...(Te=Ne.changeSet)==null?void 0:Te.removed)}});const X=R(se);if(!X.length&&!he){re.forEach(z=>{const ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:null,implementationChooseOne:!1,entity:null,isList:!1,asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:!1,interactiveEntities:!0,actionEntities:!1,like:!0,inferred:!1,parentRelationType:Yr.OrDataTypeGroup,parent:u.toReference()},H=te(ce,u.project);switch(H.setParent(u,a),H.initChildren(a),a==null||a.add(H,K.Added),H.addSelfToProject(a),typeof z){case"string":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.String].id),a);break;case"number":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Number].id),a);break;case"boolean":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Boolean].id),a);break;case"object":H.setEntity(H.project.getBuiltIn(ve[f.PrimitiveEntity][Q.Null].id),a);break}});break}else X.length===1&&!he?u.setEntity(X[0],a):re.forEach(z=>{if(typeof z=="object"&&!Array.isArray(z)&&z!==null){const ce=_A(Object.keys(z),u.project);if(ce){const H=CF(ce||X[0],u,a,Yr.OrDataTypeGroup);p.push(...H.updated),t.push(...H.added),y.push(...H.removed)}}else{const ce={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,options:null,implementationChooseOne:!1,entity:null,isList:Array.isArray(z),asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:!1,interactiveEntities:!0,actionEntities:!1,like:!0,inferred:!1,parentRelationType:Yr.OrDataTypeGroup,parent:u.toReference()},H=te(ce,u.project);H.setParent(u,a),H.initChildren(a),a==null||a.add(H,K.Added),H.addSelfToProject(a);const de=DA(z,H,{...i,id:P.UUID.uuid()},a,l);p.push(...de.updated),t.push(...de.added),y.push(...de.removed)}})}}else{const re=ky(d[0],u.project,{...i},a,l);u.setEntity((T=re.changeSet)==null?void 0:T.self,a),p.push(...(w=re.changeSet)==null?void 0:w.updated),t.push(...(A=re.changeSet)==null?void 0:A.added),y.push(...(V=re.changeSet)==null?void 0:V.removed);break}else{const re=ky(d,u.project,{...i},a,l);u.setEntity((N=re.changeSet)==null?void 0:N.self,a),p.push(...(j=re.changeSet)==null?void 0:j.updated),t.push(...(k=re.changeSet)==null?void 0:k.added),y.push(...(S=re.changeSet)==null?void 0:S.removed);break}}return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:u}}function ky(d,u,i,a,l){const p=[],t=[],y=[],v=[],T=Object.keys(d),w=_A(T,u);if(w)return{hasCreated:!1,changeSet:{updated:[],added:[],removed:[],affected:[],self:w}};const A=l?i.name+" of "+l.name:i.name,N={id:i.id||P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:A,codeName:null,type:f.DefinitionEntity,description:i.description||null,static:i.static||!1,abstract:i.abstract||!1,properties:[],methods:[],abstractMethods:[],extends:[],implements:[],x:0,y:0,parent:u.toReference()},j=te(N,u);return j.setParent(u,a),j.initChildren(a),a==null||a.add(j,K.Added),j.addSelfToProject(a),t.push(j),T.forEach((k,S)=>{const ne={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:k,type:f.Property,codeName:k,description:null,static:!1,abstract:!1,defaultValue:null,constant:!1,interactive:!0,dataType:null,implements:null,extends:null,index:S,hidden:!1,private:!1,required:!0,parent:j.toReference()},re=te(ne,u);re.setParent(j,a),re.initChildren(a),a==null||a.add(re,K.Added),re.addSelfToProject(a),t.push(re);const pe=d[k],he={id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||new Date().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DataType,parentRelationType:null,options:null,implementationChooseOne:!1,entity:null,isList:!1,asType:!1,andChildrenGroup:null,orChildrenGroup:null,staticEntities:!1,interactiveEntities:!0,actionEntities:!1,like:!0,inferred:!1,parent:re.toReference()},X=te(he,u);X.setParent(re,a),X.initChildren(a),a==null||a.add(X,K.Added),X.addSelfToProject(a),t.push(X);const z=DA(pe,X,{...i,name:k,id:P.UUID.uuid()},a,l||j);p.push(...z.updated),t.push(...z.added),y.push(...z.removed)}),{hasCreated:!0,changeSet:{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:j}}}function ma(d,u,i,a){const l=[];return!d.length||!u.length?{errors:l,overlap:!1}:(d.length>u.length?d.forEach(p=>{const t=u.find(v=>v.name===p.name),y=u.find(v=>{var T,w;return!!p.implements&&((T=v.implements)==null?void 0:T.id)===((w=p.implements)==null?void 0:w.id)});if(t){const v=new Zt({id:p.id+"--"+t.id+"--"+a,message:`Entity of type ${p.type} named "${p.name}" with id "${p.id}" overrides a base ${t.type} ${t.name} with id "${t.id}" that has the same name`,issue:null,severity:Z.Error,code:a,entity:p,firstRelationship:t});l.push(v)}if(y){const v=new Zt({id:p.id+"--"+y.id+"--"+i,message:`Entity of type ${p.type} named "${p.name}" with id "${p.id}" overrides a base ${y.type} ${y.name} with id "${y.id}" that implements the same base descriptor`,issue:null,severity:Z.Error,code:i,entity:p,firstRelationship:y});l.push(v)}}):u.forEach(p=>{var v;const t=d.find(T=>T.name===p.name),y=d.find(T=>{var w,A;return!!T.implements&&((w=T.implements)==null?void 0:w.id)===((A=p.implements)==null?void 0:A.id)});if(t){const T=new Zt({id:t.id+"--"+p.id+"--"+a,message:`Entity of type ${t.type} named "${t.name}" with id "${t.id}" overrides a base entity ${p.name} with id "${p.id}" that has the same name`,issue:null,severity:Z.Error,code:a,entity:t,firstRelationship:p});l.push(T)}if(y){const T=new Zt({id:y.id+"--"+p.id+"--"+i,message:`Entity of type ${y.type} named "${y.name}" with id "${y.id}" overrides a base entity ${p.name} with id "${p.id}" that implements the same base ${(v=y==null?void 0:y.implements)==null?void 0:v.type}`,issue:null,severity:Z.Error,code:i,entity:y,firstRelationship:p});l.push(T)}}),{errors:l,overlap:!!l.length})}function w0e(d,u){return d.abstract||(d.properties.forEach(a=>{a.abstract||a.metaSync({abstract:!0},u)}),Object.values(d.detachedDependents).forEach(a=>{a.field===Ib.Entity&&a.entity.remove({ignoreUpstream:!1},u)}),d.metaSync({abstract:!0},u)),d}function R0e(d,u){return d.abstract&&(d.properties.forEach(a=>{a.abstract&&a.metaSync({abstract:!1},u)}),Object.values(d.detachedDependents).forEach(a=>{(a.field===tm.Implements||a.field===tm.Extends)&&a.entity.onDetachedDependencyRemoved(d,a.field,u)}),d.metaSync({abstract:!1},u)),d}function g0e(d,u){return d.static||(d.properties.forEach(a=>{a.static||a.metaSync({static:!0},u)}),d.metaSync({static:!0},u)),d}function _0e(d,u){return d.static&&d.metaSync({static:!1},u),d}var $F=(d=>(d.StringValueMustNotHaveSpaces="string-value-must-not-have-spaces",d.StringValueMustNotHaveDashes="string-value-must-not-have-dashes",d))($F||{});function PF(d,u){const i=[],a=u;if(!a)return{errors:i,override:u};if(typeof a!="string")return{errors:[],override:u};if(a.includes(" ")){const l=new Zt({id:d.id+"--string-value-must-not-have-spaces",message:`Entity of type ${d.type} with id "${d.id}" has an invalid value "${u}". The value cannot contain spaces.`,issue:null,severity:Z.Error,code:"string-value-must-not-have-spaces",entity:d});i.push(l)}return{errors:i,override:a.replace(/\s/g,"-")}}function VF(d,u){const i=[],a=u;if(!a)return{errors:i,override:u};if(typeof a!="string")return{errors:[],override:u};if(a.includes(" ")){const l=new Zt({id:d.id+"--string-value-must-not-have-spaces",message:`Entity of type ${d.type} with id "${d.id}" has an invalid value "${u}". The value cannot contain spaces or dashes.`,issue:null,severity:Z.Error,code:"string-value-must-not-have-spaces",entity:d});i.push(l)}if(a.includes("-")){const l=new Zt({id:d.id+"--string-value-must-not-have-dashes",message:`Entity of type ${d.type} with id "${d.id}" has an invalid value "${u}". The value cannot contain spaces or dashes.`,issue:null,severity:Z.Error,code:"string-value-must-not-have-dashes",entity:d});i.push(l)}return{errors:i,override:a.replace(/\s|-/g,"_")}}function OA(d,u){var i;if(d.type===f.LiteralValue){let a=(i=d.value)==null?void 0:i.toString();try{a=JSON.stringify(d.value,null,2)}catch{}return`${d.type}: ${d.id} (${ie(d,u)}) = ${a}`}if(d.type===f.DataType){if(d instanceof Yi||d.increaseVersion)return`${d.type}: ${d.id} (${Td(d)})`;try{const a=Td(d);return`${d.type}: ${d.id} (${a})`}catch{}}return`${d.type}: ${d.id} (${ie(d,u)})`}function Cd(d,u){const i=Qa(d);if(i.length===0)return{list:[],last:null};let a=null;return{list:i.flatMap(p=>{if(p===u)return a=p,[p];const t=Cd(p,u);return t.last&&(a=t.last),[p,...t.list]}),last:a}}function Pp(d){const u=d.calledBy;if(u.length===0)return d.project;const i=u.reduce((a,l)=>{const p=wi(l,d.project);return!p||p.type===f.Project?a:a.type===f.Project||Cd(p,a).last?p:(Cd(a,p).last,a)},d.project);return i.type===f.FunctionDeclaration&&i.parent.type===f.Loop?i.parent:i}function xe(d,u){let i=Pp(d);if(d.type===f.InternalCall)if(d.parent.type===f.VariableInstance){const l=Ns(i,d.parent.declaration,d.project);!l.compatible&&l.type!=="b-is-global-a-is-not"?d.parent.remove({ignoreUpstream:!1},u):(d.parent.setParent(i,u),d.parent.addSelfToProject(u))}else d.parent.setParent(i,u),d.parent.addSelfToProject(u);else if((d.type===f.ContinueStatement||d.type===f.BreakStatement)&&i.type!==f.Loop){d.remove({ignoreUpstream:!1},u);return}else if(d.type===f.ReturnStatement&&!wr.includes(i.type)){d.remove({ignoreUpstream:!1},u);return}else if(st.includes(d.type)){const l=d.usedInternalCalls[0];if(l)if(i=Pp(l),d.type===f.VariableInstance){const p=Ns(i,d.declaration,d.project);!p.compatible&&p.type!=="b-is-global-a-is-not"?d.remove({ignoreUpstream:!1},u):(d.setParent(i,u),d.addSelfToProject(u))}else d.setParent(i,u),d.addSelfToProject(u);else if(d.type===f.VariableInstance){const p=Ns(i,d.declaration,d.project);!p.compatible&&p.type!=="b-is-global-a-is-not"?d.remove({ignoreUpstream:!1},u):(d.setParent(i,u),d.addSelfToProject(u))}else d.setParent(i,u),d.addSelfToProject(u)}else d.setParent(i,u),d.addSelfToProject(u);if(nr.includes(d.type))return;pt(d).forEach(l=>{let p=Pp(l);if(l.type===f.InternalCall)if(l.parent.type===f.VariableInstance){const t=Ns(p,l.parent.declaration,d.project);!t.compatible&&t.type!=="b-is-global-a-is-not"?l.parent.remove({ignoreUpstream:!1},u):(l.parent.setParent(p,u),l.parent.addSelfToProject(u))}else l.parent.setParent(p,u),l.parent.addSelfToProject(u);else if((l.type===f.ContinueStatement||l.type===f.BreakStatement)&&p.type!==f.Loop){l.remove({ignoreUpstream:!1},u);return}else if(l.type===f.ReturnStatement&&!wr.includes(p.type)){l.remove({ignoreUpstream:!1},u);return}else if(st.includes(l.type)){const t=l.usedInternalCalls[0];if(t)if(p=Pp(t),l.type===f.VariableInstance){const y=Ns(p,l.declaration,d.project);!y.compatible&&y.type!=="b-is-global-a-is-not"?l.remove({ignoreUpstream:!1},u):(l.setParent(p,u),l.addSelfToProject(u))}else l.setParent(p,u),l.addSelfToProject(u);else if(l.type===f.VariableInstance){const y=Ns(p,l.declaration,d.project);!y.compatible&&y.type!=="b-is-global-a-is-not"?l.remove({ignoreUpstream:!1},u):(l.setParent(p,u),l.addSelfToProject(u))}else l.setParent(p,u),l.addSelfToProject(u)}else l.setParent(p,u),l.addSelfToProject(u)})}function Sy(d,u,i=new Set){const a=sn(d),l=sn(u),p=a.filter(v=>!l.includes(v)),t=a.filter(v=>l.includes(v)),y=p.reduce((v,T)=>i.has(T.id)?v:(i.add(T.id),R([...v,...Sy(T,u,i)])),[]);return R([...t,...y])}function il(d,u){const i=Cd(d,u);return i.last===u&&i.list.length>0&&i.list[0]!==u}function CA(d,u){return!!Cd(d,u).last}function D0e(d){if(Ht.includes(d.type))return d;if([...ws,f.VariableDeclaration].includes(d.type)){const u=d.parent;return Ht.includes(u.type)?u:null}return null}function $A(d,u){if(!d||!u)throw new Error("Both entities must be defined to find a common ancestor");if(d===u)return d;const i=d.parent;if(i){if(i===u)return u;if(i.type===f.Project)return null}else return null;const a=u.parent;if(a){if(a===d)return d;if(a.type===f.Project)return null}else return null;return $A(i,a)}function rr(d){if(Bf.includes(d.type)){if(d.type===f.FunctionDeclaration){const u=d.parent;if(u.type===f.DefinitionEntity)return rr(u);if(u.type===f.Loop)return u}return d.type===f.DefinitionEntity&&d.parent.type===f.DataType?rr(d.parent):d}else{const u=d.parent;return u?rr(u):null}}function qy(d,u){const i=Vp(d,u);if(!i)return null;if(Bf.includes(i.type)){if(i.type===f.FunctionDeclaration){const a=Vp(i.parent,u);if(a){if(a.type===f.DefinitionEntity)return a;if(a.type===f.Loop)return a}}return i}else{const a=i.parent?Vp(i.parent,u):null;return a?qy(a,u):null}}function NF(d){if(!d)return null;if(ws.includes(d.type))return d;const u=d.parent;return u?NF(u):null}function LF(d){if(!d)return null;if(er.includes(d.type))return d;const u=d.parent;return u?LF(u):null}function BF(d){if(!d)return null;if(Rs.includes(d.type))return d;const u=d.parent;return u?BF(u):null}function O0e(d){return d.type===f.VariableDeclaration?[d]:er.includes(d.type)?[...d.inputs,...d.outputs||[]]:nr.includes(d.type)?d.outputs:Pl.includes(d.type)||d.type===f.FunctionDeclaration?d.inputs:[]}function C0e(d){const u=sn(d),i=[],a=[];o1.includes(d.type)&&i.push(...Zy(d));const l=u.filter(p=>{const t=i.includes(p);return t?!1:ws.includes(p.type)&&!t?(a.push(p),!1):!0});return i.sort((p,t)=>il(t,p)?-1:0),a.sort((p,t)=>il(t,p)?-1:0),[...i,...a,...l]}function MF(d){return[...d].sort((u,i)=>il(i,u)?-1:0)}function $0e(d){const u=MF(d),i=[];return u.forEach(a=>{const l=i[i.length-1];if(l){const p=l[l.length-1];il(a,p)?i.push([a]):l.push(a)}else i.push([a])}),i}function ci(d){const u=d.map(i=>rr(i));return R(u)}function Zy(d){return er.includes(d.type)?[...ci(d.successCalls),...ci(d.errorCalls)]:Ht.includes(d.type)?ci(d.calls):[]}function P0e(d,u){return Zy(d).includes(u)}function PA(d){return d.writesValues||[]}function V0e(d,u){return PA(d).includes(u)}function UF(d){var u;return st.includes((u=d==null?void 0:d.readsValue)==null?void 0:u.type)?d.readsValue:null}function N0e(d){return d.writesValues}function jF(d=[]){return d.map(UF).filter(u=>!!u)}function Jy(d=[]){return d.map(u=>u.writesValues).flat().filter(u=>st.includes(u.type))}function xF(d=[]){return d.map(u=>u.readsValue).filter(u=>!!u&&st.includes(u.type))}function FF(d){return st.includes(d.type)?d:null}function GF(d){return d.writesValues.map(FF).filter(u=>!!u)}function KF(d=[]){return d.reduce((u,i)=>i.type===f.OutputMap?[...u,...GF(i)]:u,[])}function pt(d){return d.type===f.Loop?R([...Ps(ci(d.successCalls)),...Ps(ci(d.errorCalls)),...d.body?pt(d.body):[]]):er.includes(d.type)?R([...Ps(ci(d.successCalls)),...Ps(ci(d.errorCalls))]):Ht.includes(d.type)?R(Ps(ci(d.calls))):[]}function L0e(d){return er.includes(d.type)?[...Ps(ci(d.successCalls)),...Ps(ci(d.errorCalls))]:Ht.includes(d.type)?Ps(ci(d.calls)):[]}function kF(d,u=new Set){return d.writesValues.filter(a=>st.includes(a.type)&&!u.has(a.id)).reduce((a,l)=>u.has(l.id)?a:[...a,...Xt(l,u)],[])}function SF(d,u=new Set){var a;return(((a=d.readsValue)==null?void 0:a.writesValues)||[]).filter(l=>st.includes(l.type)&&!u.has(l.id)).reduce((l,p)=>u.has(p.id)?l:[...l,...Xt(p,u)],[])}function Xt(d,u=new Set){if(u.has(d.id))return[];if(d.type===f.ReturnStatement)return xF(d.outputs).reduce((a,l)=>[...a,...Xt(l,u)],[]);if(d.type===f.FunctionCall||d.type===f.Operation||d.type===f.Condition)return[...pt(d).reduce((p,t)=>{const y=rr(t);return[...p,...Xt(y||t,u)]},[]),...jF(d.inputs),...KF(d.outputs)].reduce((p,t)=>[...p,...Xt(t,u)],[]);if(Pl.includes(d.type)){const i=Jy(d.inputs),l=pt(d).reduce((p,t)=>{const y=rr(t);return[...p,...Xt(y||t,u)]},[]);return i.push(...l),i.reduce((p,t)=>[...p,...Xt(t,u)],[])}if(d.type===f.FunctionDeclaration){const i=[...Jy(d.inputs)],l=pt(d).reduce((p,t)=>{const y=rr(t);return[...p,...Xt(y||t,u)]},[]);return i.push(...l),i.reduce((p,t)=>[...p,...Xt(t)],[])}if(st.includes(d.type)){u.add(d.id);const a=pt(d).reduce((l,p)=>{const t=rr(p);return[...l,...Xt(t||p,u)]},[]);return[d,...a,...SF(d,u),...kF(d,u)]}return[]}function Xi(d,u=new Set){return u.has(d.id)?[]:(u.add(d.id),[...sn(d).reduce((l,p)=>[...l,p,...Xi(p,u)],[])])}function Ps(d){return d.reduce((u,i)=>i.type===f.ReturnStatement||i.type===f.ContinueStatement||i.type===f.BreakStatement?[...u,i]:[...u,i,...pt(i)],[])}function qF(d){const u=d.entities||[],i=[...u,...d.functions||[],...d.events||[],...d.projects||[]],a=u.reduce((v,T)=>[...v,...T.properties],[]),l=u.reduce((v,T)=>[...v,...T.methods],[]),p=l.reduce((v,T)=>[...v,...Jy(T.inputs),...Ps(ci(T.calls)),...T.returnStatements],[]),t=d.functions.reduce((v,T)=>[...v,...Ps(ci(T.calls)),...T.returnStatements],[]),y=d.events.reduce((v,T)=>[...v,...Ps(ci(T.calls)),...T.returnStatements],[]);return[...i,...a,...l,...p,...t,...y]}function ZF(d,u){return u.filter(a=>{if(!a)return!1;switch(a.type){case f.FunctionCall:return a.inputs.find(l=>l.id===d.id)!==void 0||a.outputs.find(l=>l.id===d.id)!==void 0;case f.Condition:return a.successCalls.find(l=>l.id===d.id)!==void 0||a.errorCalls.find(l=>l.id===d.id)!==void 0||a.inputs.find(l=>l.id===d.id)!==void 0;case f.Operation:return a.outputs.find(l=>l.id===d.id)!==void 0;case f.VariableDeclaration:return er.includes(d.type)?A6(d).find(p=>{var t;return((t=p.readsValue)==null?void 0:t.id)===a.id})!==void 0:!1;case f.DefinitionEntity:return a.properties.find(l=>l.id===d.id)!==void 0||a.methods.find(l=>l.id===d.id)!==void 0;case f.FunctionDeclaration:return a.inputs.find(l=>l.id===d.id)!==void 0||(a.returnStatements.map(l=>l.outputs).flat()||[]).find(l=>l.id===d.id)!==void 0;default:return!1}})}function B0e(d){const u=qF(d.project);return ZF(d,u)}function Vp(d,u){return d?typeof d=="string"?u[d]:d.type===f.GenericReference?u[d.entityId]:u[d.id]?u[d.id]:null:null}function JF(d={},u){const i={};return Object.keys(d).forEach(a=>{const l=u.get(a)||a,p=d[a];i[l]=p}),i}function $d(d,u={},i={}){const a={ignoreBuiltInBaseEntities:!1,allBuiltInEntityIds:[],entityMaps:new Map,...i};if(a.ignoreBuiltInBaseEntities&&(ki.includes(d.type)||(a.allBuiltInEntityIds||[]).includes(d.id)))return{upstream:{},downstream:{}};const l=d,p=d,t=d,y=d,v=d,T=d,w=d,A=d,V=d,N=d,j=d,k=d,S=d,W=[...S.readsValue?[S.readsValue]:[],...S.declaration?[S.declaration]:[],...(k.calledByEntry||[]).flatMap(se=>se),...(k.calledBySuccess||[]).flatMap(se=>se),...(k.calledByError||[]).flatMap(se=>se),...N.parent?[N.parent]:[]];Array.isArray(t.implements)?W.push(...t.implements.flatMap(se=>se)):V.implements&&W.push(V.implements),Array.isArray(t.extends)?W.push(...t.extends.flatMap(se=>se)):V.extends&&W.push(V.extends),v.valueAsTypeList&&Array.isArray(v.valueAsTypeList)&&W.push(...v.valueAsTypeList.flatMap(se=>se)),v.valueAsTypeSingle&&W.push(v.valueAsTypeSingle),(S.internalCalls||[]).forEach(se=>{const he=J(se);if(he&&u[he]){const X=u[he];[...X.calledByEntry||[],...X.calledBySuccess||[],...X.calledByError||[]].forEach(z=>{const ce=J(z);ce&&u[ce]&&W.push(u[ce])})}});const ne=[...(l.inputs||[]).flatMap(se=>se),...(j.inputsDeclarations||[]).flatMap(se=>se),...(l.outputs||[]).flatMap(se=>se),...(j.outputsDeclarations||[]).flatMap(se=>se),...(S.internalCalls||[]).flatMap(se=>se),...S.writesValues||[],...k.dataType?[k.dataType]:[],...T.body?[T.body]:[],...k.defaultValue?[k.defaultValue]:[],...(k.successCalls||[]).flatMap(se=>se),...(k.errorCalls||[]).flatMap(se=>se),...(t.properties||[]).flatMap(se=>se),...(t.methods||[]).flatMap(se=>se),...(t.abstractMethods||[]).flatMap(se=>se),...w.error?[w.error]:[],...w.process?[w.process]:[],...N.throws?[N.throws]:[],...(p.andChildrenGroup||[]).flatMap(se=>se),...(p.orChildrenGroup||[]).flatMap(se=>se),...(A.entities||[]).flatMap(se=>se),...(A.functions||[]).flatMap(se=>se),...(A.functionCalls||[]).flatMap(se=>se),...(A.events||[]).flatMap(se=>se),...(A.conditions||[]).flatMap(se=>se),...(A.operations||[]).flatMap(se=>se),...(A.loops||[]).flatMap(se=>se),...(A.variableDeclarations||[]).flatMap(se=>se),...(A.variableInstances||[]).flatMap(se=>se),...(A.searches||[]).flatMap(se=>se),...(A.projects||[]).flatMap(se=>se),...(y.calls||[]).flatMap(se=>se)];d.type===f.DataType&&(p.entity&&u[J(p.entity)]&&u[J(p.entity)].parent&&J(u[J(p.entity)].parent)===d.id?ne.push(p.entity):p.entity&&W.push(p.entity)),(S.internalCalls||[]).forEach(se=>{const he=J(se);if(he&&u[he]){const X=u[he];[...X.successCalls||[],...X.errorCalls||[]].forEach(z=>{const ce=J(z);ce&&u[ce]&&ne.push(u[ce])})}});const re={},pe={};return W.forEach(se=>{var z;const he=J(se);if(he&&a.ignoreBuiltInBaseEntities&&(ki.includes(se.type)||(a.allBuiltInEntityIds||[]).includes(he)))return;const X=se.version;if(he){const ce=((z=a.entityMaps)==null?void 0:z.get(he))||he;re[ce]=X}}),ne.forEach(se=>{var z;const he=J(se);if(he&&a.ignoreBuiltInBaseEntities&&(ki.includes(se.type)||(a.allBuiltInEntityIds||[]).includes(he)))return;const X=se.version;if(he){const ce=((z=a.entityMaps)==null?void 0:z.get(he))||he;pe[ce]=X}}),{upstream:re,downstream:pe}}function M0e(d,u){const i=[];if(ws.includes(d.type)){ys(d).forEach(p=>{const t=qy(p,u);t&&i.push(t)});const l=[...d.inputs||[],...d.outputs||[]].map(p=>{const t=Vp(p,u);return t?w6(t,u):null}).filter(p=>p!==null);i.push(...R(l))}if(st.includes(d.type)){const a=Wy(d);a&&i.push(a)}return R(i)}function Qa(d){const u=[];if(ws.includes(d.type)){d.calledBy.forEach(l=>{const p=rr(l);p&&u.push(p)});const a=[...d.inputs||[],...d.outputs||[]].map(l=>Wy(l)).filter(l=>l!==null);u.push(...R(a))}if(st.includes(d.type)){const i=Wy(d);i&&u.push(i)}return R(u)}function ys(d){return[...d.calledByEntry||[],...d.calledByError||[],...d.calledBySuccess||[]].filter(u=>u.type!==f.GenericReference)}function WF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ActionDescriptor)throw new Error("Entity must be an action descriptor to be flattened");return[d,...d.inputs.flatMap(a=>ye(a,u,i)),...d.outputs.flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function HF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ArgumentDeclaration)throw new Error("Entity must be an argument declaration to be flattened");return[d,...d.defaultValue?ye(d.defaultValue,u):[],...d.writesValues.flatMap(a=>ye(a,u,i)),...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function YF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.BreakStatement)throw new Error("Entity must be a break statement to be flattened");return[d,...d.outputs.flatMap(a=>ye(a,u,i)),...d.throws?ye(d.throws,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function zF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.BuiltInBaseEntity)throw new Error("Entity must be a built-in base entity to be flattened");return[d,...(d.properties||[]).flatMap(a=>ye(a,u,i)),...(d.methods||[]).flatMap(a=>ye(a,u,i)),...(d.abstractMethods||[]).flatMap(a=>ye(a,u,i)),...(d.extends||[]).flatMap(a=>ye(a,u,i))]}function XF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Condition)throw new Error("Entity must be a condition to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function QF(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ContinueStatement)throw new Error("Entity must be a continue statement to be flattened");return[d,...d.outputs.flatMap(a=>ye(a,u,i)),...d.throws?ye(d.throws,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function e6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.DefinitionEntity)throw new Error("Entity must be a definition entity to be flattened");return[d,...(d.extends||[]).flatMap(a=>ye(a,u,i)),...(d.implements||[]).flatMap(a=>ye(a,u,i)),...(d.properties||[]).flatMap(a=>ye(a,u,i)),...(d.methods||[]).flatMap(a=>ye(a,u,i)),...(d.abstractMethods||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function t6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.DataType)throw new Error("Entity must be a data type to be flattened");return[d,...(d.andChildrenGroup||[]).flatMap(a=>ye(a,u,i)),...(d.orChildrenGroup||[]).flatMap(a=>ye(a,u,i)),...d.entity?ye(d.entity,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function r6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.FunctionCall)throw new Error("Entity must be a function call to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function i6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.FunctionDeclaration)throw new Error("Entity must be a function declaration to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.calls||[]).flatMap(a=>ye(a,u,i)),...d.implements?ye(d.implements,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function s6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.GlobalEvent)throw new Error("Entity must be a global event to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.calls||[]).flatMap(a=>ye(a,u,i)),...d.implements?ye(d.implements,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function n6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.InputMap)throw new Error("Entity must be an input map to be flattened");return[d,...d.readsValue?ye(d.readsValue,u,i):[],...d.declaration?ye(d.declaration,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function a6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.InstalledProject)throw new Error("Entity must be an installed project to be flattened");return[d,...(d.functions||[]).flatMap(a=>ye(a,u,i)),...(d.events||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function o6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.InternalCall)throw new Error("Entity must be an internal call to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function l6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.LiteralValue)throw new Error("Entity must be a literal value to be flattened");return[d,...d.valueAsTypeSingle?ye(d.valueAsTypeSingle,u,i):[],...d.valueAsTypeList&&Array.isArray(d.valueAsTypeList)?d.valueAsTypeList.flatMap(a=>ye(a,u,i)):[],...d.parent?ye(d.parent,u,i):[]]}function d6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Loop)throw new Error("Entity must be a loop to be flattened");return[d,...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...d.body?ye(d.body,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function u6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Operation)throw new Error("Entity must be an operation to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...d.process?ye(d.process,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function c6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.OutputMap)throw new Error("Entity must be an output map to be flattened");return[d,...(d.writesValues||[]).flatMap(a=>ye(a,u,i)),...d.declaration?ye(d.declaration,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function p6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.PrimitiveEntity)throw new Error("Entity must be a primitive entity to be flattened");return[d,...(d.properties||[]).flatMap(a=>ye(a,u,i)),...(d.methods||[]).flatMap(a=>ye(a,u,i)),...(d.abstractMethods||[]).flatMap(a=>ye(a,u,i))]}function f6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Project)throw new Error("Entity must be a project to be flattened");return[d,...(d.entities||[]).flatMap(a=>ye(a,u,i)),...(d.functions||[]).flatMap(a=>ye(a,u,i)),...(d.events||[]).flatMap(a=>ye(a,u,i)),...(d.projects||[]).flatMap(a=>ye(a,u,i)),...(d.variableDeclarations||[]).flatMap(a=>ye(a,u,i)),...(d.variableInstances||[]).flatMap(a=>ye(a,u,i)),...(d.operations||[]).flatMap(a=>ye(a,u,i)),...(d.conditions||[]).flatMap(a=>ye(a,u,i)),...(d.functionCalls||[]).flatMap(a=>ye(a,u,i)),...(d.projects||[]).flatMap(a=>ye(a,u,i)),...(d.loops||[]).flatMap(a=>ye(a,u,i)),...(d.searches||[]).flatMap(a=>ye(a,u,i))]}function h6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Property)throw new Error("Entity must be a property to be flattened");return[d,...d.defaultValue?ye(d.defaultValue,u,i):[],...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function y6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ReturnDeclaration)throw new Error("Entity must be a return declaration to be flattened");return[d,...d.readsValue?ye(d.readsValue,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function m6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ReturnStatement)throw new Error("Entity must be a return statement to be flattened");return[d,...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.throws?ye(d.throws,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function v6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.Search)throw new Error("Entity must be a search to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputsDeclarations||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputsDeclarations||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...d.error?ye(d.error,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.parent?ye(d.parent,u,i):[]]}function E6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.ValueDescriptor)throw new Error("Entity must be a value descriptor to be flattened");return[d,...d.defaultValue?ye(d.defaultValue,u,i):[],...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function T6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.VariableDeclaration)throw new Error("Entity must be a variable declaration to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(d.internalCalls||[]).flatMap(a=>ye(a,u,i)),...(d.writesValues||[]).flatMap(a=>ye(a,u,i)),...d.readsValue?ye(d.readsValue,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.dataType?ye(d.dataType,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function b6(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(u.has(d.id))return[];if(u.add(d.id),d.type!==f.VariableInstance)throw new Error("Entity must be a variable instance to be flattened");return[d,...(d.successCalls||[]).flatMap(a=>ye(a,u,i)),...(d.errorCalls||[]).flatMap(a=>ye(a,u,i)),...(d.inputs||[]).flatMap(a=>ye(a,u,i)),...(d.outputs||[]).flatMap(a=>ye(a,u,i)),...(d.internalCalls||[]).flatMap(a=>ye(a,u,i)),...(d.writesValues||[]).flatMap(a=>ye(a,u,i)),...d.readsValue?ye(d.readsValue,u,i):[],...d.defaultValue?ye(d.defaultValue,u,i):[],...(ys(d)||[]).flatMap(a=>ye(a,u,i)),...d.declaration?ye(d.declaration,u,i):[],...d.parent?ye(d.parent,u,i):[]]}function Vs(){const d=new Set,u=QN.flatMap(i=>ye(i,d)).map(i=>i.id);if(!u.includes("http-request-error-return-delaration-id"))throw new Error("Built-in base entities must be included in the list");return u}function ye(d,u=new Set,i={ignoreBuiltInBaseEntities:!1}){if(!d)throw new Error("Entity must be defined to be flattened");if(d.type===f.GenericReference)return[];if(i.ignoreBuiltInBaseEntities&&(ki.includes(d.type)||Vs().includes(d.id)))return[];if(u.has(d.id))return[];switch(d.type){case f.FunctionCall:return r6(d,u,i);case f.Operation:return u6(d,u,i);case f.Condition:return XF(d,u,i);case f.Loop:return d6(d,u,i);case f.Search:return v6(d,u,i);case f.GlobalEvent:return s6(d,u,i);case f.ReturnStatement:return m6(d,u,i);case f.ContinueStatement:return QF(d,u,i);case f.BreakStatement:return YF(d,u,i);case f.VariableDeclaration:return T6(d,u,i);case f.DefinitionEntity:return e6(d,u,i);case f.FunctionDeclaration:return i6(d,u,i);case f.Project:return f6(d,u,i);case f.ActionDescriptor:return WF(d,u,i);case f.ArgumentDeclaration:return HF(d,u,i);case f.ReturnDeclaration:return y6(d,u,i);case f.ValueDescriptor:return E6(d,u,i);case f.InputMap:return n6(d,u,i);case f.OutputMap:return c6(d,u,i);case f.DataType:return t6(d,u,i);case f.InstalledProject:return a6(d,u,i);case f.InternalCall:return o6(d,u,i);case f.LiteralValue:return l6(d,u,i);case f.Property:return h6(d,u,i);case f.VariableInstance:return b6(d,u,i);case f.BuiltInBaseEntity:return i.ignoreBuiltInBaseEntities?[]:zF(d,u,i);case f.PrimitiveEntity:return i.ignoreBuiltInBaseEntities?[]:p6(d,u,i)}return[]}function VA(d){return d.type===f.FunctionCall||d.type===f.InternalCall||[f.Operation,f.Condition,f.Loop].includes(d.type)?d.declaration.inputs:d.type===f.FunctionDeclaration||Pl.includes(d.type)?d.inputs:d.type===f.Search?d.inputsDeclarations:[]}function U0e(d,u){return u.type===f.Condition?u.inputs.find(i=>i.declaration.id===d.id):u.type===f.FunctionCall||u.type===f.Operation?u.inputs.find(i=>i.declaration.id===d.id):null}function A6(d){return er.includes(d.type)?d.inputs:[]}function I6(d){var u;return d.type===f.FunctionCall?((u=d.declaration.returnStatements[0])==null?void 0:u.outputs)||[]:[f.Operation,f.Condition,f.Loop].includes(d.type)?d.declaration.outputs:d.type===f.Search?d.outputsDeclarations:nr.includes(d.type)?d.outputs:[]}function j0e(d,u){return u.type===f.Condition?null:u.type===f.FunctionCall||u.type===f.Operation?u.outputs.find(i=>i.declaration.id===d.id):null}function x0e(d){return d.type===f.Condition?[]:er.includes(d.type)?d.outputs:[]}function Wy(d){const u=d.readsValue;return u?rr(u):null}function w6(d,u){const i=d.readsValue;return i?qy(i,u):null}function R6(d){const u=d.internalCalls||[];return R(ci(R(u.flatMap(i=>[...i.successCalls,...i.errorCalls]))))}function Pd(d){const u=PA(d),i=[];return u.forEach(a=>{if(st.includes(a.type))i.push(a);else if(Wn.includes(a.type)){const l=a.parent;i.push(l)}}),i}function R(d){const u=new Set;return d.filter(i=>!i||u.has(i.id)?!1:(u.add(i.id),!0))}function sn(d,u=!1){const i=[];if(d.type===f.Project&&i.push(...(d==null?void 0:d.entities)||[],...(d==null?void 0:d.functions)||[],...(d==null?void 0:d.variableDeclarations)||[],...(d==null?void 0:d.variableInstances)||[],...(d==null?void 0:d.searches)||[],...(d==null?void 0:d.loops)||[],...(d==null?void 0:d.operations)||[],...(d==null?void 0:d.conditions)||[],...(d==null?void 0:d.functionCalls)||[],...(d==null?void 0:d.events)||[],...(d==null?void 0:d.projects)||[]),wr.includes(d.type)&&i.push(...(d==null?void 0:d.detachedChildren)||[]),d.type===f.DefinitionEntity){const a=[...d.suggestedMethods,...d.methods].flatMap(l=>l.collapsed&&u?[]:sn(l));i.push(...a)}if(d.type===f.Condition){const a=d.successCalls.map(p=>rr(p)),l=d.errorCalls.map(p=>rr(p));i.push(...a,...l)}if(Pl.includes(d.type)){if(d.collapsed&&u)return[];const a=d.inputs.map(p=>Pd(p)).flat(),l=d.calls.map(p=>rr(p));i.push(...R(a),...l)}if(er.includes(d.type)&&d.type!==f.Condition&&d.type!==f.Loop){const a=d==null?void 0:d.outputs.map(t=>Pd(t)).flat(),l=d.successCalls.map(t=>rr(t)),p=d.errorCalls.map(t=>rr(t));i.push(...R(a),...l,...p)}if(st.includes(d.type)){const a=Pd(d),l=R6(d);i.push(...a,...l)}if(d.type===f.Loop){const a=d.outputs.map(t=>Pd(t)).flat();if(d.body){const t=sn(d.body,u);i.push(...t)}const l=d.errorCalls.map(t=>rr(t)),p=d.successCalls.map(t=>rr(t));i.push(...R(a),...p,...l)}if(d.type===f.FunctionDeclaration){if(d.collapsed&&u)return[];const a=d.inputs.map(p=>Pd(p)).flat(),l=d.calls.map(p=>rr(p));i.push(...R(a),...l)}return R(i)}function Hy(d,u=!1){const i=sn(d,u),a=[...i,...i.reduce((l,p)=>[...l,...Hy(p,u)],[])];return R(a)}function g6(d){const u=Qa(d),i=[...u,...u.reduce((a,l)=>[...a,...g6(l)],[])];return R(i)}function Np(d){return d.implements.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,f.DefinitionEntity,...Np(i),...Lp(i)]:[...u,i.name],[])}function Lp(d){return d.extends.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,f.DefinitionEntity,...Lp(i),...Np(i)]:[...u,i.name],[])}function NA(d){return d.extends.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,i,...NA(i),...LA(i)]:[...u,i],[])}function LA(d){return d.implements.reduce((u,i)=>i.type===f.DefinitionEntity?[...u,i,...LA(i),...NA(i)]:[...u,i],[])}function Vd(d){return[...Lp(d),...Np(d)].filter((i,a,l)=>l.indexOf(i)===a)}function BA(d){return d.implements.length===0&&d.extends.length===0?null:d.implements.find(a=>a.type===f.BuiltInBaseEntity&&a.name===Ce.PERSISTED_ENTITY)?d:[...d.implements,...d.extends].reduce((a,l)=>{if(l.type===f.DefinitionEntity){const p=BA(l);if(p)return p}return a},null)}function F0e(d){const u=d.extends.find(i=>i.type===f.BuiltInBaseEntity);return u&&u.type===f.BuiltInBaseEntity?u:null}function G0e(d){const u=d.implements.find(i=>i.type===f.BuiltInBaseEntity);return u&&u.type===f.BuiltInBaseEntity?u:null}function Yy(d){const u=d.extends.find(i=>i.type===f.DefinitionEntity);return u&&u.type===f.DefinitionEntity?u:null}function Ii(d){if(d.type===f.BuiltInBaseEntity)return[d];const u=[...d.implements,...d.extends].reduce((i,a)=>a.type===f.BuiltInBaseEntity?[...i,a]:a.type===f.DefinitionEntity?[...i,...Ii(a)]:i,[]);return R(u)}function Bp(d){return d.type===f.PrimitiveEntity?!0:d.type===f.BuiltInBaseEntity?d.interactive:!Ii(d).find(a=>!a.interactive)}function K0e(d){return d.parent===d.project&&d.project.variableDeclarations.includes(d)}function MA(d){return d.parent!==d.project?!1:f.VariableDeclaration===d.type?d.project.variableDeclarations.includes(d):f.VariableInstance===d.type?d.project.variableInstances.includes(d):f.FunctionCall===d.type?d.project.functionCalls.includes(d):f.Condition===d.type?d.project.conditions.includes(d):f.Operation===d.type?d.project.operations.includes(d):f.Loop===d.type?d.project.loops.includes(d):f.Search===d.type?d.project.searches.includes(d):!1}function _6(d){if([...Ht,f.DefinitionEntity,f.InstalledProject,f.Project].includes(d.type)||MA(d))return!1;const u=Qa(d);return u.length===0?!0:u.some(i=>_6(i))}function UA(d){return[...Ht,f.DefinitionEntity,f.InstalledProject,f.Project].includes(d.type)||MA(d)?!1:Qa(d).length===0}function D6(d,u=0){if(UA(d)){const i=Qa(d);return i.length===0?d:i.map(l=>D6(l,u+1)).reduce((l,p)=>l?p&&p.x<l.x?p:l:p,null)}return null}function O6(d){const u=[];if(UA(d))u.push(d);else return[];return Qa(d).forEach(a=>{u.push(...O6(a))}),u}function jA(d){return d.type===f.FunctionDeclaration&&d.parent!==d.project&&!![f.DefinitionEntity,f.Loop,f.InstalledProject].includes(d.parent.type)}function k0e(d,u){const i=new Map;return d.forEach(a=>{i.set(a.id,a)}),u.forEach(a=>{i.set(a.id,a)}),Array.from(i.values())}function Mp(d){switch(d){case f.DefinitionEntity:return va;case f.FunctionDeclaration:return Ma;case f.VariableDeclaration:return Ka;case f.VariableInstance:return Ga;case f.FunctionCall:return Xa;case f.Operation:return Ua;case f.Condition:return Fa;case f.ReturnStatement:return ja;case f.Loop:return bi;case f.Search:return ka;case f.InputMap:return $s;case f.OutputMap:return Xs;case f.ArgumentDeclaration:return fa;case f.ReturnDeclaration:return Ni;case f.Property:return ca;case f.InstalledProject:return Sa;case f.Project:return P;case f.DataType:return Yi;case f.GlobalEvent:return xa;case f.InternalCall:return qa;case f.ValueDescriptor:return Qs;case f.BuiltInBaseEntity:return $n;case f.PrimitiveEntity:return Li;case f.ActionDescriptor:return dt;case f.LiteralValue:return Ti;case f.ContinueStatement:return ui;case f.BreakStatement:return Za;default:return null}}function wi(d,u,i=null){const a=d!=null&&d.parent?J(d==null?void 0:d.parent):null;let l=a?u.get(a):null,p=i||d;if((d==null?void 0:d.id)===(u==null?void 0:u.id))return u;if(d.type===f.ReturnStatement)return Lr(d,u,p);if(d.type===f.FunctionDeclaration&&(l==null?void 0:l.type)===f.Loop)return l;if(Ht.includes(d.type))return d;if(d.type===f.Loop)return p.id===d.id?l:d;if(ki.includes(d.type))return null;const t=d.parent;if(!t)return null;if(t.type===f.GenericReference){const y=J(t);if(!y)return null;const v=u.get(y);return v?wi(v,u,p):null}else return t===u?u:wi(t,u,p)}function Lr(d,u,i=null){const a=d!=null&&d.parent?J(d==null?void 0:d.parent):null;let l=a?u.get(a):null,p=i||d;if(d.type===f.FunctionDeclaration&&(l==null?void 0:l.type)===f.Loop)return Lr(l.parent,u,p);if(Ht.includes(d.type))return d;if(ki.includes(d.type))return null;const t=d.parent;if(!t)return null;if(t.type===f.GenericReference){const y=J(t);if(!y)return null;const v=u.get(y);return v?Lr(v,u,p):null}else return t===u?u:Lr(t,u,p)}function Up(d,u){if(ki.includes(d.type)||u.getBuiltIn(d.id))return null;const i=Ri(d.parent,u);return i?i===u?wr.includes(d.type)?d:null:i.type===f.DefinitionEntity?d:Up(i,u):null}function zy(d,u,i){if(d===u||u===i||d===i||!d||!u)return!1;const a=wi(u.parent,i);return a===i?!1:a===d?!0:zy(a,u,i)}var Xy=(d=>(d.SameBothLocal="same-both-local",d.AInB="a-in-b",d.BInA="b-in-a",d.ParallelInCommonParent="parallel-in-common-parent",d.ParallelInProject="parallel-in-project",d.AIsGlobalBIsNot="a-is-global-b-is-not",d.BIsGlobalAIsNot="b-is-global-a-is-not",d.SameBothGlobal="same-both-global",d))(Xy||{});function Ns(d,u,i){const a=wi(d,i),l=wi(u,i);if(!a)throw new Error("Could not find scope owner for the entity: "+d.id);if(!l)throw new Error("Could not find scope owner for the entity: "+u.id);if(a===l&&a.type!==f.Project)return{compatible:!0,type:"same-both-local",commonAncestorScope:a};if(a===l&&a.type===f.Project)return{compatible:!0,type:"same-both-global",commonAncestorScope:a};if(a.type===f.Project&&l.type!==f.Project)return{compatible:!1,type:"a-is-global-b-is-not",commonAncestorScope:a};if(a.type!==f.Project&&l.type===f.Project)return{compatible:!1,type:"b-is-global-a-is-not",commonAncestorScope:l};if(zy(a,l,i))return{compatible:!0,type:"b-in-a",commonAncestorScope:a};if(zy(l,a,i))return{compatible:!0,type:"a-in-b",commonAncestorScope:l};const y=$A(a,l);return y===i?{compatible:!1,type:"parallel-in-project",commonAncestorScope:y}:y?{compatible:!1,type:"parallel-in-common-parent",commonAncestorScope:wi(y,i)}:{compatible:!1,type:"parallel-in-project",commonAncestorScope:i}}function C6(d,u,i){const a=Ns(d,u,i);if(!a.compatible||a.type!=="same-both-local")return null;if(d===u)return d;let l=wi(d.parent,i);if(l){if(l===u)return u;if(l.type===f.Project)return d}else return d;for(;l;){if(l){if(l===u)return u;if(l.type===f.Project)return d}else return d;l=wi(l.parent,i)}let p=wi(u.parent,i);if(p){if(p===d)return d;if(p.type===f.Project)return u}else return u;for(;p;){if(p){if(p===d)return d;if(p.type===f.Project)return u}else return u;p=wi(p.parent,i)}return null}function $6(d){return d.length===0?null:d.length===1?d[0]:d.reduce((i,a)=>{const l=C6(i,a,a.project);return!l||l===a?i:a},d[0])}function Ri(d,u){if(!d)return null;let i;return typeof d=="string"?i=d:d.type===f.GenericReference?i=J(d):i=d.id,i===u.id?u:u.get(i)}function eo(d){if(!d)return null;if(ki.includes(d.type))return d;if(d.type===f.Project)return null;if(d.project.getBuiltIn(d.id))return d;const u=d.parent;return!u||u.type===f.Project?null:eo(u)}function jp(d){const u=[];function i(p,t){return u.some(y=>y.blockedByCaller===p&&y.blockedByCalling===t)}function a(p,t){i(p,t)||u.push({blockedByCaller:p,blockedByCalling:t})}const l=Up(d,d.project);return d.calledBySuccess.forEach(p=>{[...p.successCalls||[]].forEach(v=>{nr.includes(v.type)&&v!==d&&(pt(d).find(A=>A===v)||a(p,v))});let y;if(er.includes(p.type)&&(y=p),y){const v=jp(y);v.reachable||pt(d).find(A=>A===p)||v.blocks.forEach(A=>{a(p,A.blockedByCalling)})}}),d.calledByError.forEach(p=>{[...p.errorCalls||[]].forEach(v=>{nr.includes(v.type)&&v!==d&&(pt(d).find(A=>A===v)||a(p,v))});let y;if(er.includes(p.type)&&(y=p),y){const v=jp(y);v.reachable||pt(d).find(A=>A===p)||v.blocks.forEach(A=>{a(p,A.blockedByCalling)})}}),d.calledByEntry.forEach(p=>{if([...p.calls||[]].forEach(v=>{nr.includes(v.type)&&v!==d&&(pt(d).find(A=>A===v)||a(p,v))}),p===l)return;let y;if(p.type===f.FunctionDeclaration){const v=rr(p);if(v.type===f.DefinitionEntity)return;v.type===f.Loop&&(y=v)}if(y){const v=jp(y);v.reachable||v.blocks.forEach(T=>{a(p,T.blockedByCalling)})}}),{reachable:u.length===0,entryPoint:l,blocks:u}}function S0e(d){return Bf.includes(d.type)?d.type===f.FunctionDeclaration?!jA(d):!0:!1}function q0e(d){if(f.ActionDescriptor===d.type){if(d.project.operationDeclarations.find(p=>p.id===d.id))return f.Operation;if(d.project.globalEventActionDescriptors.find(p=>p.id===d.id))return f.GlobalEvent;if(d.project.loopDeclarations.find(p=>p.id===d.id))return f.Loop;if(d.project.conditionDeclarations.find(p=>p.id===d.id))return f.Condition}return d.type}function Qy(d,u){return d.type===f.BuiltInBaseEntity?d.name===u:!!Lp(d).includes(u)}function Z0e(d,u){return d.type===f.BuiltInBaseEntity?d.name===u:!!Np(d).includes(u)}function Qi(d,u){return d.type===f.BuiltInBaseEntity?d.name===u:!!Vd(d).includes(u)}function J0e(d){const u=[];return d.entities.forEach(i=>{if(Qy(i,Ce.PERSISTED_ENTITY)){u.push(i);return}}),R(u)}function W0e(d){const u=[];return d.entities.forEach(i=>{if(Qy(i,Ce.RELATIONAL_DATABASE)){u.push(i);return}}),R(u)}function H0e(d){return d.type!==f.DefinitionEntity||d.abstract||!Qy(d,Ce.PERSISTED_ENTITY)?null:(d==null?void 0:d.properties.find(i=>{var a;return((a=i.implements)==null?void 0:a.id)===ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.primaryKey.id&&!i.abstract}))||null}function P6(d){var a;const u=BA(d);if(!u)return null;const i=u.properties.find(l=>{var p;return((p=l.implements)==null?void 0:p.id)===ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.database.id});return i?(a=i.getDefaultValue())==null?void 0:a.valueAsType:null}function Nd(d){if(d.type!==f.DefinitionEntity)return[];if(d.abstract)return[];if(!Qi(d,Ce.PERSISTED_ENTITY))return[];const u=[],i=d.properties.filter(a=>{var l;return((l=a.implements)==null?void 0:l.id)!==ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.database.id&&!a.abstract});return u.push(...i),u}function Y0e(d){var i;if(!d||d.type!==f.DefinitionEntity||!Qi(d,Ce.PERSISTED_ENTITY))return null;const u=d.properties.find(a=>{var l;return((l=a.implements)==null?void 0:l.id)===ve[f.BuiltInBaseEntity][Ce.PERSISTED_ENTITY].properties.database.id});return(i=u==null?void 0:u.getDefaultValue())==null?void 0:i.valueAsTypeSingle}function gr(d,u){var a;if(!u1.includes(u.type)||!d)return u.project||null;let i=u.project;return d.type===f.Project?i=d:((a=u.project)==null?void 0:a.id)!==d.project.id&&(i=d.project),i}function z0e(d){switch(d){case f.Project:return P;case f.InstalledProject:return Sa;case f.DefinitionEntity:return va;case f.FunctionDeclaration:return Ma;case f.GlobalEvent:return xa;case f.VariableInstance:return Ga;case f.VariableDeclaration:return Ka;case f.InputMap:return $s;case f.OutputMap:return Xs;case f.Condition:return Fa;case f.Operation:return Ua;case f.FunctionCall:return Xa;case f.ReturnDeclaration:return Ni;case f.ArgumentDeclaration:return fa;case f.PrimitiveEntity:return Li;case f.DataType:return Yi;case f.Property:return ca;case f.ActionDescriptor:return dt;case f.ReturnStatement:return ja;case f.ContinueStatement:return ui;case f.BreakStatement:return Za;case f.Loop:return bi;case f.Search:return ka;case f.ValueDescriptor:return Qs;case f.InternalCall:return qa;case f.LiteralValue:return Ti}return null}function X0e(d){const u={added:{},updated:{},removed:{},affected:[],seenEntities:[],self:d==null?void 0:d.self};return d==null||d.added.forEach(i=>{u.added[i.id]=i}),d==null||d.updated.forEach(i=>{u.updated[i.id]=i}),d==null||d.removed.forEach(i=>{u.removed[i.id]=i}),u.affected=Array.from(new Set(d==null?void 0:d.affected.map(i=>i.id))),u}function Ar(d,u){const i=Mp(d.type);return i?!i.MUTABLE_META_PROPERTIES.every(l=>{const p=d[l],t=u[l];return t===void 0||p===t?!0:Array.isArray(p)&&Array.isArray(t)?p.length!==t.length?!1:p.every((y,v)=>y===t[v]):!1}):!1}function em(d,u={}){if(d.type===f.Project)return[];if(!d.parent)return[];const i=J(d.parent);if(!i)return[];const a=u[i];return a?[a.id,...em(a,u)]:[]}function Q0e(d){const u=[],i=new Set;return[...d.listAdded,...d.listUpdated,...d.listAffected].forEach(a=>{const l=rr(a);!l||i.has(l.id)||(i.add(l.id),u.push(l))}),R(u)}function eve(d){if(d.type===f.Condition)return null;if(d.type===f.Search)return d.project.getBuiltIn(ve["value-descriptor"][Vl.SearchErrorOutputDescriptor].id)||null;if(d.type===f.Operation)return d.declaration.error;if(d.type===f.FunctionCall){const i=d.declaration.returnStatements.find(a=>!!a.throws);return(i==null?void 0:i.throws)||null}return null}function V6(d){const u=d.entities.filter(l=>!!l.implements.find(p=>p.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.id)),i=u.find(l=>{const p=l.properties.find(v=>v.implements&&v.implements.id===ve["built-in-base-entity"].BUILT_IN_RELATIONAL_DATABASE_ENTITY.properties.default.id),t=p==null?void 0:p.getDefaultValue();return(t==null?void 0:t.value)===!0});return i||u[0]||null}function xA(d,u){const i=Array.from(new Set([...u.getAllBuiltInIds(),...Vs()]));return!!(i.includes(d.id)||!em(d,{...u.instances,...u.builtInInstances}).every(p=>!i.includes(p)))}function N6(d){if(!d)return null;if(d.type===f.Project)return d.id;const u=d.parent;return u?N6(u):d.id}function xp(d){if(d.declaration&&d.declaration.type===f.Property){if(d.declaration.interactive){if(d.declaration.implements&&!d.declaration.implements.interactive)return!1;if(d.declaration.extends&&!d.declaration.extends.interactive)return!1}else return!1;if(d.declaration.private){const u=rr(d),i=Up(u,d.project);if((i==null?void 0:i.type)===f.FunctionDeclaration&&(i==null?void 0:i.parent.type)===f.DefinitionEntity&&(i==null?void 0:i.parent.id)!==d.declaration.parent.id)return!1}}return!0}function FA(d){if(d.interactive){if(d.implements&&!d.implements.interactive)return!1;if(d.extends&&!d.extends.interactive)return!1}else return!1;if(d.private){const u=rr(d),i=Up(u,d.project);if((i==null?void 0:i.type)===f.FunctionDeclaration&&(i==null?void 0:i.parent.type)===f.DefinitionEntity&&(i==null?void 0:i.parent.id)!==d.parent.id)return!1}return!0}function tve(d,u,i){const a=u,l=i,p=!!i,t=[];return a.forEach(y=>{var v;if(p){const T=Ns(l,y,d);if(!T.compatible&&T.type!=="b-is-global-a-is-not")return;t.push(y)}else{if(((v=y.parent)==null?void 0:v.type)!==f.Project)return;t.push(y)}}),R(t)}function L6(d){const u=cpe(),i=d.toJSON();u.safeParse(i).success;const l=d.implements.flatMap(w=>rve(d,w)),p=d.extends.flatMap(w=>ive(d,w)),t=nve(d),y=sve(d);d.methods.flatMap(w=>w.validate());const v=[...l,...p,...t,...y,...U6(d)];return Qt(d.errors,v)}function B6(d,u){const i=u.properties.filter(p=>p.abstract),a=[];let l=[...d.properties];return i.forEach(p=>{const t=l.find(y=>{var v;return((v=y.implements)==null?void 0:v.id)===p.id});t?l=l.filter(y=>y.id!==t.id):a.push(p)}),a}function M6(d,u){const i=u.abstractMethods,a=[];let l=[...d.methods];return i.forEach(p=>{const t=l.find(y=>{var v;return((v=y.implements)==null?void 0:v.id)===p.id});t?l=l.filter(y=>y.id!==t.id):a.push(p)}),a}function rve(d,u){const i=[];if(!u.abstract){const w=He({id:d.id+"--"+oe.ImplementingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is implementing a non-abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.ImplementingNonAbstractEntity,entity:d});return i.push(w.error),i}const a=u.properties.filter(w=>w.abstract),l=[];let p=[...d.properties];a.forEach(w=>{const A=p.find(V=>{var N;return((N=V.implements)==null?void 0:N.id)===w.id});A?p=p.filter(V=>V.id!==A.id):l.push(w)}),l.length&&l.forEach(w=>{const A=He({id:d.id+"--"+oe.MissingPropertyImplementation+"--"+w.id,message:`Property "${w.name}" with id "${w.id}" of entity "${u.name}" with id "${u.id}" is not implemented when entity "${d.name}" with id "${d.id}" implements it`,issue:null,severity:Z.Error,code:oe.MissingPropertyImplementation,entity:d});i.push(A.error)});const t=[];let y=[...d.methods];u.abstractMethods.forEach(w=>{const A=y.find(V=>{var N;return((N=V.implements)==null?void 0:N.id)===w.id});A?y=y.filter(V=>V.id!==A.id):t.push(w)}),t.length&&t.forEach(w=>{const A=He({id:d.id+"--"+oe.MissingMethodImplementation+"--"+w.id,message:`Method "${w.name}" with id "${w.id}" of entity "${u.name}" with id "${u.id}" is not implemented when entity "${d.name}" with id "${d.id}" implements it`,issue:null,severity:Z.Error,code:oe.MissingMethodImplementation,entity:d});i.push(A.error)});const v=[];u.properties.forEach(w=>{const A=p.find(V=>V.name===w.name);A&&v.push([A,w])}),v.length&&v.forEach(([w])=>{const A=He({id:d.id+"--"+ae.PropertyOverwritesOtherSiblingWithSameName+"--"+w.id,message:`Property "${w.name}" with id "${w.id}" of entity "${d.name}" with id "${d.id}" overwrites the property with the same name from the base entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.PropertyOverwritesOtherSiblingWithSameName,entity:d});i.push(A.error)});const T=[];return u.methods.forEach(w=>{const A=y.find(V=>V.name===w.name);A&&T.push([A,w])}),T.length&&T.forEach(([w])=>{const A=He({id:d.id+"--"+ae.MethodOverwritesOtherSiblingWithSameName+"--"+w.id,message:`Method "${w.name}" with id "${w.id}" of entity "${d.name}" with id "${d.id}" overwrites the method with the same name from the base entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.MethodOverwritesOtherSiblingWithSameName,entity:d});i.push(A.error)}),i}function ive(d,u){const i=[],a=[];if(!d.abstract&&u.abstract){const p=He({id:d.id+"--"+u.id+"--"+oe.NonAbstractExtendingAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is not-abstract but is extending an abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonAbstractExtendingAbstractEntity,entity:d,firstRelationship:u});return i.push(p.error),i}if(d.abstract&&!u.abstract){const p=He({id:d.id+"--"+u.id+"--"+oe.AbstractExtendingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is abstract but is extending an non-abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.AbstractExtendingNonAbstractEntity,entity:d,firstRelationship:u});return i.push(p.error),i}d.properties.forEach(p=>{var y;const t=u.properties.find(v=>{var T;return v.name===p.name&&((T=p.extends)==null?void 0:T.id)!==v.id});((y=p.implements)==null?void 0:y.id)!==(t==null?void 0:t.id)&&t&&a.push(p)}),a.length&&a.forEach(p=>{const t=He({id:d.id+"--"+ae.PropertyOverwritesOtherSiblingWithSameName,message:`Property "${p.name}" with id "${p.id}" of entity "${d.name}" with id "${d.id}" overwrites the property with the same name from the extended entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.PropertyOverwritesOtherSiblingWithSameName,entity:d});i.push(t.error)});const l=[];return d.methods.forEach(p=>{var y;const t=u.methods.find(v=>{var T;return v.name===p.name&&((T=p.extends)==null?void 0:T.id)!==v.id});((y=p.implements)==null?void 0:y.id)!==(t==null?void 0:t.id)&&t&&l.push(p)}),l.length&&l.forEach(p=>{const t=He({id:d.id+"--"+ae.MethodOverwritesOtherSiblingWithSameName,message:`Method "${p.name}" with id "${p.id}" of entity "${d.name}" with id "${d.id}" overwrites the method with the same name from the extended entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:ae.MethodOverwritesOtherSiblingWithSameName,entity:d});i.push(t.error)}),i}function sve(d){const u=[];if(!d.properties.length){const i=He({id:d.id+"--"+oe.NoProperties,message:"No properties implemented",issue:null,severity:Z.Warning,code:oe.NoProperties,entity:d});u.push(i.error)}return d.properties.forEach(i=>{i.validate()}),u}function nve(d){const u=[];if(d.abstract){if(d.methods.length){const i=He({id:d.id+"--"+oe.AbstractEntityWithNonAbstractMethods,message:`Entity "${d.name}" with id "${d.id}" is marked as abstract but has non-abstract methods`,issue:null,severity:Z.Error,code:oe.AbstractEntityWithNonAbstractMethods,entity:d});u.push(i.error)}if(d.properties.some(i=>!i.abstract)){const i=He({id:d.id+"--"+oe.AbstractEntityWithNonAbstractProperties,message:`Entity "${d.name}" with id "${d.id}" is marked as abstract but has non-abstract properties`,issue:null,severity:Z.Error,code:oe.AbstractEntityWithNonAbstractProperties,entity:d});u.push(i.error),d.properties.forEach(a=>{if(!a.abstract){const l=He({id:d.id+"--"+oe.StaticEntityWithNonStaticProperties+"--"+a.id,message:`Property "${a.name}" with id "${a.id}" of entity "${d.name}" with id "${d.id}" is not marked as abstract but the entity is marked as abstract`,issue:null,severity:Z.Error,code:oe.StaticEntityWithNonStaticProperties,entity:d});u.push(l.error)}})}}else{if(d.abstractMethods.length){const i=He({id:d.id+"--"+oe.AbstractPropertyInNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is not marked as abstract but has abstract methods`,issue:null,severity:Z.Error,code:oe.AbstractPropertyInNonAbstractEntity,entity:d});u.push(i.error)}d.properties.some(i=>i.abstract)&&d.properties.forEach(i=>{if(i.abstract){const a=He({id:d.id+"--"+oe.AbstractPropertyInNonAbstractEntity+"--"+i.id,message:`Property "${i.name}" with id "${i.id}" of entity "${d.name}" with id "${d.id}" is marked as abstract but the entity is not marked as abstract`,issue:null,severity:Z.Error,code:oe.AbstractPropertyInNonAbstractEntity,entity:d,firstRelationship:i});u.push(a.error)}})}return d.static&&d.properties.some(i=>!i.static)&&d.properties.forEach(i=>{if(!i.static){const a=He({id:d.id+"--"+oe.NonStaticPropertyInStaticEntity+"--"+i.id,message:`Property "${i.name}" with id "${i.id}" of entity "${d.name}" with id "${d.id}" is not marked as static but the entity is marked as static`,issue:null,severity:Z.Error,code:oe.NonStaticPropertyInStaticEntity,entity:d,firstRelationship:i});u.push(a.error)}}),u}function ave(d,u){const i=[],a=Ii(u);if(!u.abstract){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.ImplementingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is implementing a non-abstract built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.ImplementingNonAbstractEntity,entity:d,firstRelationship:u});i.push(t)}const l=d.implements.filter(t=>t.id!==u.id);if(d.abstract){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.AbstractEntityImplements,message:`Entity "${d.name}" with id "${d.id}" is marked as abstract and cannot implement built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.AbstractEntityImplements,entity:d,firstRelationship:u});i.push(t)}if(d.static&&!u.static){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.StaticImplementingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is marked as static and cannot implement non-static built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.StaticImplementingNonStaticEntity,entity:d,firstRelationship:u});i.push(t)}if(!d.static&&u.static){const t=new Zt({id:d.id+"--"+u.id+"--"+oe.NonStaticImplementingStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is not marked as static and cannot implement static built-in entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonStaticImplementingStaticEntity,entity:d,firstRelationship:u});i.push(t)}return l.length&&l.forEach(t=>{if(t.type===f.BuiltInBaseEntity){const y=a.filter(v=>v.id!==t.id);y.length&&y.forEach(v=>{if(v.id!==t.id){const T=new Zt({id:d.id+"--"+v.id+"--"+t.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${v.name}" with id "${v.id}" but also implements entity "${t.name}" with id "${t.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:v,secondRelationship:t});i.push(T)}})}else{Ii(t).forEach(w=>{const A=a.filter(V=>V.id!==w.id);A.length&&A.forEach(V=>{if(V.id!==w.id){const N=new Zt({id:d.id+"--"+V.id+"--"+w.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${V.name}" with id "${V.id}" but also implements entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:V,secondRelationship:w});i.push(N)}})});const v=ma(u.ownDeclaredProperties,t.ownDeclaredProperties,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameImplementation,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameName);i.push(...v.errors);const T=ma(u.abstractMethods,[...t.abstractMethods,...t.methods],ae.MethodOverwritesOtherImplementedEntitysMethodWithSameImplementation,ae.MethodOverwritesOtherImplementedEntitysMethodWithSameName);i.push(...T.errors)}}),R(d.extends.flatMap(t=>Ii(t))).forEach(t=>{if(!a.find(y=>y.id===t.id)){const y=new Zt({id:d.id+"--"+u.id+"--"+t.id+"--"+oe.ExtendsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${u.name}" with id "${u.id}" but also extends entity "${t.name}" with id "${t.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ExtendsIncompatibleEntities,entity:d,firstRelationship:u,secondRelationship:t});i.push(y)}}),i}function ove(d,u,i=!1){const a=[],l=Ii(u);if(!d.abstract&&u.abstract){const w=He({id:d.id+"--"+u.id+"--"+oe.NonAbstractExtendingAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is not-abstract but is extending an abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonAbstractExtendingAbstractEntity,entity:d,firstRelationship:u});a.push(w.error)}if(d.abstract&&!u.abstract){const w=He({id:d.id+"--"+u.id+"--"+oe.AbstractExtendingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is abstract but is extending an non-abstract entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.AbstractExtendingNonAbstractEntity,entity:d,firstRelationship:u});a.push(w.error)}if(!d.static&&u.static){const w=He({id:d.id+"--"+u.id+"--"+oe.NonStaticExtendingStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is not static but is extending a static entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.NonStaticExtendingStaticEntity,entity:d,firstRelationship:u});a.push(w.error)}if(d.static&&!u.static){const w=He({id:d.id+"--"+u.id+"--"+oe.StaticExtendingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is static but is extending an non-static entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.StaticExtendingNonStaticEntity,entity:d,firstRelationship:u});a.push(w.error)}if(!Bp(u)){const w=He({id:d.id+"--"+u.id+"--"+oe.ExtendingNonInteractiveEntity,message:`Entity "${d.name}" with id "${d.id}" is extending an non-interactive entity "${u.name}" with id "${u.id}"`,issue:null,severity:Z.Error,code:oe.ExtendingNonInteractiveEntity,entity:d,firstRelationship:u});a.push(w.error)}const t=d.extends.filter(w=>w.id!==u.id);t.length&&t.forEach(w=>{if(w.type===f.BuiltInBaseEntity){const A=l.filter(V=>V.id!==w.id);A.length&&A.forEach(V=>{if(V.id!==w.id){const N=He({id:d.id+"--"+V.id+"--"+w.id+"--"+oe.ExtendsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is extending built-in entity "${V.name}" with id "${V.id}" but also extends entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ExtendsIncompatibleEntities,entity:d,firstRelationship:V,secondRelationship:w});a.push(N.error)}})}else{Ii(w).forEach(W=>{const ne=l.filter(re=>re.id!==W.id);ne.length&&ne.forEach(re=>{if(re.id!==W.id){const pe=new Zt({id:d.id+"--"+re.id+"--"+W.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is extending built-in entity "${re.name}" with id "${re.id}" but also extends or implements entity "${W.name}" with id "${W.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:re,secondRelationship:W});a.push(pe)}})});const V=!!Ii(w).find(W=>W.id===u.id);let N=[...w.properties];V&&(N=N.filter(W=>!u.properties.find(ne=>{var re;return ne.id===W.id||ne.name===W.name||ne.id===((re=W.implements)==null?void 0:re.id)})));let j=[...w.methods];V&&(j=j.filter(W=>!u.methods.find(ne=>{var re;return ne.id===W.id||ne.name===W.name||ne.id===((re=W.implements)==null?void 0:re.id)})));const k=ma(u.ownDeclaredProperties,N,ae.PropertyOverwritesOtherExtendedEntitysPropertyWithSameImplementation,ae.PropertyOverwritesOtherExtendedEntitysPropertyWithSameName);a.push(...k.errors);const S=ma(u.abstractMethods,j,ae.MethodOverwritesOtherExtendedEntitysMethodWithSameImplementation,ae.MethodOverwritesOtherExtendedEntitysMethodWithSameName);a.push(...S.errors)}}),i&&console.log("self.implements.length",d.implements.length),d.implements.length&&d.implements.forEach(w=>{if(w.type===f.BuiltInBaseEntity){const A=l.filter(V=>V.id!==w.id);A.length&&A.forEach(V=>{if(V.id!==w.id){const N=new Zt({id:d.id+"--"+V.id+"--"+w.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${V.name}" with id "${V.id}" but also implements entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:V,secondRelationship:w});a.push(N)}})}else{Ii(w).forEach(j=>{const k=l.filter(S=>S.id!==j.id);k.length&&k.forEach(S=>{if(S.id!==j.id){const W=new Zt({id:d.id+"--"+S.id+"--"+j.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is implementing built-in entity "${S.name}" with id "${S.id}" but also implements entity "${j.name}" with id "${j.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:S,secondRelationship:j});a.push(W)}})});const V=ma(u.ownDeclaredProperties,w.ownDeclaredProperties,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameImplementation,ae.PropertyOverwritesOtherImplementedEntitysPropertyWithSameName);a.push(...V.errors);const N=ma(u.abstractMethods,[...w.abstractMethods,...w.methods],ae.MethodOverwritesOtherImplementedEntitysMethodWithSameImplementation,ae.MethodOverwritesOtherImplementedEntitysMethodWithSameName);a.push(...N.errors)}});const y=ma(d.ownDeclaredProperties,u.ownDeclaredProperties,ae.PropertyOverwritesOtherSiblingWithSameImplementation,ae.PropertyOverwritesOtherSiblingWithSameName);a.push(...y.errors);const v=ma(u.methods,u.abstractMethods,ae.MethodOverwritesOtherSiblingWithSameImplementation,ae.MethodOverwritesOtherSiblingWithSameName);return a.push(...v.errors),R(d.extends.flatMap(w=>Ii(w))).forEach(w=>{if(!l.find(A=>A.id===w.id)){const A=new Zt({id:d.id+"--"+u.id+"--"+w.id+"--"+oe.ImplementsIncompatibleEntities,message:`Entity "${d.name}" with id "${d.id}" is extending built-in entity "${u.name}" with id "${u.id}" but also extends entity "${w.name}" with id "${w.id}" which is incompatible`,issue:null,severity:Z.Error,code:oe.ImplementsIncompatibleEntities,entity:d,firstRelationship:u,secondRelationship:w});a.push(A)}}),a}function lve(d){const u=[];return d.implements.forEach(i=>{if(!i.static){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.StaticImplementingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is static but implements entity "${i.name}" with id "${i.id}" which is non-static`,issue:null,severity:Z.Error,code:oe.StaticImplementingNonStaticEntity,entity:d,firstRelationship:i});u.push(a)}}),d.extends.forEach(i=>{if(!i.static){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.StaticExtendingNonStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is static but extends entity "${i.name}" with id "${i.id}" which is non-static`,issue:null,severity:Z.Error,code:oe.StaticExtendingNonStaticEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function dve(d){const u=[];if(d.implements.length){const i=new Zt({id:d.id+"--"+oe.AbstractEntityImplements,message:`Entity "${d.name}" with id "${d.id}" cannot be marked as abstract because it implements other entities`,issue:null,severity:Z.Error,code:oe.AbstractEntityImplements,entity:d});u.push(i)}return d.extends.forEach(i=>{if(!i.abstract){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.AbstractExtendingNonAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is abstract but extends entity "${i.name}" with id "${i.id}" which is non-abstract`,issue:null,severity:Z.Error,code:oe.AbstractExtendingNonAbstractEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function uve(d){const u=[];return d.extends.forEach(i=>{if(i.static){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.NonStaticExtendingStaticEntity,message:`Entity "${d.name}" with id "${d.id}" is non-static but extends entity "${i.name}" with id "${i.id}" which is static`,issue:null,severity:Z.Error,code:oe.NonStaticExtendingStaticEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function cve(d){const u=[];return d.extends.forEach(i=>{if(i.abstract){const a=new Zt({id:d.id+"--"+i.id+"--"+oe.NonAbstractExtendingAbstractEntity,message:`Entity "${d.name}" with id "${d.id}" is non-abstract but extends entity "${i.name}" with id "${i.id}" which is abstract`,issue:null,severity:Z.Error,code:oe.NonAbstractExtendingAbstractEntity,entity:d,firstRelationship:i});u.push(a)}}),u}function U6(d){const u=[],i=d.name;if(!i){const V=He({id:`${d.id}--${ae.EmptyName}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" does not have a name. Entities of type ${d.type} must have valid names.`,issue:null,severity:Z.Error,code:ae.EmptyName,entity:d});return u.push(V.error),u}const l=[...d.project.functions,...d.project.entities.flatMap(V=>V.methods)].filter(V=>V.id!==d.id),p=i.trim(),t=!l.some(V=>V.name===i||V.name===p);if(!t){const V=He({id:`${d.id}--${ae.NameNotUniqueInScope}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" does not have a unique name. Entities of type ${d.type} must have valid names among all other entities of its type.`,issue:null,severity:Z.Error,code:ae.NameNotUniqueInScope,entity:d});u.push(V.error)}const y=Tr(i);if(!!l.some(V=>Tr(V.name)===y)&&t){const V=He({id:`${d.id}--${ae.NameAsResolvedCodeNameNotUniqueInScope}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" does not have a unique name once it is resolved as it will appear in code: "${y}". Entities of type ${d.type} must have valid names including their code name form.`,issue:null,severity:Z.Error,code:ae.NameAsResolvedCodeNameNotUniqueInScope,entity:d});u.push(V.error)}if(!/^[a-zA-Z_]/.test(i)){const V=He({id:`${d.id}--${ae.NameMustStartWithLetterOrUnderscore}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" has a name that does not start with a letter or underscore.`,issue:null,severity:Z.Error,code:ae.NameMustStartWithLetterOrUnderscore,entity:d});u.push(V.error)}const w=i.substring(1);if(!/^[a-zA-Z0-9_ ]*$/.test(w)){const V=He({id:`${d.id}--${ae.NameCanOnlyContainLettersNumbersUnderscoreAndSpaces}`,message:`Definition entity "${ie(d,d.project)}" with id "${d.id}" has a name that contains invalid characters. It can only contain letters, numbers, underscores and spaces.`,issue:null,severity:Z.Error,code:ae.NameCanOnlyContainLettersNumbersUnderscoreAndSpaces,entity:d});u.push(V.error)}return u}const pve=Object.freeze(Object.defineProperty({__proto__:null,getBaseMethodsNotImplemented:M6,getBasePropertiesNotImplemented:B6,validate:L6,validateCanBecomeAbstract:dve,validateCanBecomeNonAbstract:cve,validateCanBecomeNonStatic:uve,validateCanBecomeStatic:lve,validateCanExtendEntity:ove,validateCanImplementEntity:ave,validateDefinitionEntityName:U6},Symbol.toStringTag,{value:"Module"}));function fve(d,u){const i=[];if(d.parent)if(d.id===d.parent)i.push(new ee({id:`${d.id}--${d.parent}--${q.SelfReference}`,code:q.SelfReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has a reference to itself at 'parent'. This is not allowed. Change the reference string or the 'entityId' property of the reference object.`,issue:null}));else{const a=u.get(d.parent);a?[f.Project,f.DataType].includes(a.type)||i.push(new ee({id:`${d.id}--${d.parent}--${q.InvalidParentReference}`,code:q.InvalidParentReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has a parent reference that isn't pointing to an entity of type 'project' or 'data-type'.`,issue:null})):i.push(new ee({id:`${d.id}--${d.parent}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", is referencing an entity with id "${d.parent}" that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,issue:null}))}return d.implements&&Array.isArray(d.implements)?d.implements.forEach(a=>{if(d.id===a){i.push(new ee({id:`${d.id}--${a}--${q.SelfReference}`,code:q.SelfReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has a reference to itself at one of the 'implements' references. This is not allowed. Change the reference string or the 'entityId' property of the reference object.`,issue:null}));return}const l=u.get(a);l?[f.DefinitionEntity,f.BuiltInBaseEntity].includes(l.type)?l.abstract||i.push(new ee({id:`${d.id}--${a}--${q.InvalidImplementsReference}`,code:q.InvalidImplementsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'implements' reference that isn't pointing to an abstract entity.`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.InvalidImplementsReference}`,code:q.InvalidImplementsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'implements' reference that isn't pointing to an entity of type 'definition-entity' or 'built-in-base-entity'.`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", is referencing an entity with id "${a}" that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,issue:null}))}):i.push(new ee({id:`${d.id}--${ae.InvalidObjectStructure}`,code:ae.InvalidObjectStructure,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'implements' property that isn't an array.`,issue:null})),d.extends&&Array.isArray(d.extends)&&d.extends.forEach(a=>{const l=u.get(a);l?[f.DefinitionEntity,f.BuiltInBaseEntity].includes(l.type)?l.abstract&&i.push(new ee({id:`${d.id}--${a}--${q.InvalidExtendsReference}`,code:q.InvalidExtendsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'extends' reference that isn't pointing to a non-abstract entity. Did you want to use the property 'implements', which holds a list of references to absract entities, instead?`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.InvalidExtendsReference}`,code:q.InvalidExtendsReference,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", has an 'extends' reference that isn't pointing to an entity of type 'definition-entity' or 'built-in-base-entity'.`,issue:null})):i.push(new ee({id:`${d.id}--${a}--${q.ReferencedEntityNotFound}`,code:q.ReferencedEntityNotFound,severity:Z.Error,message:`Entity of type "${d.type}" with id "${d.id}", is referencing an entity with id "${a}" that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,issue:null}))}),i}var tm=(d=>(d.Extends="extends",d.Implements="implements",d))(tm||{});const Vt=class Vt extends mr{constructor(i,a){super(i);D(this,"initialData");D(this,"id");D(this,"name");D(this,"codeName",null);D(this,"description",null);D(this,"x");D(this,"y");D(this,"static");D(this,"abstract");D(this,"type",f.DefinitionEntity);D(this,"properties",[]);D(this,"methods",[]);D(this,"abstractMethods",[]);D(this,"extends",[]);D(this,"implements",[]);D(this,"project");D(this,"errors",[]);D(this,"parent");D(this,"detachedDependents",{});D(this,"knownVersions",null);D(this,"activeVersion",!1);D(this,"initialized",!1);D(this,"startedInitialization",!1);D(this,"suggestedProperties",[]);D(this,"suggestedMethods",[]);this.initialData=i,this.project=a,this.id=i.id,this.name=i.name,this.description=i.description,this.x=i.x,this.y=i.y,this.codeName=i.codeName,this.static=i.static,this.abstract=i.abstract}static new(i=null){return{id:P.UUID.uuid(),version:P.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:(i==null?void 0:i.author)||P.sessionAuthor,previousVersion:null,deleted:!1,type:f.DefinitionEntity,name:"",codeName:null,description:"",static:!1,abstract:!1,properties:[],methods:[],abstractMethods:[],extends:[],implements:[],x:0,y:0,parent:null}}static fromGenerationTarget(i,a){let l=a;if(i.parent){const T=J(i.parent);l=a.get(T)}const p=[];i.implements&&i.implements.forEach(T=>{p.push(a.get(T)||a.getBuiltIn(T))});const t=[];i.extends&&i.extends.forEach(T=>{t.push(a.get(T)||a.getBuiltIn(T))});const y={id:i.id,version:P.UUID.uuid(),createdAt:L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:i.name,type:f.DefinitionEntity,codeName:i.codeName||null,description:i.description,static:i.static,abstract:i.abstract,properties:[],methods:[],abstractMethods:[],extends:t,implements:p,x:0,y:0,parent:l},v=te(y,a);return v.setParent(l,null),v}static validateGenerationTarget(i,a){let l=JSON.parse(JSON.stringify(i));const p=[],t=fve(l,a),y=ub(l,a);p.push(...t,...y,...br(l));const v=l.parent?a.get(l.parent):null;if(v&&v.type===f.DataType){const T=v;T.entity&&p.push(new ee({id:`${i.id}--${q.NewEntityWouldOverriteExisting}`,code:q.NewEntityWouldOverriteExisting,severity:Z.Error,message:`The entity of type '${i.type}' with id '${i.id}' can't be added to the 'parent' entity with id '${T.id}' because it already has an 'entity' child. Data type entities can only have one 'entity' as children.
|
|
401
401
|
You can inspect the existing 'entity' field with the 'describe_entity' action. Like so:
|
|
402
402
|
${On({describe_entity:T.entity.id})}
|
|
403
403
|
Alternatively you can update the parent data-type entity with 'update' action to remove the existing value of the field.`,issue:null}))}return{errors:p,modifiedData:l}}get interactive(){return this.implements.length?this.implements.every(i=>i.interactive):!0}get allMethods(){return R([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return R([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){return R([...this.extends.flatMap(i=>i.allMethods,[]),...this.implements.flatMap(i=>i.allMethods,[])])}get allBasePropertiesFromOriginalParents(){return R([...this.extends.flatMap(i=>i.allProperties,[]),...this.implements.flatMap(i=>i.allProperties,[])])}get allBasePropertiesFromExtendedAndImplementedEntities(){return R([...this.extends.reduce((i,a)=>[...[...a.ownDeclaredProperties,...a.allBasePropertiesFromExtendedAndImplementedEntities].filter(p=>!p.abstract),...i],[]),...this.implements.reduce((i,a)=>[...[...a.ownDeclaredProperties,...a.allBasePropertiesFromExtendedAndImplementedEntities].filter(p=>!p.abstract),...i],[])])}get allBaseMethodsFromExtendedAndImplementedEntities(){return R([...this.extends.reduce((i,a)=>a.type!==f.DefinitionEntity?[]:[...[...a.ownDeclaredMethods,...a.allBaseMethodsFromExtendedAndImplementedEntities].filter(p=>p.type!==f.ActionDescriptor),...i],[]),...this.implements.reduce((i,a)=>a.type!==f.DefinitionEntity?a.abstractMethods:[...[...a.ownDeclaredMethods,...a.allBaseMethodsFromExtendedAndImplementedEntities].filter(p=>p.type!==f.ActionDescriptor),...i],[])])}get extendedPropertiesFromOriginalParents(){return R(this.extends.reduce((i,a)=>{const l=[...a.ownDeclaredProperties,...a.extendedPropertiesFromOriginalParents].filter(p=>!p.abstract);return[...i,...l]},[]))}get implementedPropertiesFromOriginalParents(){return R([...this.extends.reduce((i,a)=>{const l=a.implementedPropertiesFromOriginalParents,p=[...a.ownDeclaredProperties].filter(t=>!!t.abstract&&!l.find(y=>y.name===t.name));return[...l,...p,...i]},[]),...this.implements.reduce((i,a)=>{const l=a.implementedPropertiesFromOriginalParents,p=[...a.ownDeclaredProperties].filter(t=>!!t.abstract&&!l.find(y=>y.name===t.name));return[...l,...p,...i]},[])].filter(i=>!!i.abstract))}get extendedMethodsFromOriginalParents(){return R(this.extends.reduce((i,a)=>{if(a.type!==f.DefinitionEntity)return[];const l=[...a.ownDeclaredMethods,...a.extendedMethodsFromOriginalParents].filter(p=>p.type!==f.ActionDescriptor);return[...i,...l]},[]))}get implementedMethodsFromOriginalParents(){return R([...this.extends.reduce((i,a)=>{const l=a.type===f.DefinitionEntity?a.methods:[],p=[...a.abstractMethods].filter(t=>!l.find(y=>y.name===t.name));return[...l,...p,...i]},[]),...this.implements.reduce((i,a)=>[...a.abstractMethods,...i],[])].filter(i=>i.type===f.ActionDescriptor))}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredProperties(){return this.properties.filter(i=>!i.isExtendedProperty)}get extendedMethods(){return this.methods.filter(i=>i.isExtendedMethod)}get ownDeclaredMethods(){return this.methods.filter(i=>!i.isExtendedMethod)}validateGeneratedUpdate(i){const a=[];return i.parent&&a.push(new ee({id:`${this.id}--${q.InvalidParentUpdate}`,code:q.InvalidParentUpdate,severity:Z.Error,message:`Entity of type '${this.type}' with id '${this.id}' cannot have the 'parent' property updated. The 'parent' on an '${this.type}', must be the root project as it is a globally declared entity.`,issue:null})),{errors:a,modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];return a==="implements"&&this.removeImplementation(i),a==="extends"&&this.removeExtension(i),{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];return a==="implements"&&this.addImplementation(i),a==="extends"&&this.addExtension(i),{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){return this.implements.forEach(i=>{ki.includes(i.type)||i.unsubscribeDependents([{entity:this,field:"implements"}])}),this}subscribeToDependencies(){return this.implements.forEach(i=>{ki.includes(i.type)||i.subscribeDependents([{entity:this,field:"implements"}])}),this.extends.forEach(i=>{ki.includes(i.type)||i.subscribeDependents([{entity:this,field:"extends"}])}),this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=P.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new Vt(this,this.project);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.properties=[...this.properties],i.methods=[...this.methods],i.abstractMethods=[...this.abstractMethods],i.extends=[...this.extends],i.implements=[...this.implements],i.parent=this.parent,this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];if(this.parent){this.parent.increaseVersion(i);const y=this.parent.recursiveCaptureUpstreamVersions(i);a.push(this.parent,...y.updated),l.push(...y.added),p.push(...y.removed)}return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new Vt(T,this.project)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.properties=y.properties,this.methods=y.methods,this.abstractMethods=y.abstractMethods,this.extends=y.extends,this.implements=y.implements,this.parent=y.parent,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){if(this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const l=J(i.parent),p=this.project.get(l),t=this.parent;if(t&&t.id!==(p==null?void 0:p.id)&&this.removeFromParent(a),p)this.setParent(p,a);else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${l}' that isn't found in the project`)}else throw a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);return i.extends.forEach(l=>{const p=J(l),t=this.project.get(p);t&&this.addExtension(t)}),i.implements.forEach(l=>{const p=J(l),t=this.project.get(p);t&&this.addImplementation(t)}),this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];if(this.initialData.parent){const t=J(this.initialData.parent),y=this.project.get(t);if(y)this.setParent(y,null),i.push(y);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${t}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);return this.initialData.extends.forEach(t=>{const y=J(t),v=this.project.get(y);v&&(this.addExtension(v),v.type!==f.BuiltInBaseEntity&&i.push(v))}),this.initialData.implements.forEach(t=>{const y=J(t),v=this.project.get(y);v&&(this.addImplementation(v),v.type!==f.BuiltInBaseEntity&&i.push(v))}),{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"after-all-children-initialized"))){const a=[],l=[],p=[],t=[];this.initialized=!0;const{updated:y,added:v,removed:T,affected:w}=this.syncImplementationProperties(i);a.push(...y),l.push(...v),p.push(...T),t.push(...w);const{updated:A,added:V,removed:N,affected:j}=this.addExtendedProperties(i);a.push(...A),l.push(...V),p.push(...N),t.push(...j);const{updated:k,added:S,removed:W}=this.removeUnrecognizedProperties(i);a.push(...k),l.push(...S),p.push(...W);const{updated:ne,added:re,removed:pe,affected:se}=this.syncImplementationMethods(i);a.push(...ne),l.push(...re),p.push(...pe),t.push(...se);const{updated:he,added:X,removed:z,affected:ce}=this.addExtendedMethods(i);a.push(...he),l.push(...X),p.push(...z),t.push(...ce);const{updated:H,added:de,removed:Te}=this.removeUnrecognizedMethods(i);return a.push(...H),l.push(...de),p.push(...Te),this.addSuggestions(),this.captureVersion(),i==null||i.attemptAutoclose("after-all-children-initialized",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-self-to-project"))){const a=[this],l=[],p=[],t=[];if(this.parent.type===f.DataType){const y=this.parent;y.entity=this,a.push(y)}else this.project.addDefinitionEntity(this);return this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}setParent(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"set-parent"))){var l;return((l=this.parent)==null?void 0:l.id)!==(i==null?void 0:i.id)&&(this.parent=i,a&&(a==null||a.add(this,K.Updated))),a==null||a.attemptAutoclose("set-parent",this.id),this}addExtension(i){return this.extends.includes(i)||this.extends.push(i),this}removeExtension(i){return this.extends=this.extends.filter(a=>a.id!==i.id),this}addImplementation(i){return this.implements.includes(i)||this.implements.push(i),this}removeImplementation(i){return this.implements=this.implements.filter(a=>a.id!==i.id),this}removeProperty(i){return this.properties=this.properties.filter(a=>a.id!==i.id),this}addMethod(i){return this.methods.includes(i)||(this.methods.push(i),this.suggestedMethods=this.suggestedMethods.filter(a=>a.name!==i.name)),this}removeMethod(i){return this.methods=this.methods.filter(a=>a.id!==i.id),this}addProperty(i){return this.properties.includes(i)||(this.properties.push(i),this.suggestedProperties=this.suggestedProperties.filter(a=>a.name!==i.name)),this}addSuggestedProperty(i){return this.suggestedProperties.includes(i)||this.suggestedProperties.push(i),this}addSuggestedMethod(i){return this.suggestedMethods.includes(i)||this.suggestedMethods.push(i),this}removeSuggestedProperty(i){return this.suggestedProperties=this.suggestedProperties.filter(a=>a.id!==i.id),this}removeSuggestedMethod(i){return this.suggestedMethods=this.suggestedMethods.filter(a=>a.id!==i.id),this}addAbstractMethod(i){return this.abstractMethods.includes(i)||this.abstractMethods.push(i),this}removeAbstractMethod(i){return this.abstractMethods=this.abstractMethods.filter(a=>a.id!==i.id),this}initChildren(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.properties=this.initialData.properties.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.methods=this.initialData.methods.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.abstractMethods=this.initialData.abstractMethods.map(a=>{const l=te(a,this.project);return l.setParent(this,null),l.initChildren(i),l}),this.extends=this.initialData.extends.map(a=>te(a,this.project)),this.implements=this.initialData.implements.map(a=>te(a,this.project)),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}removeUnrecognizedProperties(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-unrecognized-properties"))){const a=[],l=[],p=[],t=[];let y=[...this.properties];y=y.filter(T=>T.parent.id===this.id),y=y.filter(T=>!T.isExtendedProperty);const v=this.implementedPropertiesFromOriginalParents;return y=y.filter(T=>this.interactive&&!T.implements?!1:!v.find(w=>{var A;return w.id===((A=T.implements)==null?void 0:A.id)})),y.forEach(T=>{const w=T.remove({ignoreUpstream:!1},i);p.push(...w.removed),a.push(...w.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-properties",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}removeUnrecognizedMethods(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-unrecognized-methods"))){const a=[],l=[],p=[],t=[];let y=[...this.methods];y=y.filter(T=>T.parent.id===this.id),y=y.filter(T=>!T.isExtendedMethod);const v=this.implementedMethodsFromOriginalParents;return y=y.filter(T=>this.interactive&&!T.implements?!1:!v.find(w=>{var A;return w.id===((A=T.implements)==null?void 0:A.id)})),y.forEach(T=>{const w=T.remove({ignoreUpstream:!1},i);p.push(...w.removed),a.push(...w.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-methods",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncImplementationMethods(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-implementation-methods"))){const a=[],l=[],p=[],t=[],y=this.methods,v=this.implementedMethodsFromOriginalParents,T=[...this.allBaseMethodsFromExtendedAndImplementedEntities,...y];return v.filter(A=>!T.find(N=>{var j;return((j=N.implements)==null?void 0:j.id)===A.id})).forEach(A=>{if(this.methods.find(k=>{var S;return((S=k.implements)==null?void 0:S.id)===A.id}))return;const N=this.methods.find(k=>{var pe,se;if(k.name===A.name&&!k.implements)return!0;const S=Qi(this,Ce.CRON_JOB),W=Qi(this,Ce.HTTP_ENDPOINT),ne=((pe=k.implements)==null?void 0:pe.id)===ve["built-in-base-entity"].BUILT_IN_HTTP_ENDPOINT_ENTITY.methods.handler.id,re=((se=k.implements)==null?void 0:se.id)===ve["built-in-base-entity"].BUILT_IN_CRON_JOB_ENTITY.methods.handler.id;return!!(S&&!re&&!W&&ne||W&&!ne&&!S&&re)});if(N&&N.type===f.FunctionDeclaration){N.setImplements(A),N.metaSync({name:A.name},i),i==null||i.add(N,K.Updated),i==null||i.add(this,K.Updated);return}const j=A.implementAsFunctionDeclaration(i,this);l.push(j),i==null||i.add(j,K.Added),this.addMethod(j)}),i==null||i.attemptAutoclose("sync-implementation-methods",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}syncImplementationProperties(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"sync-implementation-properties"))){const a=[],l=[],p=[],t=[],y=this.properties,v=this.implementedPropertiesFromOriginalParents,T=[...this.allBasePropertiesFromExtendedAndImplementedEntities,...y];return v.filter(A=>!T.find(N=>{var j;return((j=N.implements)==null?void 0:j.id)===A.id})).forEach(A=>{if(this.properties.find(k=>{var S;return((S=k.implements)==null?void 0:S.id)===A.id}))return;const N=this.properties.find(k=>k.name===A.name&&!!k.abstract&&!k.implements);if(N){N.setImplements(A,i),N.metaSync({abstract:!1},i),N.afterAllChildrenInitialized(i);return}const j=A.implement(this,i,P.UUID.uuid());l.push(j),i==null||i.add(j,K.Added)}),i==null||i.attemptAutoclose("sync-implementation-properties",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addExtendedMethods(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-extended-methods"))){const a=[],l=[],p=[],t=[],y=this.methods,T=this.extendedMethodsFromOriginalParents.filter(A=>A.type===f.FunctionDeclaration),w=new Set(y.filter(A=>{var V;return!!((V=A.extends)!=null&&V.id)}).map(A=>A.extends.id));return T.forEach(A=>{if(w.has(A.id))return;w.add(A.id);const V=A.clone(i,this,P.UUID.uuid());V.setExtends(A,i),V.initChildren(i),l.push(V),i==null||i.add(V,K.Added),this.addMethod(V)}),i==null||i.attemptAutoclose("add-extended-methods",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addExtendedProperties(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"add-extended-properties"))){const a=[],l=[],p=[],t=[],y=this.properties,v=this.extendedPropertiesFromOriginalParents,T=v.filter(A=>v.find(N=>{var j;return((j=N.implements)==null?void 0:j.id)===A.id})?!1:!A.abstract),w=new Set(y.filter(A=>{var V;return!!((V=A.extends)!=null&&V.id)}).map(A=>A.extends.id));return T.forEach(A=>{if(w.has(A.id))return;w.add(A.id);const V=A.clone(i,this,P.UUID.uuid());V.setExtends(A,i),V.initChildren(i),l.push(V),i==null||i.add(V,K.Added),this.addProperty(V)}),i==null||i.attemptAutoclose("add-extended-properties",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSuggestions(){return this.implements.forEach(i=>{B6(this,i).forEach(p=>{const t=p.toJSON();t.id=`_suggestion--parent--${this.id}--${p.id}`;const y=te(t,this.project);y.suggestion=!0,y.setParent(this,null),y.initChildren(null),this.addSuggestedProperty(y)}),M6(this,i).forEach(p=>{const t=`_suggestion--parent--${this.id}--${p.id}`,y=p.implementAsFunctionDeclaration(null,this,t),v=te(y,this.project);if(v.suggestion=!0,v.setParent(this,null),v.initChildren(null),this.methods=this.methods.filter(T=>T.id!==t),v.inputs.forEach(T=>{T.suggestion=!0}),v.returnStatements.length){const T=v.returnStatements[0];T.suggestion=!0,T.outputs.forEach(w=>{w.suggestion=!0})}this.addSuggestedMethod(v)})}),this}subscribe(){return this.activeVersion=!0,this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.name=i.name!==void 0?i.name:p.name,this.codeName=i.codeName!==void 0?i.codeName:p.codeName,this.description=i.description!==void 0?i.description:p.description,this.x=i.x||p.x,this.y=i.y||p.y,this.static=i.static!==void 0?i.static:this.static,this.abstract=i.abstract!==void 0?i.abstract:this.abstract,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await Vt.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await Vt.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await Vt.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await Vt.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await Vt.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await Vt.repository.APILoadVersion(this.id,a,...l)}removeFromParent(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-from-parent"))){const a=[],l=[],p=[],t=[];if(this.parent.type===f.Project)this.parent.removeDefinitionEntity(this);else if(this.parent.type===f.DataType&&this.parent.entity&&this.parent.entity.id===this.id){const y=this.parent.setEntity(null,i);a.push(y)}return i==null||i.attemptAutoclose("remove-from-parent",this.id),{added:R(p),updated:R(a),removed:R(l),affected:R(t),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){const l=[],p=[],t=[],y=[];if(a!=null&&a.hasRemoved(this.id))return a==null||a.attemptAutoclose("remove-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(p.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},a),Object.values(this.detachedDependents).forEach(v=>{const{updated:T,removed:w,added:A}=v.entity.onDetachedDependencyRemoved(this,v.field,a);l.push(...T),p.push(...w),t.push(...A)}),this.properties.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.methods.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.abstractMethods.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.suggestedProperties.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),this.suggestedMethods.forEach(v=>{const{updated:T,removed:w}=v.remove({ignoreUpstream:!0},a);l.push(...T),p.push(...w)}),!i){const v=this.removeFromParent(a);t.push(...v.added),l.push(...v.updated),p.push(...v.removed),y.push(...v.affected)}return a==null||a.attemptAutoclose("remove-entity",this.id),{added:R(t),updated:R(l),removed:R(p),affected:R(y),self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){const a=[],l=[],p=[],t=[];return i!=null&&i.hasAdded(this.id)?(i==null||i.attemptAutoclose("restore-entity",this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(y=>{const{updated:v,removed:T,added:w}=y.entity.onDetachedDependencyRestored(this,y.field,i);l.push(...v),p.push(...T),a.push(...w)}),this.properties.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.methods.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.abstractMethods.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.suggestedProperties.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),this.suggestedMethods.forEach(y=>{const{updated:v}=y.restore({},i);l.push(...v)}),i==null||i.attemptAutoclose("restore-entity",this.id),{added:R(a),updated:R(l),removed:R(p),affected:R(t),self:this})}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.extends.flatMap(l=>l.toFlat(i)),...this.implements.flatMap(l=>l.toFlat(i)),...this.properties.flatMap(l=>l.toFlat(i)),...this.methods.flatMap(l=>l.toFlat(i)),...this.abstractMethods.flatMap(l=>l.toFlat(i)),...this.parent.toFlat(i)])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.extends.flatMap(l=>l.toFlatIds(i)),...this.implements.flatMap(l=>l.toFlatIds(i)),...this.properties.flatMap(l=>l.toFlatIds(i)),...this.methods.flatMap(l=>l.toFlatIds(i)),...this.abstractMethods.flatMap(l=>l.toFlatIds(i)),...this.parent.toFlatIds(i)])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,codeName:this.codeName,description:this.description,static:this.static,abstract:this.abstract,x:this.x,y:this.y,type:this.type,name:this.name}}toJSON(i=new Set){return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,codeName:this.codeName,description:this.description,x:this.x,y:this.y,static:this.static,abstract:this.abstract,properties:this.properties.map(a=>a.toJSON(i)),methods:this.methods.map(a=>a.toJSON(i)),abstractMethods:this.abstractMethods.map(a=>a.toJSON(i)),implements:this.implements.map(a=>a.toJSON(i)),extends:this.extends.map(a=>a.toJSON(i)),parent:this.parent.toReference()})}toJSONClone(i=Le){var l,p,t,y,v;let a;return(l=i.seenEntityMaps)!=null&&l.has(this.id)?a=i.seenEntityMaps.get(this.id):(a=i.newId||Rr(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,a)),(p=i.seenEntities)!=null&&p.has(a)||(t=i.seenEntities)!=null&&t.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((y=i.seenEntities)==null||y.add(a),(v=i.seenEntities)==null||v.add(this.id),{id:a,version:P.UUID.uuid(),createdAt:i.timestamp||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,type:this.type,name:this.name,codeName:this.codeName,description:this.description,x:this.x,y:this.y,static:this.static,abstract:this.abstract,properties:this.properties.map(T=>T.toJSONClone({...i,newId:null})),methods:this.methods.map(T=>T.toJSONClone({...i,newId:null})),abstractMethods:this.abstractMethods.map(T=>T.toJSONClone({...i,newId:null})),implements:this.implements.map(T=>T.type===f.BuiltInBaseEntity?T.toJSON():T.toJSONClone({...i,newId:null})),extends:this.extends.map(T=>T.type===f.BuiltInBaseEntity?T.toJSON():T.toJSONClone({...i,newId:null})),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,name:this.name,codeName:this.codeName,description:this.description,type:this.type,x:this.x,y:this.y,static:this.static,abstract:this.abstract,properties:this.properties.map(p=>p.toReference(i)),methods:this.methods.map(p=>p.toReference(i)),abstractMethods:this.abstractMethods.map(p=>p.toReference(i)),implements:this.implements.map(p=>p.toReference(i)),extends:this.extends.map(p=>p.toReference(i)),parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(l=>l.toFlatJSON(i)),...this.methods.flatMap(l=>l.toFlatJSON(i)),...this.abstractMethods.flatMap(l=>l.toFlatJSON(i)),...this.implements.flatMap(l=>l.toFlatJSON(i)),...this.extends.flatMap(l=>l.toFlatJSON(i)),...this.parent.toFlatJSON(i)])}toGenerationTarget(){const i=this.parent.type===f.Project?void 0:this.parent.id;return{id:this.id,name:this.name,description:this.description,type:this.type,static:this.static,abstract:this.abstract,extends:this.extends.map(a=>a.id),implements:this.implements.map(a=>a.id),parent:i}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(l=>l.toFlatGenerationTarget(i)),...this.methods.flatMap(l=>l.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(l=>l.toFlatGenerationTarget(i)),...this.implements.filter(l=>l.type===f.DefinitionEntity).flatMap(l=>l.toFlatGenerationTarget(i)),...this.implements.filter(l=>l.type===f.DefinitionEntity).flatMap(l=>l.toFlatGenerationTarget(i)),...this.parent.toFlatGenerationTarget(i)])}clearErrors(){return this.errors=[],this.properties.forEach(i=>i.clearErrors()),this.methods.forEach(i=>i.clearErrors()),this.abstractMethods.forEach(i=>i.clearErrors()),this}validate(){return this.errors=L6(this),{success:!0,error:null,data:null}}getErrors(){return[...this.errors,...this.properties.flatMap(a=>a.getErrors()),...this.methods.flatMap(a=>a.getErrors()),...this.abstractMethods.flatMap(a=>a.getErrors())]}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"clone-entity")),a=null,l=null,p=!0){var k,S,W;let t=gr(a,this);const y=this.toJSON(),v=l||P.UUID.uuid();y.properties=[],y.methods=[],y.abstractMethods=[];const T=v.split("-id"),w=T[T.length-1||0]||v;y.id=v,y.version=P.UUID.uuid(),y.createdAt=(i==null?void 0:i.timestamp)||L().toISOString(),y.author=(i==null?void 0:i.author)||"1",y.previousVersion=null,y.deleted=!1;const A=St(y,t);a&&A.setParent(a,null),p&&A.subscribe(),A.initChildren(i),i==null||i.add(A,K.Added);const V=(k=this.properties)==null?void 0:k.map(ne=>ne.clone(i,A,P.UUID.uuid(),p));A.properties=V;const N=(S=this.methods)==null?void 0:S.map((ne,re)=>ne.clone(i,A,w+"-method-"+re+"-id",p));A.methods=N;const j=(W=this.abstractMethods)==null?void 0:W.map((ne,re)=>ne.clone(i,A,w+"-abstract-method-"+re+"-id",p));return A.abstractMethods=j,i==null||i.attemptAutoclose("clone-entity",this.id),A}getFunctionDeclaration(i){return this.methods.find(a=>a.id===i)}implement(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"implement-definition-entity")),l){const p=Ky(this,i,a,l);return a==null||a.attemptAutoclose("implement-definition-entity",this.id),p}getAllInteractiveMethods(){const i=this.implements.filter(l=>l.type===f.DefinitionEntity||l.type===f.BuiltInBaseEntity&&l.interactive);return R([...this.methods,...this.extends.flatMap(l=>l.getAllInteractiveMethods()),...i.flatMap(l=>l.getAllInteractiveMethods())])}inferFromInputs(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),this,!0,"infer-definition-entity-from-inputs"))){const l=[],p=[],t=[],y=[];if(this.parent.type!==f.DataType||!this.parent.inferred)return a==null||a.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:[],updated:[],removed:[],affected:[],self:this};const v=[];i.forEach(A=>{v.find(N=>ie(N,this.project)===ie(A,this.project))||v.push(A)});const T=this.properties.filter(A=>!A.dataType);v.forEach(A=>{var W,ne;const V=T.find(re=>ie(re,this.project)===ie(A,this.project));if(!V)return;const j=di(A.parent).getMasterInputWithValueWritterFromAllInstances(A),k=Ys(j,a),S=k==null?void 0:k.clone(a,V,P.UUID.uuid(),!0);S&&((W=V.dataType)==null||W.merge(S,a),S.id!==((ne=V.dataType)==null?void 0:ne.id)&&S.remove({ignoreUpstream:!1},a),V.dataType&&(V.dataType.metaSync({inferred:!0,like:!0},a),V.setDataType(V.dataType,a),a==null||a.add(V,K.Affected))),A.setDeclaration(V),a==null||a.add(A,K.Updated)});const w=[];return v.forEach(A=>{if(!A.declaration){w.push(A);return}}),w.length===0?(a==null||a.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(w.forEach(A=>{var re,pe,se,he;const V=this.properties.find(X=>ie(X,this.project)===ie(A,this.project));if(V){if(A.setDeclaration(V),!V.getDataType(a)){const z=di(A.parent).getMasterInputWithValueWritterFromAllInstances(A),ce=Ys(z),H=ce==null?void 0:ce.clone(a,V,P.UUID.uuid(),!0);H&&((re=V.dataType)==null||re.merge(H,a),H.id!==((pe=V.dataType)==null?void 0:pe.id)&&H.remove({ignoreUpstream:!1},a),V.dataType&&(V.dataType.metaSync({inferred:!0,like:!0},a),V.setDataType(V.dataType,a),a==null||a.add(V,K.Affected)))}return}const N={id:P.UUID.uuid(),type:f.Property,version:P.UUID.uuid(),createdAt:(a==null?void 0:a.timestamp)||L().toISOString(),author:P.sessionAuthor,previousVersion:null,deleted:!1,name:ie(A,this.project),codeName:A.codeName,description:A.description,defaultValue:null,static:!0,abstract:!1,private:!1,hidden:!1,required:!1,constant:!0,interactive:!0,index:A.index,implements:null,extends:null,dataType:null,parent:this.toReference()},j=te(N,this.project);j.setParent(this,a),j.initChildren(a),a==null||a.add(j,K.Added);const S=di(A.parent).getMasterInputWithValueWritterFromAllInstances(A),W=Ys(S),ne=W==null?void 0:W.clone(a,j,P.UUID.uuid(),!0);return ne&&((se=j.dataType)==null||se.merge(ne,a),ne.id!==((he=j.dataType)==null?void 0:he.id)&&ne.remove({ignoreUpstream:!1},a),j.dataType&&(j.dataType.metaSync({inferred:!0,like:!0},a),j.setDataType(j.dataType,a),a==null||a.add(j,K.Affected))),this.addProperty(j),A.setDeclaration(j),a==null||a.add(A,K.Updated),j}),a==null||a.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:R(l),updated:R(p),removed:R(t),affected:R(y),self:this})}getRawDefaultValue(){const i={};return this.properties.forEach(a=>{var p;if(!FA(a))return;const l=Tr(a.name);i[l]=((p=a.getDefaultValue())==null?void 0:p.value)||null}),i}getActiveRawDefaultValue(){const i={};return this.properties.forEach(a=>{var t;if(!FA(a))return;const l=Tr(a.name),p=(t=this.project.requestActiveDynamicValue(a))==null?void 0:t.value;i[l]=(p==null?void 0:p.value)||null}),i}};D(Vt,"repository",{APICreate:async(i,...a)=>i,APIUpdate:async(i,...a)=>i,APIDelete:async(i,...a)=>i,APIClone:async(i,...a)=>{},APILoad:async(i,...a)=>null,APILoadVersion:async(i,a,...l)=>null}),D(Vt,"type",f.DefinitionEntity),D(Vt,"USER_MANAGED_PARENT_TYPES",[f.Project,f.DataType]),D(Vt,"PARENT_TYPES",[...Vt.USER_MANAGED_PARENT_TYPES]),D(Vt,"MUTABLE_BASE_PROPERTIES",["name","codeName","description","static","abstract"]),D(Vt,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),D(Vt,"BASE_PROPERTIES",[...Vt.MUTABLE_BASE_PROPERTIES,...Vt.INMUTABLE_BASE_PROPERTIES]),D(Vt,"MUTABLE_META_PROPERTIES",[...Vt.MUTABLE_BASE_PROPERTIES,"x","y"]),D(Vt,"INMUTABLE_META_PROPERTIES",[...Vt.INMUTABLE_BASE_PROPERTIES]),D(Vt,"META_PROPERTIES",[...Vt.MUTABLE_META_PROPERTIES,...Vt.INMUTABLE_META_PROPERTIES]),D(Vt,"MUTABLE_UPSTREAM_PROPERTIES",["extends","implements"]),D(Vt,"INMUTABLE_UPSTREAM_PROPERTIES",["parent"]),D(Vt,"UPSTREAM_PROPERTIES",[...Vt.MUTABLE_UPSTREAM_PROPERTIES,...Vt.INMUTABLE_UPSTREAM_PROPERTIES]),D(Vt,"MUTABLE_DOWNSTREAM_PROPERTIES",["properties","methods","abstractMethods"]),D(Vt,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),D(Vt,"DOWNSTREAM_PROPERTIES",[...Vt.MUTABLE_DOWNSTREAM_PROPERTIES,...Vt.INMUTABLE_DOWNSTREAM_PROPERTIES]),D(Vt,"PROPERTIES",[...Vt.META_PROPERTIES,...Vt.UPSTREAM_PROPERTIES,...Vt.DOWNSTREAM_PROPERTIES]);let va=Vt;function hve(d){const u=Sde(),i=d.toJSON();u.safeParse(i).success;const l=[];return Qt(d.errors,l)}const kp=class kp extends mr{constructor(i,a){super(i);D(this,"initialData");D(this,"id");D(this,"version");D(this,"name");D(this,"description",null);D(this,"type",f.BuiltInBaseEntity);D(this,"abstract",!1);D(this,"static");D(this,"properties",[]);D(this,"methods",[]);D(this,"abstractMethods",[]);D(this,"extends",[]);D(this,"interactive",!1);D(this,"errors",[]);D(this,"project");this.initialData=this.initialData||i,this.project=this.project||a,this.id=this.id||i.id,this.version=this.version||i.version,this.name=this.name||i.name,this.static=this.static||i.static,this.interactive=this.interactive||i.interactive,this.abstract=i.abstract,this.properties=this.initialData.properties.map(l=>{const p=te(l,this.project);return p.setParent(this,null),p.initChildren(null),p}),this.methods=this.initialData.methods.map(l=>{const p=te(l,this.project);return p.setParent(this,null),p.initChildren(null),p}),this.abstractMethods=this.initialData.abstractMethods.map(l=>{const p=te(l,this.project);return p.setParent(this,null),p.initChildren(null),p}),this.extends=this.initialData.extends.map(l=>te(l,this.project))}get allMethods(){return R([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return R([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){return R([...this.extends.flatMap(i=>i.allMethods,[])])}get allBasePropertiesFromOriginalParents(){return R([...this.extends.flatMap(i=>i.allProperties,[])])}get allBasePropertiesFromExtendedAndImplementedEntities(){return R(this.extends.reduce((i,a)=>{const l=[...a.ownDeclaredProperties,...a.allBasePropertiesFromExtendedAndImplementedEntities].filter(p=>!p.abstract);return[...i,...l]},[]))}get extendedPropertiesFromOriginalParents(){return R(this.extends.reduce((i,a)=>{const l=[...a.ownDeclaredProperties,...a.extendedPropertiesFromOriginalParents].filter(p=>!p.abstract);return[...i,...l]},[]))}get implementedPropertiesFromOriginalParents(){return R([...this.extends.reduce((i,a)=>{const l=a.implementedPropertiesFromOriginalParents,p=[...a.ownDeclaredProperties].filter(t=>!!t.abstract&&!l.find(y=>y.name===t.name));return[...l,...p,...i]},[])])}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredMethods(){return this.methods.filter(i=>!i.isExtendedMethod)}get ownDeclaredProperties(){return this.properties.filter(i=>!i.isExtendedProperty)}subscribe(){return this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}async APILoad(i=me,...a){return await kp.repository.APILoad(this.id,...a),this}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.properties.flatMap(l=>l.toFlat(i)),...this.methods.flatMap(l=>l.toFlat(i)),...this.abstractMethods.flatMap(l=>l.toFlat(i)),...this.extends.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.properties.flatMap(l=>l.toFlatIds(i)),...this.methods.flatMap(l=>l.toFlatIds(i)),...this.abstractMethods.flatMap(l=>l.toFlatIds(i)),...this.extends.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,interactive:this.interactive,abstract:this.abstract,static:this.static,type:this.type,name:this.name}}toJSON(i=new Set){return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,abstract:this.abstract,static:this.static,interactive:this.interactive,properties:this.properties.map(a=>a.toJSON(i)),methods:this.methods.map(a=>a.toJSON(i)),abstractMethods:this.abstractMethods.map(a=>a.toJSON(i)),extends:this.extends.map(a=>a.toJSON(i))})}toReference(i=Le){return{id:this.id+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:this.id,version:this.version,entityType:this.type}}toShallowJSON(i=Le){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,abstract:this.abstract,static:this.static,interactive:this.interactive,properties:this.properties.map(a=>a.toReference()),methods:this.methods.map(a=>a.toReference()),abstractMethods:this.abstractMethods.map(a=>a.toReference()),extends:this.extends.map(a=>a.toReference())}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(l=>l.toFlatJSON(i)),...this.methods.flatMap(l=>l.toFlatJSON(i)),...this.abstractMethods.flatMap(l=>l.toFlatJSON(i))])}toGenerationTarget(){return{id:this.id,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,interactive:this.interactive,extends:this.extends.map(i=>i.id)}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(l=>l.toFlatGenerationTarget(i)),...this.methods.flatMap(l=>l.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(l=>l.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.properties.forEach(i=>i.clearErrors()),this.methods.forEach(i=>i.clearErrors()),this.abstractMethods.forEach(i=>i.clearErrors()),this}validate(){const i=hve(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.properties.flatMap(a=>a.getErrors()),...this.methods.flatMap(a=>a.getErrors()),...this.abstractMethods.flatMap(a=>a.getErrors())]}getShallowErrors(){return this.errors}implement(i,a=this.project.addChangeSet(new G(this.project,P.sessionAuthor,L().toISOString(),null,!0,"implement-built-in-base-entity")),l){const p=Ky(this,i,a,l);return a==null||a.attemptAutoclose("implement-built-in-base-entity",this.id),p}getAllInteractiveMethods(){const i=[];return this.interactive&&(i.push(...this.methods),this.extends.filter(l=>l.type===f.BuiltInBaseEntity&&l.interactive||l.type===f.PrimitiveEntity).forEach(l=>{l instanceof kp&&i.push(...l.getAllInteractiveMethods())})),R(i)}};D(kp,"repository",{APILoad:async(i,...a)=>null});let $n=kp;function yve(d){const u=Bde(),i=d.toJSON();u.safeParse(i).success;const l=[];return Qt(d.errors,l)}const nm=class nm extends mr{constructor(i,a){super(i);D(this,"initialData");D(this,"id");D(this,"name");D(this,"description",null);D(this,"type",f.PrimitiveEntity);D(this,"static");D(this,"abstract");D(this,"properties",[]);D(this,"methods",[]);D(this,"abstractMethods",[]);D(this,"extends",[]);D(this,"errors",[]);D(this,"project");this.initialData=i,this.project=a,this.id=i.id,this.name=i.name,this.static=i.static,this.abstract=i.abstract,this.properties=this.initialData.properties.map(l=>{const p=te(l,this.project);return p.setParent(this,null),p.initChildren(null),p}),this.methods=this.initialData.methods.map(l=>{const p=te(l,this.project);return p.parent=this,p}),this.abstractMethods=this.initialData.abstractMethods.map(l=>{const p=te(l,this.project);return p.parent=this,p})}get allMethods(){return R([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return R([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){return R([...this.extends.flatMap(i=>i.allMethods,[])])}get allBasePropertiesFromOriginalParents(){return R([...this.extends.flatMap(i=>i.allProperties,[])])}get allBasePropertiesFromExtendedAndImplementedEntities(){return R(this.extends.reduce((i,a)=>{const l=[...a.ownDeclaredProperties,...a.allBasePropertiesFromExtendedAndImplementedEntities].filter(p=>!p.abstract);return[...i,...l]},[]))}get extendedPropertiesFromOriginalParents(){return R(this.extends.reduce((i,a)=>{const l=[...a.ownDeclaredProperties,...a.extendedPropertiesFromOriginalParents].filter(p=>!p.abstract);return[...i,...l]},[]))}get implementedPropertiesFromOriginalParents(){return R([...this.extends.reduce((i,a)=>{const l=a.implementedPropertiesFromOriginalParents,p=[...a.ownDeclaredProperties].filter(t=>!!t.abstract&&!l.find(y=>y.name===t.name));return[...l,...p,...i]},[])])}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredMethods(){return this.methods.filter(i=>!i.isExtendedMethod)}get ownDeclaredProperties(){return this.properties.filter(i=>!i.isExtendedProperty)}subscribe(){return this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}async APILoad(i=me,...a){return await nm.repository.APILoad(this.id,...a),this}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.properties.flatMap(l=>l.toFlat(i)),...this.methods.flatMap(l=>l.toFlat(i)),...this.abstractMethods.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.properties.flatMap(l=>l.toFlatIds(i)),...this.methods.flatMap(l=>l.toFlatIds(i)),...this.abstractMethods.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,static:this.static,abstract:this.abstract,type:this.type,name:this.name}}toJSON(i=new Set){return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,properties:this.properties.map(a=>a.toJSON(i)),methods:this.methods.map(a=>a.toJSON(i)),abstractMethods:this.abstractMethods.map(a=>a.toJSON(i)),extends:this.extends.map(a=>a.toJSON(i))})}toReference(i=Le){return{id:this.id+"--"+P.UUID.uuid()+"--ref",type:f.GenericReference,entityId:this.id,version:this.version,entityType:this.type}}toShallowJSON(i=Le){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,abstract:this.abstract,static:this.static,properties:this.properties.map(a=>a.toReference()),methods:this.methods.map(a=>a.toReference()),abstractMethods:this.abstractMethods.map(a=>a.toReference()),extends:this.extends.map(a=>a.toReference())}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(l=>l.toFlatJSON(i)),...this.methods.flatMap(l=>l.toFlatJSON(i)),...this.abstractMethods.flatMap(l=>l.toFlatJSON(i))])}toGenerationTarget(){return{id:this.id,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,extends:this.extends.map(i=>i.id)}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(l=>l.toFlatGenerationTarget(i)),...this.methods.flatMap(l=>l.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(l=>l.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.properties.forEach(i=>i.clearErrors()),this.methods.forEach(i=>i.clearErrors()),this.abstractMethods.forEach(i=>i.clearErrors()),this}validate(){const i=yve(this);return this.errors=i,{success:!0,error:null,data:this.toJSON()}}getErrors(){return[...this.errors,...this.properties.flatMap(a=>a.getErrors()),...this.methods.flatMap(a=>a.getErrors()),...this.abstractMethods.flatMap(a=>a.getErrors())]}getShallowErrors(){return this.errors}getAllInteractiveMethods(){const i=[];return i.push(...this.methods),this.extends.filter(l=>l.type===f.BuiltInBaseEntity&&l.interactive||l.type===f.PrimitiveEntity).forEach(l=>{l instanceof $n&&i.push(...l.getAllInteractiveMethods())}),R(i)}};D(nm,"repository",{APILoad:async(i,...a)=>null});let Li=nm;function St(d,u){if(!d)throw new Error("Entity is null");const i=u.get(d.id);switch(d.type){case f.LiteralValue:return i||new Ti(d,u);case f.DefinitionEntity:return i||new va(d,u);case f.PrimitiveEntity:return i||new Li(d,u);case f.FunctionDeclaration:return i||new Ma(d,u);case f.GlobalEvent:return i||new xa(d,u);case f.DataType:return i||new Yi(d,u);case f.Property:return i||new ca(d,u);case f.FunctionCall:return i||new Xa(d,u);case f.Condition:return i||new Fa(d,u);case f.Operation:return i||new Ua(d,u);case f.VariableDeclaration:return i||new Ka(d,u);case f.VariableInstance:return i||new Ga(d,u);case f.OutputMap:return i||new Xs(d,u);case f.ReturnDeclaration:return i||new Ni(d,u);case f.ArgumentDeclaration:return i||new fa(d,u);case f.InputMap:return i||new $s(d,u);case f.Project:return i||new P(d);case f.InstalledProject:return i||new Sa(d,u);case f.ActionDescriptor:return i||new dt(d,u);case f.ReturnStatement:return i||new ja(d,u);case f.Loop:return i||new bi(d,u);case f.Search:return i||new ka(d,u);case f.ValueDescriptor:return i||new Qs(d,u);case f.BuiltInBaseEntity:return i||new $n(d,u);case f.InternalCall:return i||new qa(d,u);case f.ContinueStatement:return i||new ui(d,u);case f.BreakStatement:return i||new Za(d,u);case f.GenericReference:return u.get(d.entityId);default:throw new Error("Invalid entity type: "+d.type)}}function te(d,u){if(!d)throw new Error("Entity is null");const i=St(d,u);return i.subscribe(),i}function mve(d,u){if(!d)throw new Error("Entity is null");switch(d.type){case f.LiteralValue:return Ti.fromGenerationTarget(d,u);case f.DefinitionEntity:return va.fromGenerationTarget(d,u);case f.FunctionDeclaration:return Ma.fromGenerationTarget(d,u);case f.GlobalEvent:return xa.fromGenerationTarget(d,u);case f.DataType:return Yi.fromGenerationTarget(d,u);case f.Property:return ca.fromGenerationTarget(d,u);case f.FunctionCall:return Xa.fromGenerationTarget(d,u);case f.Condition:return Fa.fromGenerationTarget(d,u);case f.Operation:return Ua.fromGenerationTarget(d,u);case f.VariableDeclaration:return Ka.fromGenerationTarget(d,u);case f.VariableInstance:return Ga.fromGenerationTarget(d,u);case f.OutputMap:return Xs.fromGenerationTarget(d,u);case f.ReturnDeclaration:return Ni.fromGenerationTarget(d,u);case f.ArgumentDeclaration:return fa.fromGenerationTarget(d,u);case f.InputMap:return $s.fromGenerationTarget(d,u);case f.InstalledProject:return Sa.fromGenerationTarget(d,u);case f.ReturnStatement:return ja.fromGenerationTarget(d,u);case f.Loop:return bi.fromGenerationTarget(d,u);case f.Search:return ka.fromGenerationTarget(d,u);case f.ActionDescriptor:return dt.fromGenerationTarget(d,u);case f.ValueDescriptor:return Qs.fromGenerationTarget(d,u);case f.InternalCall:return qa.fromGenerationTarget(d,u);case f.ContinueStatement:return ui.fromGenerationTarget(d,u);case f.BreakStatement:return Za.fromGenerationTarget(d,u);default:throw new Error("Invalid entity type: "+d.type)}}const Le={seenEntityMaps:new Map,seenEntities:new Set,timestamp:L().toISOString()};class j6{constructor(){D(this,"initialData")}}const me={cascade:!1},x6={APILoad:async(d,...u)=>null},vve={APICreate:async(d,...u)=>d,APIUpdate:async(d,...u)=>d,APIDelete:async(d,...u)=>d,APIClone:async(d,...u)=>{},APILoadVersion:async(d,u,...i)=>null,...x6};class Eve{}class Tve extends j6{}class bve{}class Ave{}class Ive{}class GA{}class wve extends GA{}class Rve extends GA{}class gve{}class Fp{static initReadsValue(u){if(u.initialData.readsValue&&u.initialData.readsValue.type!==f.GenericReference)u.readsValue=te(u.initialData.readsValue,u.project);else if(u.initialData.readsValue&&u.initialData.readsValue.type===f.GenericReference){const i=Ri(u.initialData.readsValue,u.project);i&&(u.readsValue=i)}if(u.readsValue){if(st.includes(u.readsValue.type)){let i=u.parent;wr.includes(i.type)||(i=i.parent);const a=u.type===f.InputMap&&u.parent.type===f.Loop;a&&(i=u.parent.parent),u.readsValue.setParent(i,null),u.readsValue.initChildren(null),i&&i.type!==f.Project&&!a&&i.detachedChildren.includes(u)?i.replaceDetachedChild(u,u.readsValue):i&&i.type!==f.Project&&!a&&i.subscribeDetachedChild(u.readsValue)}u.readsValue.addValueReader(u,null)}return u.readsValue}}class Gp{static initWritesValues(u,i){const a=u.initialData.writesValues.reduce((p,t)=>{if(t.type===f.GenericReference||u.writesValues.some(v=>v.id===t.id))return p;const y=te(t,u.project);return y.setValueWriter(u,null),st.includes(y.type)&&(y.setParent(i,null),y.initChildren(null)),[...p,y]},[]),l=[...u.writesValues];return u.writesValues=R([...l,...a]),u.writesValues}}class _ve{}var vr=(d=>(d.PROJECT_INITIALIZED="project-initialized",d.CHANGE_SET_CLOSED="change-set-closed",d.EXPLICIT_DEFINITION_ENTITY_ADDED="explicit-definition-entity-added",d.EXPLICIT_DEFINITION_ENTITY_REMOVED="explicit-definition-entity-removed",d.EXPLICIT_DEFINITION_ENTITY_UPDATED="explicit-definition-entity-updated",d.PERSISTED_DEFINITION_ENTITY_ADDED="persisted-definition-entity-added",d.PERSISTED_DEFINITION_ENTITY_REMOVED="persisted-definition-entity-removed",d.PERSISTED_DEFINITION_ENTITY_UPDATED="persisted-definition-entity-updated",d.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED="relational-database-definition-entity-added",d.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED="relational-database-definition-entity-removed",d.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED="relational-database-definition-entity-updated",d))(vr||{});const Xe=class Xe extends mr{constructor(i){super(i);D(this,"initialData");D(this,"id");D(this,"type",f.Project);D(this,"name",null);D(this,"description",null);D(this,"x");D(this,"y");D(this,"entities",[]);D(this,"projects",[]);D(this,"functions",[]);D(this,"events",[]);D(this,"variableDeclarations",[]);D(this,"variableInstances",[]);D(this,"conditions",[]);D(this,"operations",[]);D(this,"functionCalls",[]);D(this,"loops",[]);D(this,"searches",[]);D(this,"primitives",[]);D(this,"builtInBaseEntities",[]);D(this,"operationDeclarations",[]);D(this,"globalEventActionDescriptors",[]);D(this,"loopDeclarations",[]);D(this,"loopDeclarationsBodies",[]);D(this,"conditionDeclarations",[]);D(this,"valueDescriptors",[]);D(this,"dataTypes",[]);D(this,"project");D(this,"instances",{});D(this,"builtInInstances",{});D(this,"deletedInstances",{});D(this,"errors",[]);D(this,"references",[]);D(this,"history",[]);D(this,"undoableStackValueIndex",-1);D(this,"detachedDependents",{});D(this,"knownVersions",null);D(this,"activeVersion",!1);D(this,"initialized",!1);D(this,"startedInitialization",!1);D(this,"_eventsHub",new zb);D(this,"onCloseChangeSetCallback",null);D(this,"onAddChangeSetCallback",null);D(this,"onDiscardChangeSetCallback",null);D(this,"onRequestActiveDynamicValueCallback",null);if(this.initialData=i,this.id=i.id,this.name=i.name,this.description=i.description,this.x=0,this.y=0,this.instances[this.id]=this,!Xe.UUID)throw new Error("UUID module is already initialized. Please inject a valid UUID module.")}static get UUID(){return this._UUIDModule}static injectUUIDModule(i){this._UUIDModule=i}static new(i=null){return{id:Xe.UUID.uuid(),version:Xe.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||L().toISOString(),author:(i==null?void 0:i.author)||Xe.sessionAuthor,previousVersion:null,deleted:!1,type:f.Project,name:"",description:"",entities:[],functions:[],events:[],projects:[],variableDeclarations:[],variableInstances:[],conditions:[],operations:[],functionCalls:[],loops:[],searches:[]}}static validateGenerationTarget(i,a){let l=JSON.parse(JSON.stringify(i));const p=[];return p.push(...br(l)),{errors:p,modifiedData:l}}get off(){return this._eventsHub.off}get on(){return this._eventsHub.on}get emit(){return this._eventsHub.emit}async closePendingChangeSets(){const i=this.history.find(a=>a.dirty&&!a.open);i&&await this.closeChangeSet(i)}onRequestActiveDynamicValue(i){this.onRequestActiveDynamicValueCallback=i}async onCloseChangeSet(i){this.onCloseChangeSetCallback=i,await this.closePendingChangeSets()}onAddChangeSet(i){this.onAddChangeSetCallback=i}onDiscardChangeSet(i){this.onDiscardChangeSetCallback=i}async closeChangeSet(i){const a=this.history.findIndex(t=>t.id===i.id),l=this.history.slice(0,a),p=l[l.length-1];if(!(p!=null&&p.dirty)&&this.onCloseChangeSetCallback){(await this.onCloseChangeSetCallback(i)).success&&(i.dirty=!1,this.emit("change-set-closed",i),this.closePendingChangeSets());return}}toLatestChangeSet(i,a,l,p=!1,t="here-this"){if(!this.history.length)return new G(this,i,a,l,p,t);const y=this.history[this.history.length-1];return y.open?y:this.addChangeSet(new G(this,i,a,l,p,t))}addChangeSet(i){var p,t;if(!this.history.length)return this.undoableStackValueIndex=Ab(this.undoableStackValueIndex,this.history,i),(p=this.onAddChangeSetCallback)==null||p.call(this,i,this.undoableStackValueIndex),i;const a=this.history.find(y=>y.id===(i==null?void 0:i.id));if(a)return a;const l=this.history.find(y=>y.open);if(l)throw console.warn("Previous still open: ",l),console.warn("New change set: ",i),new Error(`There is already an open change-set with id '${l.id}'.`);return this.undoableStackValueIndex=Ab(this.undoableStackValueIndex,this.history,i),(t=this.onAddChangeSetCallback)==null||t.call(this,i,this.undoableStackValueIndex),i}discardChangeSet(i){var l;const a=this.history.findIndex(p=>p.id===(i==null?void 0:i.id));return a!==-1&&(this.history.splice(a,1),this.undoableStackValueIndex=this.undoableStackValueIndex-1,(l=this.onDiscardChangeSetCallback)==null||l.call(this,i)),this}async inject(...i){return await Promise.all(i.map(a=>new Promise(async l=>{await a.init(this),l(null)}))),this}validateGeneratedUpdate(i){return{errors:[],modifiedData:i}}subscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]||(this.detachedDependents[a.entity.id]=a)}),this}unsubscribeDependents(i){return i.forEach(a=>{this.detachedDependents[a.entity.id]&&delete this.detachedDependents[a.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new G(this.project,Xe.sessionAuthor,L().toISOString(),this,!0,"sync-dependents"))){const a=[],l=[],p=[],t=[];return Object.values(this.detachedDependents).forEach(y=>{const v=y.entity.afterAllChildrenInitialized(i);a.push(...v.updated),l.push(...v.added),p.push(...v.removed),t.push(...v.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}onDetachedDependencyRemoved(i,a,l){const p=[],t=[],y=[],v=[];return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}onDetachedDependencyRestored(i,a,l){const p=[],t=[],y=[],v=[];return{updated:R(p),added:R(t),removed:R(y),affected:R(v),self:this}}unsubscribeFromDependencies(){return this}subscribeToDependencies(){return this}increaseVersion(i){if(i&&!L(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);return i&&L(i).isSame(L(this.createdAt))?this:(this.previousVersion=this.version,this.version=Xe.UUID.uuid(),this.createdAt=L(i).toISOString()||L().toISOString(),this)}captureVersion(){var a;const i=((a=this.knownVersions)==null?void 0:a.get(this.version))||new Xe(this);return i.metaSync(this.toMeta(),null),this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map([[this.version,i]]),i.entities=[...this.entities],i.projects=[...this.projects],i.functions=[...this.functions],i.events=[...this.events],i.variableDeclarations=[...this.variableDeclarations],i.variableInstances=[...this.variableInstances],i.conditions=[...this.conditions],i.operations=[...this.operations],i.functionCalls=[...this.functionCalls],i.loops=[...this.loops],i.searches=[...this.searches],this}recursiveCaptureUpstreamVersions(i){const a=[],l=[],p=[],t=[];return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}async restoreVersion(i){var v;const a=[],l=[],p=[],t=[];if(this.version===i)return{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this};if(!this.knownVersions){const T=new Map;for(const[w,A]of this.knownVersions||new Map){if(T.set(w,A),A.activeVersion=!1,A.knownVersions)for(const[V,N]of A.knownVersions)T.set(V,N);A.knownVersions=null}}let y=(v=this.knownVersions)==null?void 0:v.get(i);if(!y){const T=await this.APILoadVersion({},i);if(!T)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);y=new Xe(T)}return this.metaSync(y.toShallowJSON(),null),this.previousVersion=y.previousVersion,this.version=y.version,this.createdAt=y.createdAt,this.author=y.author,this.deleted=y.deleted,this.entities=y.entities,this.projects=y.projects,this.functions=y.functions,this.events=y.events,this.variableDeclarations=y.variableDeclarations,this.variableInstances=y.variableInstances,this.conditions=y.conditions,this.operations=y.operations,this.functionCalls=y.functionCalls,this.loops=y.loops,this.searches=y.searches,{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}updateWithShallowTransfer(i,a=this.project.addChangeSet(new G(this.project,Xe.sessionAuthor,L().toISOString(),this,!0,"update-with-shallow-transfer"))){return this.metaSync(i,a),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.captureVersion(),this.subscribeToDependencies(),a==null||a.attemptAutoclose("update-with-shallow-transfer",this.id),this}hydrateAncestors(){const i=[],a=[],l=[],p=[];return{updated:R(i),added:R(a),removed:R(l),affected:R(p),self:this}}afterAllChildrenInitialized(i=null){const a=[],l=[],p=[],t=[];return this.initialized||(this.initialized=!0,this.emit("project-initialized",this,i)),this.validate(),this.captureVersion(),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}addSelfToProject(i){const a=[],l=[],p=[],t=[];return this.subscribe(),this.subscribeToDependencies(),{updated:R(a),added:R(l),removed:R(p),affected:R(t),self:this}}get instancesList(){return Object.values(this.instances)}isOperationDeclaration(i){return this.operationDeclarations.includes(i)}isGlobalEventActionDescriptor(i){return this.globalEventActionDescriptors.includes(i)}isLoopDeclaration(i){return this.loopDeclarations.includes(i)}isConditionDeclaration(i){return this.conditionDeclarations.includes(i)}initChildren(i=this.project.addChangeSet(new G(this.project,Xe.sessionAuthor,L().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.entities=this.initialData.entities.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.projects=this.initialData.projects.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.variableDeclarations=this.initialData.variableDeclarations.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.variableInstances=this.initialData.variableInstances.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.conditions=this.initialData.conditions.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.operations=this.initialData.operations.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.functions=this.initialData.functions.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.events=this.initialData.events.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.functionCalls=this.initialData.functionCalls.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.loops=this.initialData.loops.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.searches=this.initialData.searches.map(a=>{const l=te(a,this);return l.setParent(this,null),l.initChildren(i),l}),this.attachOrphanReferences(),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribeInstance(i){return(!this.instances[i.id]||this.instances[i.id]!==i)&&(this.instances[i.id]=i),this}subscribeDeletedInstance(i){return(!this.deletedInstances[i.id]||this.deletedInstances[i.id]!==i)&&(this.deletedInstances[i.id]=i),this}subscribeBuiltInInstance(i){return(!this.builtInInstances[i.id]||this.builtInInstances[i.id]!==i)&&(this.builtInInstances[i.id]=i),this}subscribe(){return this}unsubscribe(){return this}unsubscribeInstance(i){return delete this.instances[i.id],this}unsubscribeDeletedInstance(i){return delete this.deletedInstances[i.id],this}findSubscribedBuiltInInstance(i){return this.builtInInstances[i.id]||null}get(i){return this.instances[i]||this.builtInInstances[i]||null}getDeleted(i){return this.deletedInstances[i]||null}getManaged(i){return this.getBuiltIn(i)?null:this.instances[i]||null}getBuiltIn(i){return this.builtInInstances[i]||null}findSubscribedInstanceFromReference(i){return this.instances[i.entityId]||null}findSubscribedBuiltInInstanceFromReference(i){return this.builtInInstances[i.entityId]||null}metaSync(i,a=this.project.addChangeSet(new G(this.project,Xe.sessionAuthor,L().toISOString(),this,!0,"meta-sync"))){const l=Ar(this,i),p=this.toMeta();return this.name=i.name!==void 0?i.name:p.name,this.description=i.description!==void 0?i.description:p.description,this.x=i.x||p.x,this.y=i.y||p.y,super.metaSync(i),i.deleted===!0&&!p.deleted?a==null||a.add(this,K.Removed):i.deleted===!1&&p.deleted?a==null||a.add(this,K.Added):l&&(a==null||a.add(this,K.Updated)),a==null||a.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=me,...a){return await Xe.repository.APILoad(this.id,...a),this}async APICreate(i=me,...a){return await Xe.repository.APICreate(this.toShallowJSON(),...a),this}async APIUpdate(i=me,...a){return await Xe.repository.APIUpdate(this.toShallowJSON(),...a),this}async APIDelete(i=me,...a){return await Xe.repository.APIDelete(this.toShallowJSON(),...a),this}async APIClone(i=me,...a){return await Xe.repository.APIClone(this.id,...a),this}async APILoadVersion(i=me,a,...l){return await Xe.repository.APILoadVersion(this.id,a,...l)}remove({ignoreUpstream:i}={ignoreUpstream:!1},a=this.project.addChangeSet(new G(this.project,Xe.sessionAuthor,L().toISOString(),this,!0,"remove-entity"))){return{added:[],updated:[],removed:[],affected:[],self:this}}restore({}={},i=this.project.addChangeSet(new G(this.project,Xe.sessionAuthor,L().toISOString(),this,!0,"restore-entity"))){return{added:[],updated:[],removed:[],affected:[],self:this}}getAllBuiltInIds(){const i=new Set;return[...this.primitives.flatMap(a=>a.toFlatIds(i)),...this.builtInBaseEntities.flatMap(a=>a.toFlatIds(i)),...this.operationDeclarations.flatMap(a=>a.toFlatIds(i)),...this.globalEventActionDescriptors.flatMap(a=>a.toFlatIds(i)),...this.loopDeclarations.flatMap(a=>a.toFlatIds(i)),...this.conditionDeclarations.flatMap(a=>a.toFlatIds(i)),...this.valueDescriptors.flatMap(a=>a.toFlatIds(i)),...this.dataTypes.flatMap(a=>a.toFlatIds(i))]}getAllBuiltIn(){const i=new Set;return[...this.primitives.flatMap(a=>a.toFlat(i)),...this.builtInBaseEntities.flatMap(a=>a.toFlat(i)),...this.operationDeclarations.flatMap(a=>a.toFlat(i)),...this.globalEventActionDescriptors.flatMap(a=>a.toFlat(i)),...this.loopDeclarations.flatMap(a=>a.toFlat(i)),...this.conditionDeclarations.flatMap(a=>a.toFlat(i)),...this.valueDescriptors.flatMap(a=>a.toFlat(i)),...this.dataTypes.flatMap(a=>a.toFlat(i))]}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.entities.flatMap(l=>l.toFlat(i)),...this.functions.flatMap(l=>l.toFlat(i)),...this.events.flatMap(l=>l.toFlat(i)),...this.projects.flatMap(l=>l.toFlat(i)),...this.variableDeclarations.flatMap(l=>l.toFlat(i)),...this.variableInstances.flatMap(l=>l.toFlat(i)),...this.conditions.flatMap(l=>l.toFlat(i)),...this.operations.flatMap(l=>l.toFlat(i)),...this.functionCalls.flatMap(l=>l.toFlat(i)),...this.loops.flatMap(l=>l.toFlat(i)),...this.searches.flatMap(l=>l.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.entities.flatMap(l=>l.toFlatIds(i)),...this.functions.flatMap(l=>l.toFlatIds(i)),...this.events.flatMap(l=>l.toFlatIds(i)),...this.projects.flatMap(l=>l.toFlatIds(i)),...this.variableDeclarations.flatMap(l=>l.toFlatIds(i)),...this.variableInstances.flatMap(l=>l.toFlatIds(i)),...this.conditions.flatMap(l=>l.toFlatIds(i)),...this.operations.flatMap(l=>l.toFlatIds(i)),...this.functionCalls.flatMap(l=>l.toFlatIds(i)),...this.loops.flatMap(l=>l.toFlatIds(i)),...this.searches.flatMap(l=>l.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,type:this.type,name:this.name}}toJSON(i=new Set){return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,entities:this.entities.map(a=>a.toJSON(i)),variableDeclarations:this.variableDeclarations.map(a=>a.toJSON(i)),variableInstances:this.variableInstances.map(a=>a.toJSON(i)),conditions:this.conditions.map(a=>a.toJSON(i)),operations:this.operations.map(a=>a.toJSON(i)),loops:this.loops.map(a=>a.toJSON(i)),searches:this.searches.map(a=>a.toJSON(i)),functions:this.functions.map(a=>a.toJSON(i)),events:this.events.map(a=>a.toJSON(i)),projects:this.projects.map(a=>a.toJSON(i)),functionCalls:this.functionCalls.map(a=>a.toJSON(i))})}toJSONClone(i={uuidStrategy:"uuid"}){const a=new Map,l=new Set,p=this.getAllBuiltInIds();return Object.keys(this.instances).forEach(t=>{if(p.includes(t)){a.set(t,t);return}a.set(t,Xe.UUID.uuid())}),l.add(this.id),{id:a.get(this.id),version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,entities:this.entities.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),projects:this.projects.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),variableDeclarations:this.variableDeclarations.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),variableInstances:this.variableInstances.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),conditions:this.conditions.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),operations:this.operations.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),functions:this.functions.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),events:this.events.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),functionCalls:this.functionCalls.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),loops:this.loops.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null})),searches:this.searches.map(t=>t.toJSONClone({...i,seenEntityMaps:a,seenEntities:l,newId:null}))}}toReference(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a+"--"+Xe.UUID.uuid()+"--ref",type:f.GenericReference,entityId:a,version:this.version,entityType:this.type}}toShallowJSON(i=Le){var l;let a=this.id;return(l=i.seenEntityMaps)!=null&&l.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,entities:this.entities.map(p=>p.toReference(i)),functions:this.functions.map(p=>p.toReference(i)),events:this.events.map(p=>p.toReference(i)),projects:this.projects.map(p=>p.toReference(i)),variableDeclarations:this.variableDeclarations.map(p=>p.toReference(i)),variableInstances:this.variableInstances.map(p=>p.toReference(i)),conditions:this.conditions.map(p=>p.toReference(i)),operations:this.operations.map(p=>p.toReference(i)),functionCalls:this.functionCalls.map(p=>p.toReference(i)),loops:this.loops.map(p=>p.toReference(i)),searches:this.searches.map(p=>p.toReference(i))}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.entities.flatMap(l=>l.toFlatJSON(i)),...this.functions.flatMap(l=>l.toFlatJSON(i)),...this.events.flatMap(l=>l.toFlatJSON(i)),...this.projects.flatMap(l=>l.toFlatJSON(i)),...this.variableDeclarations.flatMap(l=>l.toFlatJSON(i)),...this.variableInstances.flatMap(l=>l.toFlatJSON(i)),...this.conditions.flatMap(l=>l.toFlatJSON(i)),...this.operations.flatMap(l=>l.toFlatJSON(i)),...this.functionCalls.flatMap(l=>l.toFlatJSON(i)),...this.loops.flatMap(l=>l.toFlatJSON(i)),...this.searches.flatMap(l=>l.toFlatJSON(i))])}toGenerationTarget(){return{id:this.id,type:this.type,name:this.name,description:this.description}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[...this.entities.flatMap(l=>l.toFlatGenerationTarget(i)),...this.functions.flatMap(l=>l.toFlatGenerationTarget(i)),...this.events.flatMap(l=>l.toFlatGenerationTarget(i)),...this.projects.flatMap(l=>l.toFlatGenerationTarget(i)),...this.variableDeclarations.flatMap(l=>l.toFlatGenerationTarget(i)),...this.variableInstances.flatMap(l=>l.toFlatGenerationTarget(i)),...this.conditions.flatMap(l=>l.toFlatGenerationTarget(i)),...this.operations.flatMap(l=>l.toFlatGenerationTarget(i)),...this.functionCalls.flatMap(l=>l.toFlatGenerationTarget(i)),...this.loops.flatMap(l=>l.toFlatGenerationTarget(i)),...this.searches.flatMap(l=>l.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.entities.forEach(i=>i.clearErrors()),this.projects.forEach(i=>i.clearErrors()),this.functions.forEach(i=>i.clearErrors()),this.events.forEach(i=>i.clearErrors()),this.variableDeclarations.forEach(i=>i.clearErrors()),this.variableInstances.forEach(i=>i.clearErrors()),this.conditions.forEach(i=>i.clearErrors()),this.operations.forEach(i=>i.clearErrors()),this.functionCalls.forEach(i=>i.clearErrors()),this.loops.forEach(i=>i.clearErrors()),this.searches.forEach(i=>i.clearErrors()),this}validate(){const i=ape(),a=this.toJSON();return i.safeParse(a),this.validateChildren(),{success:!0,error:null,data:a}}validateChildren(){this.entities.forEach(i=>i.validate()),this.projects.forEach(i=>i.validate()),this.functions.forEach(i=>i.validate()),this.events.forEach(i=>i.validate()),this.variableDeclarations.forEach(i=>i.validate()),this.variableInstances.forEach(i=>i.validate()),this.conditions.forEach(i=>i.validate()),this.operations.forEach(i=>i.validate()),this.functionCalls.forEach(i=>i.validate()),this.loops.forEach(i=>i.validate()),this.searches.forEach(i=>i.validate())}getErrors(){return[...this.errors,...this.entities.flatMap(a=>a.getErrors()),...this.projects.flatMap(a=>a.getErrors()),...this.functions.flatMap(a=>a.getErrors()),...this.events.flatMap(a=>a.getErrors()),...this.variableDeclarations.flatMap(a=>a.getErrors()),...this.variableInstances.flatMap(a=>a.getErrors()),...this.conditions.flatMap(a=>a.getErrors()),...this.operations.flatMap(a=>a.getErrors()),...this.functionCalls.flatMap(a=>a.getErrors()),...this.loops.flatMap(a=>a.getErrors()),...this.searches.flatMap(a=>a.getErrors())]}getShallowErrors(){return this.errors}clone(){return this}getDefinitionEntity(i){return this.entities.find(a=>a.id===i)||null}addDefinitionEntity(i){return this.entities.includes(i)||this.entities.push(i),i}addFunctionDeclaration(i){return this.functions.includes(i)||this.functions.push(i),i}addFunctionCall(i){return this.functionCalls.includes(i)||this.functionCalls.push(i),i}addVariableDeclaration(i){return this.variableDeclarations.includes(i)||this.variableDeclarations.push(i),i}addVariableInstance(i){return this.variableInstances.includes(i)||this.variableInstances.push(i),i}addInstalledProject(i){return this.projects.includes(i)||this.projects.push(i),this}addGlobalEvent(i){return this.events.includes(i)||this.events.push(i),this}addCondition(i){return this.conditions.includes(i)||this.conditions.push(i),this}addOperation(i){return this.operations.includes(i)||this.operations.push(i),this}addLoop(i){return this.loops.includes(i)||this.loops.push(i),this}addSearch(i){return this.searches.includes(i)||this.searches.push(i),this}removeDefinitionEntity(i){const a=this.entities.findIndex(l=>l.id===i.id);if(a>-1){const l=this.entities[a];return this.entities.splice(a,1),l}return null}removeCondition(i){const a=this.conditions.findIndex(l=>l.id===i.id);if(a>-1){const l=this.conditions[a];return this.conditions.splice(a,1),l}return null}removeOperation(i){const a=this.operations.findIndex(l=>l.id===i.id);if(a>-1){const l=this.operations[a];return this.operations.splice(a,1),l}return null}removeLoop(i){const a=this.loops.findIndex(l=>l.id===i.id);if(a>-1){const l=this.loops[a];return this.loops.splice(a,1),l}return null}removeSearch(i){const a=this.searches.findIndex(l=>l.id===i.id);if(a>-1){const l=this.searches[a];return this.searches.splice(a,1),l}return null}removeFunctionCall(i){const a=this.functionCalls.findIndex(l=>l.id===i.id);if(a>-1){const l=this.functionCalls[a];return this.functionCalls.splice(a,1),l}return null}removeVariableInstance(i){const a=this.variableInstances.findIndex(l=>l.id===i.id);if(a>-1){const l=this.variableInstances[a];return this.variableInstances.splice(a,1),l}return null}removeVariableDeclaration(i){const a=this.variableDeclarations.findIndex(l=>l.id===i.id);if(a>-1){const l=this.variableDeclarations[a];return this.variableDeclarations.splice(a,1),l}return null}removeFunctionDeclaration(i){const a=this.functions.findIndex(l=>l.id===i.id);if(a>-1){const l=this.functions[a];return this.functions.splice(a,1),l}return null}removeInstalledProject(i){const a=this.projects.findIndex(l=>l.id===i.id);if(a>-1){const l=this.projects[a];return this.projects.splice(a,1),l}return null}removeGlobalEvent(i){const a=this.events.findIndex(l=>l.id===i.id);if(a>-1){const l=this.events[a];return this.events.splice(a,1),l}return null}removeTopLevelVariableDeclaration(i){if(i.type!==f.VariableDeclaration)return null;const a=this.variableDeclarations.findIndex(l=>l.id===i.id);if(a>-1){const l=this.variableDeclarations[a];return this.variableDeclarations.splice(a,1),l}return null}getEntryPoints(){return[...this.functions,...this.events,...this.entities.flatMap(a=>a.methods)]}getTerminationStatements(){return[...this.getEntryPoints().reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.ReturnStatement||t.type===f.ContinueStatement||t.type===f.BreakStatement)]},[])]}getFunctionDeclaration(i){return this.functions.find(a=>a.id===i)||null}getConditions(){return[...this.conditions,...this.getEntryPoints().reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Condition)]},[]),...this.functionCalls.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Condition)]},[]),...this.operations.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Condition)]},[]),...this.loops.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Condition)]},[]),...this.searches.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Condition)]},[])]}getOperations(){return[...this.operations,...this.getEntryPoints().reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Operation)]},[]),...this.functionCalls.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Operation)]},[]),...this.conditions.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Operation)]},[]),...this.loops.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Operation)]},[]),...this.searches.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Operation)]},[])]}getFunctionCalls(){return[...this.functionCalls,...this.getEntryPoints().reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.FunctionCall)]},[]),...this.conditions.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.FunctionCall)]},[]),...this.operations.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.FunctionCall)]},[]),...this.loops.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.FunctionCall)]},[]),...this.searches.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.FunctionCall)]},[])]}getVariables(){return[...this.variableDeclarations,...this.getEntryPoints().reduce((a,l)=>{const p=Xt(l);return[...a,...p]},[]),...this.functionCalls.reduce((a,l)=>{const p=Xt(l);return[...a,...p]},[]),...this.conditions.reduce((a,l)=>{const p=Xt(l);return[...a,...p]},[]),...this.operations.reduce((a,l)=>{const p=Xt(l);return[...a,...p]},[]),...this.loops.reduce((a,l)=>{const p=Xt(l);return[...a,...p]},[]),...this.searches.reduce((a,l)=>{const p=Xt(l);return[...a,...p]},[])]}getVariableInstances(){return[...this.variableInstances,...this.entities.reduce((a,l)=>[...a,...l.methods.flatMap(p=>{const y=pt(p).filter(v=>v.type===f.VariableInstance);return[...a,...y]})],[]),...this.getEntryPoints().reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableInstance);return[...a,...t]},[]),...this.functionCalls.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableInstance);return[...a,...t]},[]),...this.conditions.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableInstance);return[...a,...t]},[]),...this.operations.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableInstance);return[...a,...t]},[]),...this.loops.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableInstance);return[...a,...t]},[]),...this.searches.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableInstance);return[...a,...t]},[])]}getVariableDeclarations(){return R([...this.variableDeclarations,...this.entities.reduce((a,l)=>[...a,...l.methods.flatMap(p=>{const y=pt(p).filter(v=>v.type===f.VariableDeclaration);return[...a,...y]})],[]),...this.getEntryPoints().reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableDeclaration);return[...a,...t]},[]),...this.functionCalls.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableDeclaration);return[...a,...t]},[]),...this.conditions.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableDeclaration);return[...a,...t]},[]),...this.operations.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableDeclaration);return[...a,...t]},[]),...this.loops.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableDeclaration);return[...a,...t]},[]),...this.searches.reduce((a,l)=>{const t=Xt(l).filter(y=>y.type===f.VariableDeclaration);return[...a,...t]},[])])}getLoops(){return[...this.loops,...this.getEntryPoints().reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Loop)]},[]),...this.functionCalls.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Loop)]},[]),...this.conditions.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Loop)]},[]),...this.operations.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Loop)]},[]),...this.searches.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Loop)]},[])]}getSearches(){return[...this.searches,...this.getEntryPoints().reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Search)]},[]),...this.functionCalls.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Search)]},[]),...this.conditions.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Search)]},[]),...this.operations.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Search)]},[]),...this.loops.reduce((a,l)=>{const p=pt(l);return[...a,...p.filter(t=>t.type===f.Search)]},[])]}attachOrphanReferences(){const i=this.getVariableInstances(),a=this.getVariableDeclarations();return i.forEach(l=>{if(!l.declaration){const p=l.initialData,t=p.declaration.entityId||p.declaration.id,y=a.find(v=>v.id===t);y&&l.setDeclaration(y)}}),this}getBuiltInPersistedEntity(){return this.builtInBaseEntities.find(i=>i.name===Ce.PERSISTED_ENTITY)||null}requestActiveDynamicValue(i){var l;const a=(l=this.onRequestActiveDynamicValueCallback)==null?void 0:l.call(this,i);if(!a){const p=i.getDefaultValue();return p?{value:p,type:be.DefaultValue,inheritanceLink:null,valueOwner:i}:null}return a||null}undo(){console.log("Undoing, from: ",this.undoableStackValueIndex),this.undoableStackValueIndex=this.undoableStackValueIndex-1,console.log("To: ",this.undoableStackValueIndex);const i=this.history[this.undoableStackValueIndex+1],a=this.history[this.undoableStackValueIndex];return console.log("Current change set: ",i),console.log("Change set to restore: ",a==null?void 0:a.toJSON()),Tb(i||"initial",a||"initial",this)}redo(){console.log("Undoing, from: ",this.undoableStackValueIndex),this.undoableStackValueIndex=this.undoableStackValueIndex+1,console.log("To: ",this.undoableStackValueIndex);const i=this.history[this.undoableStackValueIndex-1],a=this.history[this.undoableStackValueIndex];return console.log("Current change set: ",i),console.log("Change set to restore: ",a.toJSON()),Tb(i||"initial",a||"initial",this)}applyExternalChangeSet(i){const a=i.payload,l=this.addChangeSet(new G(this,i.userAuthor,i.emittedAt,this)),p=a.updated[this.id];if(!p)throw new Error("Project root not found in change set transfer. Cannot apply changes.");const t={...a.added,...a.updated,...a.removed},y=[...Object.keys(a.added),...Object.keys(a.updated),...Object.keys(a.removed)];y.forEach(T=>{var w;if(!t[T]){console.warn(`Entity '${T}' not found in change set transfer. Cannot apply changes.`);const A=(w=this.get(T))==null?void 0:w.toShallowJSON();throw A?console.warn("Entity in project: ",A):console.warn("Entity not in project"),new Error(`Entity '${T}' not found in change set transfer. Cannot apply changes.`)}});const v=new Cn(p);return v.flatRecord=t,v.order=y,v.orderEntities(),console.log("All entities: ",v.order.map((T,w)=>`${w+1}: ${t[T].type} - ${T}`).join(`,
|