@memberjunction/graphql-dataprovider 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0});import{gql as g,GraphQLClient as Ie}from"graphql-request";import{gql as at}from"graphql-request";import{TransactionGroupBase as Ne,TransactionResult as be,LogError as l,LogStatusEx as b,LogErrorEx as v,ProviderConfigDataBase as xe,ProviderBase as Te,UserInfo as Re,getGraphQLTypeNameBase as N,ProviderType as Ae,BaseEntityResult as De,EntityFieldTSType as $,TransactionItem as we,UserRoleInfo as Me,SetProvider as Ve,StartupManager as Qe,IsVerboseLoggingEnabled as Fe}from"@memberjunction/core";import{ViewInfo as Ee}from"@memberjunction/core-entities";import{Observable as x,Subject as Ue,Subscription as Ge}from"rxjs";import{createClient as Le}from"graphql-ws";import{v4 as _e}from"uuid";import{SafeJSONParse as P,MJGlobal as qe,MJEventType as Oe}from"@memberjunction/global";import{openDB as ke}from"@tempfix/idb";const Y=class Y{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(Y,"FieldMapper");let C=Y;const Z=class Z extends Ne{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=g`
1
+ var Ce=Object.defineProperty;var h=(D,e)=>Ce(D,"name",{value:e,configurable:!0});import{gql as p,GraphQLClient as Ie}from"graphql-request";import{gql as at}from"graphql-request";import{TransactionGroupBase as Ne,TransactionResult as be,LogError as d,LogStatusEx as b,LogErrorEx as P,ProviderConfigDataBase as xe,ProviderBase as Ae,UserInfo as Re,getGraphQLTypeNameBase as N,ProviderType as Me,BaseEntityResult as De,EntityFieldTSType as $,TransactionItem as we,UserRoleInfo as Te,SetProvider as Ve,StartupManager as Fe,IsVerboseLoggingEnabled as Qe}from"@memberjunction/core";import{ViewInfo as Ee}from"@memberjunction/core-entities";import{Observable as x,Subject as Ue,Subscription as Ge}from"rxjs";import{createClient as Le}from"graphql-ws";import{v4 as _e}from"uuid";import{SafeJSONParse as v,MJGlobal as qe,MJEventType as Oe}from"@memberjunction/global";import{openDB as ke}from"@tempfix/idb";const Y=class Y{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};h(Y,"FieldMapper");let C=Y;const Z=class Z extends Ne{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=p`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],u=P(n),p=this.PendingTransactions[i];o.push(new be(p,u,u!==null))}return o}else throw new Error("Failed to execute transaction group")}};f(Z,"GraphQLTransactionGroup");let T=Z;const ee=class ee{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=g`
9
+ `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],u=v(n),g=this.PendingTransactions[i];o.push(new be(g,u,u!==null))}return o}else throw new Error("Failed to execute transaction group")}};h(Z,"GraphQLTransactionGroup");let A=Z;const ee=class ee{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=p`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{b({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[n]});const u=JSON.parse(n);if(b({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){b({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const p={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(p)}else b({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",n)}}));const a=g`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{b({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[n]});const u=JSON.parse(n);if(b({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){b({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const g={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(g)}else b({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",n)}}));const a=p`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -104,7 +104,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
104
104
  result
105
105
  }
106
106
  }
107
- `,o=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,o);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return P(e)}handleAgentError(e){return l(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);if(i.resolver==="RunAIAgentResolver"&&i.type==="ExecutionProgress"&&i.status==="ok"&&i.data?.progress){const n={...i.data.progress,metadata:{...i.data.progress.metadata||{},agentRunId:i.data.agentRunId}};e.onProgress(n)}}catch(i){console.error("[GraphQLAIClient] Failed to parse progress message:",i)}}));const r=g`
107
+ `,o=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,o);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return v(e)}handleAgentError(e){return d(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);if(i.resolver==="RunAIAgentResolver"&&i.type==="ExecutionProgress"&&i.status==="ok"&&i.data?.progress){const n={...i.data.progress,metadata:{...i.data.progress.metadata||{},agentRunId:i.data.agentRunId}};e.onProgress(n)}}catch(i){console.error("[GraphQLAIClient] Failed to parse progress message:",i)}}));const r=p`
108
108
  mutation RunAIAgentFromConversationDetail(
109
109
  $conversationDetailId: String!,
110
110
  $agentId: String!,
@@ -141,7 +141,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
141
141
  result
142
142
  }
143
143
  }
144
- `,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=g`
144
+ `,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=p`
145
145
  mutation ExecuteSimplePrompt(
146
146
  $systemPrompt: String!,
147
147
  $messages: String,
@@ -164,7 +164,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
164
164
  executionTimeMs
165
165
  }
166
166
  }
167
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return l(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=g`
167
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return d(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=p`
168
168
  mutation EmbedText(
169
169
  $textToEmbed: [String!]!,
170
170
  $modelSize: String!
@@ -179,15 +179,15 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
179
179
  error
180
180
  }
181
181
  }
182
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const o=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return l(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(ee,"GraphQLAIClient");let A=ee;const E="default",te=class te{constructor(){this._storage=new Map}getCategoryMap(e){const t=e||E;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||E).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||E).set(e,t)}async Remove(e,t){this.getCategoryMap(t||E).delete(e)}async ClearCategory(e){const t=e||E;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||E);return t?Array.from(t.keys()):[]}};f(te,"BrowserStorageProviderBase");let M=te;const Be="MJ_Metadata",Ke=3,$e=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Pe="Metadata_KVPairs",re=class re extends M{constructor(){super(),this._dbReady=!1,this.dbPromise=ke(Be,Ke,{upgrade(e){try{e.objectStoreNames.contains(Pe)&&e.deleteObjectStore(Pe);for(const t of $e)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){v({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{v({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return $e.includes(t)}getStoreName(e){const t=e||E;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||E;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,o),await i.done}catch(s){v({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return v({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(a),await o.done}catch(r){v({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||E,s=this.getStoreName(e);if(this.isKnownCategory(r)){const a=t.transaction(s,"readwrite");await a.objectStore(s).clear(),await a.done}else{const a=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),n=await i.getAllKeys();for(const u of n)typeof u=="string"&&u.startsWith(a)&&await i.delete(u);await o.done}}catch(t){v({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||E,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(u=>String(u));const n=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(n)).map(u=>u.slice(n.length))}catch(t){return v({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};f(re,"BrowserIndexedDBStorageProvider");let V=re;const se=class se extends xe{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,o,i,n){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,RefreshTokenFunction:s},a,o,i)}};f(se,"GraphQLProviderConfigData");let F=se;const h=class h extends Te{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
182
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const o=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return d(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};h(ee,"GraphQLAIClient");let M=ee;const E="default",te=class te{constructor(){this._storage=new Map}getCategoryMap(e){const t=e||E;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||E).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||E).set(e,t)}async Remove(e,t){this.getCategoryMap(t||E).delete(e)}async ClearCategory(e){const t=e||E;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||E);return t?Array.from(t.keys()):[]}};h(te,"BrowserStorageProviderBase");let T=te;const Be="MJ_Metadata",Ke=3,$e=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],ve="Metadata_KVPairs",re=class re extends T{constructor(){super(),this._dbReady=!1,this.dbPromise=ke(Be,Ke,{upgrade(e){try{e.objectStoreNames.contains(ve)&&e.deleteObjectStore(ve);for(const t of $e)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){P({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{P({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return $e.includes(t)}getStoreName(e){const t=e||E;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||E;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,o),await i.done}catch(s){P({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return P({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(a),await o.done}catch(r){P({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||E,s=this.getStoreName(e);if(this.isKnownCategory(r)){const a=t.transaction(s,"readwrite");await a.objectStore(s).clear(),await a.done}else{const a=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),n=await i.getAllKeys();for(const u of n)typeof u=="string"&&u.startsWith(a)&&await i.delete(u);await o.done}}catch(t){P({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||E,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(u=>String(u));const n=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(n)).map(u=>u.slice(n.length))}catch(t){return P({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};h(re,"BrowserIndexedDBStorageProvider");let V=re;const se=class se extends xe{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,o,i,n){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,RefreshTokenFunction:s},a,o,i)}};h(se,"GraphQLProviderConfigData");let Q=se;const f=class f extends Ae{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
183
183
  ${this.userInfoString()}
184
184
  UserRoles_UserIDArray {
185
185
  ${this.userRoleInfoString()}
186
186
  }
187
187
  }
188
- `,this._currentUserQuery=g`query CurrentUserAndRoles {
188
+ `,this._currentUserQuery=p`query CurrentUserAndRoles {
189
189
  ${this._innerCurrentUserQueryString}
190
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new A(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return _e()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(a){throw l(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new Re(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=g`
190
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,f._instance||(f._instance=this)}static get Instance(){return f._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new M(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return _e()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(f.Instance._configData=e,f.Instance._sessionId===void 0&&(f.Instance._sessionId=await this.GetPreferredUUID(s)),f.Instance._client||(f.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,f.Instance._sessionId,e.MJAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.Instance._client),super.Config(e)}catch(a){throw d(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new Re(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=p`
191
191
  query GetReportDataQuery ($ReportID: String!) {
192
192
  GetReportData(ReportID: $ReportID) {
193
193
  Success
@@ -196,25 +196,25 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
196
196
  ExecutionTime
197
197
  ErrorMessage
198
198
  }
199
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async InternalRunQueries(e,t){const r=g`
199
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async InternalRunQueries(e,t){const r=p`
200
200
  query RunQueriesBatch($input: [RunQueryInput!]!) {
201
201
  RunQueries(input: $input) {
202
202
  ${this.QueryReturnFieldList}
203
203
  }
204
204
  }
205
- `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),a=await this.ExecuteGQL(r,{input:s});return a&&a.RunQueries?a.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,a,o,i){const n=g`
205
+ `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),a=await this.ExecuteGQL(r,{input:s});return a&&a.RunQueries?a.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,a,o,i){const n=p`
206
206
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
207
207
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
208
208
  ${this.QueryReturnFieldList}
209
209
  }
210
210
  }
211
- `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(n,u);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=g`
211
+ `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const g=await this.ExecuteGQL(n,u);if(g&&g.GetQueryData)return this.TransformQueryPayload(g.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=p`
212
212
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
213
213
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
214
214
  ${this.QueryReturnFieldList}
215
215
  }
216
216
  }
217
- `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(n,u);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
217
+ `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const g=await this.ExecuteGQL(n,u);if(g&&g.GetQueryDataByName)return this.TransformQueryPayload(g.GetQueryDataByName)}get QueryReturnFieldList(){return`
218
218
  Success
219
219
  QueryID
220
220
  QueryName
@@ -223,7 +223,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
223
223
  TotalRowCount
224
224
  ExecutionTime
225
225
  ErrorMessage
226
- AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return l(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(n=>({params:{QueryID:n.params.QueryID||null,QueryName:n.params.QueryName||null,CategoryID:n.params.CategoryID||null,CategoryPath:n.params.CategoryPath||null,Parameters:n.params.Parameters||null,MaxRows:n.params.MaxRows??null,StartRow:n.params.StartRow??null,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||null},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=g`
226
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return d(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(n=>({params:{QueryID:n.params.QueryID||null,QueryName:n.params.QueryName||null,CategoryID:n.params.CategoryID||null,CategoryPath:n.params.CategoryPath||null,Parameters:n.params.Parameters||null,MaxRows:n.params.MaxRows??null,StartRow:n.params.StartRow??null,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||null},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=p`
227
227
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
228
228
  RunQueriesWithCacheCheck(input: $input) {
229
229
  success
@@ -239,11 +239,11 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
239
239
  }
240
240
  }
241
241
  }
242
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(n=>{if((n.status==="stale"||n.status==="no_validation")&&n.Results){const u=JSON.parse(n.Results);return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,results:u,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return l(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:c,v:d}=await this.getEntityNameAndUserView(e,t);i=d,o=c}const n=this.Entities.find(c=>c.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let u=!1;const p=N(n);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(u=!0,r=`Run${p}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),u||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const m=this.getViewRunTimeFieldList(n,i,e,u),I=g`
242
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(n=>{if((n.status==="stale"||n.status==="no_validation")&&n.Results){const u=JSON.parse(n.Results);return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,results:u,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return d(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:c,v:m}=await this.getEntityNameAndUserView(e,t);i=m,o=c}const n=this.Entities.find(c=>c.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let u=!1;const g=N(n);e.ViewID?(r=`Run${g}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${g}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(u=!0,r=`Run${g}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),u||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const y=this.getViewRunTimeFieldList(n,i,e,u),S=p`
243
243
  query RunViewQuery ($input: ${s}!) {
244
244
  ${r}(input: $input) {
245
245
  Results {
246
- ${m.join(`
246
+ ${y.join(`
247
247
  `)}
248
248
  }
249
249
  UserViewRunID
@@ -253,7 +253,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
253
253
  Success
254
254
  ErrorMessage
255
255
  }
256
- }`,y=await this.ExecuteGQL(I,{input:a});if(y&&y[r]){const c=y[r].Results;if(c&&c.length>0){const R=n.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);c.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(w=>{S[w.Name]=S[w.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw l(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const n of e){let u="",p="";const m={};let I=null,y=null;if(n.ViewEntity)y=n.ViewEntity,I=y.Get("Entity");else{const{entityName:S,v:w}=await this.getEntityNameAndUserView(n,t);y=w,I=S}const c=this.Entities.find(S=>S.Name===I);if(!c)throw new Error(`Entity ${I} not found in metadata`);s.push(c);let d=!1;const R=N(c);n.ViewID?(u=`Run${R}ViewByID`,p="RunViewByIDInput",m.ViewID=n.ViewID):n.ViewName?(u=`Run${R}ViewByName`,p="RunViewByNameInput",m.ViewName=n.ViewName):(d=!0,u=`Run${R}DynamicView`,p="RunDynamicViewInput",m.EntityName=n.EntityName),m.ExtraFilter=n.ExtraFilter||"",m.OrderBy=n.OrderBy||"",m.UserSearchString=n.UserSearchString||"",m.Fields=n.Fields,m.IgnoreMaxRows=n.IgnoreMaxRows||!1,n.MaxRows!==void 0&&(m.MaxRows=n.MaxRows),n.StartRow!==void 0&&(m.StartRow=n.StartRow),m.ForceAuditLog=n.ForceAuditLog||!1,m.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(m.AuditLogDescription=n.AuditLogDescription),d||(m.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=n.OverrideExcludeFilter||"",m.SaveViewResults=n.SaveViewResults||!1),r.push(m),a.push(...this.getViewRunTimeFieldList(c,y,n,d))}const o=g`
256
+ }`,l=await this.ExecuteGQL(S,{input:a});if(l&&l[r]){const c=l[r].Results;if(c&&c.length>0){const R=n.Fields.filter(I=>I.CodeName!==I.Name&&I.CodeName!==void 0);c.forEach(I=>{this.ConvertBackToMJFields(I),R.forEach(w=>{I[w.Name]=I[w.CodeName]})})}return l[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const n of e){let u="",g="";const y={};let S=null,l=null;if(n.ViewEntity)l=n.ViewEntity,S=l.Get("Entity");else{const{entityName:I,v:w}=await this.getEntityNameAndUserView(n,t);l=w,S=I}const c=this.Entities.find(I=>I.Name===S);if(!c)throw new Error(`Entity ${S} not found in metadata`);s.push(c);let m=!1;const R=N(c);n.ViewID?(u=`Run${R}ViewByID`,g="RunViewByIDInput",y.ViewID=n.ViewID):n.ViewName?(u=`Run${R}ViewByName`,g="RunViewByNameInput",y.ViewName=n.ViewName):(m=!0,u=`Run${R}DynamicView`,g="RunDynamicViewInput",y.EntityName=n.EntityName),y.ExtraFilter=n.ExtraFilter||"",y.OrderBy=n.OrderBy||"",y.UserSearchString=n.UserSearchString||"",y.Fields=n.Fields,y.IgnoreMaxRows=n.IgnoreMaxRows||!1,n.MaxRows!==void 0&&(y.MaxRows=n.MaxRows),n.StartRow!==void 0&&(y.StartRow=n.StartRow),y.ForceAuditLog=n.ForceAuditLog||!1,y.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(y.AuditLogDescription=n.AuditLogDescription),m||(y.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=n.OverrideExcludeFilter||"",y.SaveViewResults=n.SaveViewResults||!1),r.push(y),a.push(...this.getViewRunTimeFieldList(c,l,n,m))}const o=p`
257
257
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
258
258
  RunViews(input: $input) {
259
259
  Results {
@@ -271,7 +271,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
271
271
  Success
272
272
  ErrorMessage
273
273
  }
274
- }`,i=await this.ExecuteGQL(o,{input:r});if(i&&i.RunViews){const n=i.RunViews;for(const[u,p]of n.entries())p.Results=p.Results.map(m=>{let I=JSON.parse(m.Data);return this.ConvertBackToMJFields(I),I});return n}return null}catch(r){throw l(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(n=>({params:{EntityName:n.params.EntityName||"",ExtraFilter:n.params.ExtraFilter||"",OrderBy:n.params.OrderBy||"",Fields:n.params.Fields,UserSearchString:n.params.UserSearchString||"",IgnoreMaxRows:n.params.IgnoreMaxRows||!1,MaxRows:n.params.MaxRows,StartRow:n.params.StartRow,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||"",ResultType:n.params.ResultType||"simple"},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=g`
274
+ }`,i=await this.ExecuteGQL(o,{input:r});if(i&&i.RunViews){const n=i.RunViews;for(const[u,g]of n.entries())g.Results=g.Results.map(y=>{let S=JSON.parse(y.Data);return this.ConvertBackToMJFields(S),S});return n}return null}catch(r){throw d(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(n=>({params:{EntityName:n.params.EntityName||"",ExtraFilter:n.params.ExtraFilter||"",OrderBy:n.params.OrderBy||"",Fields:n.params.Fields,UserSearchString:n.params.UserSearchString||"",IgnoreMaxRows:n.params.IgnoreMaxRows||!1,MaxRows:n.params.MaxRows,StartRow:n.params.StartRow,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||"",ResultType:n.params.ResultType||"simple"},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=p`
275
275
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
276
276
  RunViewsWithCacheCheck(input: $input) {
277
277
  success
@@ -290,10 +290,21 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
290
290
  EntityID
291
291
  Data
292
292
  }
293
+ differentialData {
294
+ updatedRows {
295
+ PrimaryKey {
296
+ FieldName
297
+ Value
298
+ }
299
+ EntityID
300
+ Data
301
+ }
302
+ deletedRecordIDs
303
+ }
293
304
  }
294
305
  }
295
306
  }
296
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((n,u)=>{const p=e[u];if(n.status==="stale"&&n.Results){const m=p.params.EntityName,I=this.Entities.find(c=>c.Name===m),y=n.Results.map(c=>{const d=JSON.parse(c.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:n.viewIndex,status:n.status,results:y,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{viewIndex:n.viewIndex,status:n.status,results:void 0,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return l(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await Ee.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Ee.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],o=new C;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return Ae.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw l(r),r}}async GetRecordDependencies(e,t){try{const r=g`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
307
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((n,u)=>{const g=e[u];if(n.status==="differential"&&n.differentialData){const y=n.differentialData.updatedRows.map(S=>{const l=JSON.parse(S.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:n.viewIndex,status:n.status,results:void 0,differentialData:{updatedRows:y,deletedRecordIDs:n.differentialData.deletedRecordIDs},maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}if(n.status==="stale"&&n.Results){const y=n.Results.map(S=>{const l=JSON.parse(S.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:n.viewIndex,status:n.status,results:y,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{viewIndex:n.viewIndex,status:n.status,results:void 0,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return d(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await Ee.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Ee.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],o=new C;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return Me.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw d(r),r}}async GetRecordDependencies(e,t){try{const r=p`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
297
308
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
298
309
  EntityName
299
310
  RelatedEntityName
@@ -305,7 +316,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
305
316
  }
306
317
  }
307
318
  }
308
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw l(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=g`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
319
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw d(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=p`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
309
320
  GetRecordDuplicates(params: $params) {
310
321
  Status
311
322
  ErrorMessage
@@ -327,7 +338,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
327
338
  }
328
339
  }
329
340
  }
330
- }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=g`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
341
+ }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=p`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
331
342
  MergeRecords(request: $request) {
332
343
  Success
333
344
  OverallStatus
@@ -344,32 +355,32 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
344
355
  Message
345
356
  }
346
357
  }
347
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(n=>({FieldName:n.FieldName,Value:n.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(n=>n.Copy())};return(await this.ExecuteGQL(a,{request:o}))?.MergeRecords}catch(a){return l(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new De;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=N(e.EntityInfo),n=`${o}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new C,m=` ${n}(input: $input) {
348
- ${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
358
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(n=>({FieldName:n.FieldName,Value:n.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(n=>n.Copy())};return(await this.ExecuteGQL(a,{request:o}))?.MergeRecords}catch(a){return d(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new De;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const i=N(e.EntityInfo),n=`${o}${i}`,u=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),g=new C,y=` ${n}(input: $input) {
359
+ ${e.Fields.map(l=>g.MapFieldName(l.CodeName)).join(`
349
360
  `)}
350
- }`,I=g`mutation ${o}${i} ($input: ${n}Input!) {
351
- ${m}
361
+ }`,S=p`mutation ${o}${i} ($input: ${n}Input!) {
362
+ ${y}
352
363
  }
353
- `;for(let y=0;y<u.length;y++){const c=u[y];let d=c.Value;if(d)switch(c.EntityFieldInfo.TSType){case $.Date:d=d.getTime();break;case $.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case $.Number:if(typeof d!="number"){const R=Number(d);isNaN(R)||(d=R)}break}d===null&&c.EntityFieldInfo.AllowsNull===!1&&(c.EntityFieldInfo.DefaultValue!==null?d=c.EntityFieldInfo.DefaultValue:c.FieldType===$.Number||c.FieldType===$.Boolean?d=0:d=""),a.input[c.CodeName]=d}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(c=>{let d=null;c.OldValue!==null&&c.OldValue!==void 0&&(c.EntityFieldInfo.TSType===$.Date?d=c.OldValue.getTime().toString():c.EntityFieldInfo.TSType===$.Boolean?d=c.OldValue===!0?"1":"0":typeof c.OldValue!="string"?d=c.OldValue.toString():d=c.OldValue),y.push({Key:c.CodeName,Value:d})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new we(e,s.Type==="create"?"Create":"Update",m,a,{mutationName:n,mutationInputTypes:y},(c,d)=>{s.EndedAt=new Date,d&&c?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(c)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(I,a);if(y&&y[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[n]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,l(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const c=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),R=c.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${c.CodeName}: ${R}!`,o.length>0&&(o+=", "),o+=`${c.CodeName}: $${c.CodeName}`,c.TSType===$.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${c.Name}) is not a valid number`);a[c.CodeName]=parseInt(d)}else a[c.CodeName]=d}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=N(e.EntityInfo),p=new C,m=g`query Single${u}${n.length>0?"Full":""} (${i}) {
364
+ `;for(let l=0;l<u.length;l++){const c=u[l];let m=c.Value;if(m)switch(c.EntityFieldInfo.TSType){case $.Date:m=m.getTime();break;case $.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case $.Number:if(typeof m!="number"){const R=Number(m);isNaN(R)||(m=R)}break}m===null&&c.EntityFieldInfo.AllowsNull===!1&&(c.EntityFieldInfo.DefaultValue!==null?m=c.EntityFieldInfo.DefaultValue:c.FieldType===$.Number||c.FieldType===$.Boolean?m=0:m=""),a.input[c.CodeName]=m}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const l=[];e.Fields.forEach(c=>{let m=null;c.OldValue!==null&&c.OldValue!==void 0&&(c.EntityFieldInfo.TSType===$.Date?m=c.OldValue.getTime().toString():c.EntityFieldInfo.TSType===$.Boolean?m=c.OldValue===!0?"1":"0":typeof c.OldValue!="string"?m=c.OldValue.toString():m=c.OldValue),l.push({Key:c.CodeName,Value:m})}),a.input.OldValues___=l}if(e.TransactionGroup){const l=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new we(e,s.Type==="create"?"Create":"Update",y,a,{mutationName:n,mutationInputTypes:l},(c,m)=>{s.EndedAt=new Date,m&&c?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(c)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const l=await this.ExecuteGQL(S,a);if(l&&l[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(l[n]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,d(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",i="";for(let l=0;l<t.KeyValuePairs.length;l++){const c=e.Fields.find(I=>I.Name.trim().toLowerCase()===t.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(l),R=c.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${c.CodeName}: ${R}!`,o.length>0&&(o+=", "),o+=`${c.CodeName}: $${c.CodeName}`,c.TSType===$.Number){if(isNaN(t.GetValueByIndex(l)))throw new Error(`Primary Key value ${m} (${c.Name}) is not a valid number`);a[c.CodeName]=parseInt(m)}else a[c.CodeName]=m}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=N(e.EntityInfo),g=new C,y=p`query Single${u}${n.length>0?"Full":""} (${i}) {
354
365
  ${u}(${o}) {
355
- ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
366
+ ${e.Fields.filter(l=>!l.EntityFieldInfo.IsBinaryFieldType).map(l=>l.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?l.CodeName.replace("__mj_","_mj__"):l.CodeName).join(`
356
367
  `)}
357
368
  ${n}
358
369
  }
359
370
  }
360
- `,I=await this.ExecuteGQL(m,a);return I&&I[u]?this.ConvertBackToMJFields(I[u]):null}catch(a){return l(a),null}}ConvertBackToMJFields(e){return new C().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
371
+ `,S=await this.ExecuteGQL(y,a);return S&&S[u]?this.ConvertBackToMJFields(S[u]):null}catch(a){return d(a),null}}ConvertBackToMJFields(e){return new C().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
361
372
  ${i} {
362
373
  ${o.Fields.map(n=>n.CodeName).join(`
363
374
  `)}
364
375
  }
365
- `}return r}async Delete(e,t,r){const s=new De;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",u="";for(let c of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(R=>R.Name.trim().toLowerCase()===c.FieldName.trim().toLowerCase());a[d.CodeName]=d.Value,o.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${d.CodeName}: $${d.CodeName}`,n.length>0&&(n+=", "),n+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
366
- `),u+=`${d.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const m="Delete"+N(e.EntityInfo),I=g`${m}(${i}, options___: $options___) {
376
+ `}return r}async Delete(e,t,r){const s=new De;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",u="";for(let c of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===c.FieldName.trim().toLowerCase());a[m.CodeName]=m.Value,o.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,n.length>0&&(n+=", "),n+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
377
+ `),u+=`${m.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const y="Delete"+N(e.EntityInfo),S=p`${y}(${i}, options___: $options___) {
367
378
  ${u}
368
379
  }
369
- `,y=g`mutation ${m} (${n}, $options___: DeleteOptionsInput!) {
370
- ${I}
380
+ `,l=p`mutation ${y} (${n}, $options___: DeleteOptionsInput!) {
381
+ ${S}
371
382
  }
372
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new we(e,"Delete",I,a,{mutationName:m,mutationInputTypes:o},(c,d)=>{if(s.EndedAt=new Date,d&&c){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==c[S.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const c=await this.ExecuteGQL(y,a);if(c&&c[m]){const d=c[m];for(let R of e.PrimaryKey.KeyValuePairs){let S=d[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof S=="number"&&(S=S.toString()),w!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,l(a),!1}}async GetDatasetByName(e,t){const r=g`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
383
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new we(e,"Delete",S,a,{mutationName:y,mutationInputTypes:o},(c,m)=>{if(s.EndedAt=new Date,m&&c){let R=!0;for(const I of e.PrimaryKey.KeyValuePairs)I.Value!==c[I.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const c=await this.ExecuteGQL(l,a);if(c&&c[y]){const m=c[y];for(let R of e.PrimaryKey.KeyValuePairs){let I=m[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof I=="number"&&(I=I.toString()),w!==I)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${I}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,d(a),!1}}async GetDatasetByName(e,t){const r=p`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
373
384
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
374
385
  DatasetID
375
386
  DatasetName
@@ -378,7 +389,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
378
389
  LatestUpdateDate
379
390
  Results
380
391
  }
381
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=g`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
392
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=p`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
382
393
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
383
394
  DatasetID
384
395
  DatasetName
@@ -387,22 +398,22 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
387
398
  LatestUpdateDate
388
399
  EntityUpdateDates
389
400
  }
390
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new T(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=g`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
401
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new A(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=p`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
391
402
  GetRecordFavoriteStatus(params: $params) {
392
403
  Success
393
404
  IsFavorite
394
405
  }
395
- }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(u=>u.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=g`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
406
+ }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(u=>u.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=p`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
396
407
  SetRecordFavoriteStatus(params: $params){
397
408
  Success
398
409
  }
399
- }`,n=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=g`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
410
+ }`,n=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=p`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
400
411
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
401
412
  Success
402
413
  Status
403
414
  RecordName
404
415
  }
405
- }`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=g`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
416
+ }`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=p`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
406
417
  GetEntityRecordNames(info: $info) {
407
418
  Success
408
419
  Status
@@ -415,35 +426,35 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
415
426
  EntityName
416
427
  RecordName
417
428
  }
418
- }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=g`query GetDataContextData ($DataContextID: String!) {
429
+ }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=p`query GetDataContextData ($DataContextID: String!) {
419
430
  GetDataContextData(DataContextID: $DataContextID) {
420
431
  Success
421
432
  ErrorMessages
422
433
  Results
423
434
  }
424
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}async GetDataContextItemData(e){try{const t=g`query GetDataContextItemData ($DataContextItemID: String!) {
435
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw d(t),t}}async GetDataContextItemData(e){try{const t=p`query GetDataContextItemData ($DataContextItemID: String!) {
425
436
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
426
437
  Success
427
438
  ErrorMessage
428
439
  Result
429
440
  }
430
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new Ie(e,{headers:a})}userInfoString(){return this.infoString(new Re(null,null))}userRoleInfoString(){return this.infoString(new Me(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
441
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw d(t),t}}static async ExecuteGQL(e,t,r=!0){return f.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){const e=f.Instance&&f.Instance._configData===this._configData;if(e&&f.Instance._refreshPromise)return f.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(f.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&f.Instance&&(f.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._client=t,f.Instance&&f.Instance._configData===this._configData&&(f.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return f.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new Ie(e,{headers:a})}userInfoString(){return this.infoString(new Re(null,null))}userRoleInfoString(){return this.infoString(new Te(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
431
442
  `:s.startsWith("_")||(t+=s+`
432
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new V),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=Le({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([a,o])=>{const i=e-o.lastRequestedAt,n=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),s.push(a))}),s.forEach(a=>{const o=this._pushStatusSubjects.get(a);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(a),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${a}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${a}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new x(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:o=>{r.next(o.data)},error:async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(o)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new x(n=>{r.activeSubscribers++;const u=r.subject.subscribe(n);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,u.unsubscribe()}});const s=g`subscription StatusUpdates($sessionId: String!) {
443
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new V),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=Le({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([a,o])=>{const i=e-o.lastRequestedAt,n=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),s.push(a))}),s.forEach(a=>{const o=this._pushStatusSubjects.get(a);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(a),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${a}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${a}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new x(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:o=>{r.next(o.data)},error:async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(o)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new x(n=>{r.activeSubscribers++;const u=r.subject.subscribe(n);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,u.unsubscribe()}});const s=p`subscription StatusUpdates($sessionId: String!) {
433
444
  statusUpdates(sessionId: $sessionId) {
434
445
  date
435
446
  message
436
447
  sessionId
437
448
  }
438
449
  }
439
- `,a=new Ue,o=this.getOrCreateWSClient(),i=new Ge;return i.add(new x(n=>{const u=o.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const m=this._pushStatusSubjects.get(e);m&&(m.lastEmissionAt=Date.now()),n.next(p.data.statusUpdates.message)},error:async p=>{const m=p;if(m?.extensions?.code==="JWT_EXPIRED"||m?.message?.includes("token has expired")||m?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),n.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),n.error(y)}}else n.error(p)},complete:()=>{n.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:n=>a.next(n),error:n=>{a.error(n),this._pushStatusSubjects.delete(e)},complete:()=>{a.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:a,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new x(n=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const p=a.subscribe(n);return()=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers>0&&m.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};f(h,"GraphQLDataProvider");let Q=h;async function Je(D){const e=new Q;return Ve(e),await e.Config(D),await Qe.Instance.Startup(),qe.Instance.RaiseEvent({event:Oe.LoggedIn,eventCode:null,component:this,args:null}),e}f(Je,"setupGraphQLClient");const ae=class ae{};f(ae,"SyncRolesAndUsersResult");let U=ae;const ne=class ne{};f(ne,"RoleInput");let G=ne;const oe=class oe{};f(oe,"UserInput");let L=oe;const ie=class ie{};f(ie,"RolesAndUsersInput");let _=ie;var ve=(D=>(D.Create="Create",D.Update="Update",D.CreateOrUpdate="CreateOrUpdate",D.Delete="Delete",D.DeleteWithFilter="DeleteWithFilter",D))(ve||{});const ue=class ue{};f(ue,"ActionItemInput");let q=ue;const ce=class ce{constructor(){this.Results=[]}};f(ce,"SyncDataResult");let O=ce;const le=class le{};f(le,"ActionItemOutput");let k=le;const de=class de{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new Ie(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
450
+ `,a=new Ue,o=this.getOrCreateWSClient(),i=new Ge;return i.add(new x(n=>{const u=o.subscribe({query:s,variables:{sessionId:e}},{next:g=>{const y=this._pushStatusSubjects.get(e);y&&(y.lastEmissionAt=Date.now()),n.next(g.data.statusUpdates.message)},error:async g=>{const y=g;if(y?.extensions?.code==="JWT_EXPIRED"||y?.message?.includes("token has expired")||y?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),n.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",l),n.error(l)}}else n.error(g)},complete:()=>{n.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:n=>a.next(n),error:n=>{a.error(n),this._pushStatusSubjects.delete(e)},complete:()=>{a.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:a,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new x(n=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const g=a.subscribe(n);return()=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers>0&&y.activeSubscribers--,g.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};h(f,"GraphQLDataProvider");let F=f;async function Je(D){const e=new F;return Ve(e),await e.Config(D),await Fe.Instance.Startup(),qe.Instance.RaiseEvent({event:Oe.LoggedIn,eventCode:null,component:this,args:null}),e}h(Je,"setupGraphQLClient");const ae=class ae{};h(ae,"SyncRolesAndUsersResult");let U=ae;const ne=class ne{};h(ne,"RoleInput");let G=ne;const oe=class oe{};h(oe,"UserInput");let L=oe;const ie=class ie{};h(ie,"RolesAndUsersInput");let _=ie;var Pe=(D=>(D.Create="Create",D.Update="Update",D.CreateOrUpdate="CreateOrUpdate",D.Delete="Delete",D.DeleteWithFilter="DeleteWithFilter",D))(Pe||{});const ue=class ue{};h(ue,"ActionItemInput");let q=ue;const ce=class ce{constructor(){this.Results=[]}};h(ce,"SyncDataResult");let O=ce;const le=class le{};h(le,"ActionItemOutput");let k=le;const de=class de{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new Ie(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
440
451
  GetData(input: $input) {
441
452
  Success
442
453
  ErrorMessages
443
454
  Queries
444
455
  Results
445
456
  }
446
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?P(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),Fe()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;l(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
457
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?v(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),Qe()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;d(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
447
458
  GetAllEntities {
448
459
  Success
449
460
  ErrorMessage
@@ -466,7 +477,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
466
477
  }
467
478
  }
468
479
  }
469
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return l(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
480
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return d(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
470
481
  SyncData(items: $items) {
471
482
  Success
472
483
  Results {
@@ -490,11 +501,11 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
490
501
  RecordJSON
491
502
  }
492
503
  }
493
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return l(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
504
+ }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return d(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
494
505
  SyncRolesAndUsers(data: $data) {
495
506
  Success
496
507
  }
497
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return l(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
508
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return d(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
498
509
  RunViewByNameSystemUser(input: $input) {
499
510
  Results {
500
511
  PrimaryKey {
@@ -511,7 +522,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
511
522
  ErrorMessage
512
523
  Success
513
524
  }
514
- }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return l(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
525
+ }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return d(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
515
526
  RunViewByIDSystemUser(input: $input) {
516
527
  Results {
517
528
  PrimaryKey {
@@ -528,7 +539,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
528
539
  ErrorMessage
529
540
  Success
530
541
  }
531
- }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return l(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
542
+ }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return d(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
532
543
  RunDynamicViewSystemUser(input: $input) {
533
544
  Results {
534
545
  PrimaryKey {
@@ -545,7 +556,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
545
556
  ErrorMessage
546
557
  Success
547
558
  }
548
- }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return l(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
559
+ }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return d(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
549
560
  RunViewsSystemUser(input: $input) {
550
561
  Results {
551
562
  PrimaryKey {
@@ -562,7 +573,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
562
573
  ErrorMessage
563
574
  Success
564
575
  }
565
- }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return l(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
576
+ }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return d(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
566
577
  GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
567
578
  QueryID
568
579
  QueryName
@@ -574,7 +585,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
574
585
  ErrorMessage
575
586
  AppliedParameters
576
587
  }
577
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?P(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
588
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?v(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return d(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
578
589
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
579
590
  QueryID
580
591
  QueryName
@@ -586,7 +597,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
586
597
  ErrorMessage
587
598
  AppliedParameters
588
599
  }
589
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?P(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
600
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?v(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return d(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
590
601
  CreateQuerySystemUser(input: $input) {
591
602
  Success
592
603
  ErrorMessage
@@ -641,7 +652,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
641
652
  Role
642
653
  }
643
654
  }
644
- }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return l(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
655
+ }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return d(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
645
656
  UpdateQuerySystemUser(input: $input) {
646
657
  Success
647
658
  ErrorMessage
@@ -696,14 +707,14 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
696
707
  Role
697
708
  }
698
709
  }
699
- }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return l(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return l("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
710
+ }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return d(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return d("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
700
711
  DeleteQuerySystemResolver(ID: $ID, options: $options) {
701
712
  Success
702
713
  ErrorMessage
703
714
  ID
704
715
  Name
705
716
  }
706
- }`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return l(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=g`
717
+ }`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return d(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=p`
707
718
  query RunAIPromptSystemUser(
708
719
  $promptId: String!,
709
720
  $data: String,
@@ -762,7 +773,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
762
773
  chatResult
763
774
  }
764
775
  }
765
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return l(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=g`
776
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return d(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=p`
766
777
  query RunAIAgentSystemUser(
767
778
  $agentId: String!,
768
779
  $messages: String!,
@@ -789,7 +800,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
789
800
  result
790
801
  }
791
802
  }
792
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return l(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return P(e)}async ExecuteSimplePrompt(e){try{const t=g`
803
+ `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return d(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return v(e)}async ExecuteSimplePrompt(e){try{const t=p`
793
804
  query ExecuteSimplePromptSystemUser(
794
805
  $systemPrompt: String!,
795
806
  $messages: String,
@@ -812,7 +823,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
812
823
  executionTimeMs
813
824
  }
814
825
  }
815
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return l(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=g`
826
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return d(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=p`
816
827
  query EmbedTextSystemUser(
817
828
  $textToEmbed: [String!]!,
818
829
  $modelSize: String!
@@ -827,7 +838,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
827
838
  error
828
839
  }
829
840
  }
830
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return l(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(de,"GraphQLSystemUserClient");let B=de;const ye=class ye{};f(ye,"GetDataOutput");let K=ye;const me=class me{};f(me,"SimpleRemoteEntityOutput");let J=me;const ge=class ge{};f(ge,"SimpleRemoteEntity");let j=ge;const pe=class pe{};f(pe,"SimpleRemoteEntityField");let W=pe;const he=class he{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=g`
841
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return d(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};h(de,"GraphQLSystemUserClient");let B=de;const ye=class ye{};h(ye,"GetDataOutput");let K=ye;const me=class me{};h(me,"SimpleRemoteEntityOutput");let J=me;const ge=class ge{};h(ge,"SimpleRemoteEntity");let j=ge;const pe=class pe{};h(pe,"SimpleRemoteEntityField");let W=pe;const fe=class fe{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=p`
831
842
  mutation RunAction($input: RunActionInput!) {
832
843
  RunAction(input: $input) {
833
844
  Success
@@ -836,7 +847,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
836
847
  ResultData
837
848
  }
838
849
  }
839
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){l(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return l(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=g`
850
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){d(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return d(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=p`
840
851
  mutation RunEntityAction($input: EntityActionInput!) {
841
852
  RunEntityAction(input: $input) {
842
853
  Success
@@ -844,18 +855,20 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
844
855
  ResultData
845
856
  }
846
857
  }
847
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){l(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(he,"GraphQLActionClient");let z=he;const fe=class fe{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(i=>{try{const n=JSON.parse(i);n.resolver==="RunTestResolver"&&n.type==="TestExecutionProgress"&&n.status==="ok"&&n.data?.progress&&e.onProgress(n.data.progress)}catch(n){console.error("[GraphQLTestingClient] Failed to parse progress message:",n)}}));const r=g`
858
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){d(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};h(fe,"GraphQLActionClient");let z=fe;const he=class he{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{const u=JSON.parse(n);u.resolver==="RunTestResolver"&&u.type==="TestExecutionProgress"&&u.status==="ok"&&u.data?.progress&&e.onProgress(u.data.progress)}catch(u){console.error("[GraphQLTestingClient] Failed to parse progress message:",u)}}));const r=p`
848
859
  mutation RunTest(
849
860
  $testId: String!,
850
861
  $verbose: Boolean,
851
862
  $environment: String,
852
- $tags: String
863
+ $tags: String,
864
+ $variables: String
853
865
  ) {
854
866
  RunTest(
855
867
  testId: $testId,
856
868
  verbose: $verbose,
857
869
  environment: $environment,
858
- tags: $tags
870
+ tags: $tags,
871
+ variables: $variables
859
872
  ) {
860
873
  success
861
874
  errorMessage
@@ -863,13 +876,14 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
863
876
  result
864
877
  }
865
878
  }
866
- `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s},o=await this._dataProvider.ExecuteGQL(r,a);return this.processTestResult(o.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{const u=JSON.parse(n);u.resolver==="RunTestResolver"&&u.type==="TestExecutionProgress"&&u.status==="ok"&&u.data?.progress&&e.onProgress(u.data.progress)}catch(u){console.error("[GraphQLTestingClient] Failed to parse progress message:",u)}}));const r=g`
879
+ `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,o={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s,variables:a},i=await this._dataProvider.ExecuteGQL(r,o);return this.processTestResult(i.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(u=>{try{const g=JSON.parse(u);g.resolver==="RunTestResolver"&&g.type==="TestExecutionProgress"&&g.status==="ok"&&g.data?.progress&&e.onProgress(g.data.progress)}catch(g){console.error("[GraphQLTestingClient] Failed to parse progress message:",g)}}));const r=p`
867
880
  mutation RunTestSuite(
868
881
  $suiteId: String!,
869
882
  $verbose: Boolean,
870
883
  $environment: String,
871
884
  $parallel: Boolean,
872
885
  $tags: String,
886
+ $variables: String,
873
887
  $selectedTestIds: String,
874
888
  $sequenceStart: Int,
875
889
  $sequenceEnd: Int
@@ -880,6 +894,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
880
894
  environment: $environment,
881
895
  parallel: $parallel,
882
896
  tags: $tags,
897
+ variables: $variables,
883
898
  selectedTestIds: $selectedTestIds,
884
899
  sequenceStart: $sequenceStart,
885
900
  sequenceEnd: $sequenceEnd
@@ -890,11 +905,11 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
890
905
  result
891
906
  }
892
907
  }
893
- `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,o={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,selectedTestIds:a,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},i=await this._dataProvider.ExecuteGQL(r,o);return this.processSuiteResult(i.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=g`
908
+ `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,o=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,i={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,variables:a,selectedTestIds:o,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},n=await this._dataProvider.ExecuteGQL(r,i);return this.processSuiteResult(n.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=p`
894
909
  query IsTestRunning($testId: String!) {
895
910
  IsTestRunning(testId: $testId)
896
911
  }
897
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return l(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=P(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=P(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return l(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};f(fe,"GraphQLTestingClient");let H=fe;const Se=class Se{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=g`
912
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return d(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=v(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=v(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return d(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};h(he,"GraphQLTestingClient");let H=he;const Se=class Se{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=p`
898
913
  query GetRegistryComponent(
899
914
  $registryName: String!,
900
915
  $namespace: String!,
@@ -915,7 +930,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
915
930
  specification
916
931
  }
917
932
  }
918
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(o){return l(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw l(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=g`
933
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(o){return d(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw d(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=p`
919
934
  query GetRegistryComponent(
920
935
  $registryName: String!,
921
936
  $namespace: String!,
@@ -936,7 +951,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
936
951
  specification
937
952
  }
938
953
  }
939
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let o;if(a.specification)try{o=JSON.parse(a.specification)}catch(i){l(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw l(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=g`
954
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let o;if(a.specification)try{o=JSON.parse(a.specification)}catch(i){d(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw d(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=p`
940
955
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
941
956
  SearchRegistryComponents(params: $params) {
942
957
  components
@@ -945,7 +960,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
945
960
  limit
946
961
  }
947
962
  }
948
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw l(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=g`
963
+ `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw d(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=p`
949
964
  query ResolveComponentDependencies(
950
965
  $registryId: String!,
951
966
  $componentId: String!
@@ -970,7 +985,7 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
970
985
  }
971
986
  }
972
987
  }
973
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw l(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return l(s),null}}async SendComponentFeedback(e){try{const t=g`
988
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw d(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return d(s),null}}async SendComponentFeedback(e){try{const t=p`
974
989
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
975
990
  SendComponentFeedback(feedback: $feedback) {
976
991
  success
@@ -978,5 +993,5 @@ var Ce=Object.defineProperty;var f=(D,e)=>Ce(D,"name",{value:e,configurable:!0})
978
993
  error
979
994
  }
980
995
  }
981
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(Se,"GraphQLComponentRegistryClient");let X=Se;export{q as ActionItemInput,k as ActionItemOutput,V as BrowserIndexedDBStorageProvider,M as BrowserStorageProviderBase,C as FieldMapper,K as GetDataOutput,A as GraphQLAIClient,z as GraphQLActionClient,X as GraphQLComponentRegistryClient,Q as GraphQLDataProvider,F as GraphQLProviderConfigData,B as GraphQLSystemUserClient,H as GraphQLTestingClient,T as GraphQLTransactionGroup,G as RoleInput,_ as RolesAndUsersInput,j as SimpleRemoteEntity,W as SimpleRemoteEntityField,J as SimpleRemoteEntityOutput,ve as SyncDataAction,O as SyncDataResult,U as SyncRolesAndUsersResult,L as UserInput,at as gql,Je as setupGraphQLClient};
996
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};h(Se,"GraphQLComponentRegistryClient");let X=Se;export{q as ActionItemInput,k as ActionItemOutput,V as BrowserIndexedDBStorageProvider,T as BrowserStorageProviderBase,C as FieldMapper,K as GetDataOutput,M as GraphQLAIClient,z as GraphQLActionClient,X as GraphQLComponentRegistryClient,F as GraphQLDataProvider,Q as GraphQLProviderConfigData,B as GraphQLSystemUserClient,H as GraphQLTestingClient,A as GraphQLTransactionGroup,G as RoleInput,_ as RolesAndUsersInput,j as SimpleRemoteEntity,W as SimpleRemoteEntityField,J as SimpleRemoteEntityOutput,Pe as SyncDataAction,O as SyncDataResult,U as SyncRolesAndUsersResult,L as UserInput,at as gql,Je as setupGraphQLClient};
982
997
  //# sourceMappingURL=index.mjs.map