@memberjunction/graphql-dataprovider 5.8.0 → 5.9.0

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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var V=Object.defineProperty;var p=(h,e)=>V(h,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),w=require("@memberjunction/global"),b=require("@memberjunction/core-entities"),$=require("rxjs"),G=require("graphql-ws"),q=require("uuid"),_=require("@tempfix/idb");class A{static{p(this,"FieldMapper")}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}}class x extends u.TransactionGroupBase{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
1
+ "use strict";var V=Object.defineProperty;var g=(h,e)=>V(h,"name",{value:e,configurable:!0});var d=require("graphql-request"),u=require("@memberjunction/core"),v=require("@memberjunction/global"),N=require("@memberjunction/core-entities"),b=require("rxjs"),G=require("graphql-ws"),q=require("uuid"),_=require("@tempfix/idb");class w{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const s=this.MapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(w.DB_PREFIX)?w.GQL_PREFIX+e.substring(w.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(w.GQL_PREFIX)?w.DB_PREFIX+e.substring(w.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const s=this.ReverseMapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}}class x extends u.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=d.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],c=w.SafeJSONParse(a),d=this.PendingTransactions[i];o.push(new u.TransactionResult(d,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class P{static{p(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:o,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,o,s);const a=await P.executeMutation(e);if(!e.validateAck(a)){s&&clearTimeout(s);const c=a?.errorMessage??"Server rejected the request";return u.LogError(`[FireAndForget:${t}] Server rejected: ${c}`),e.createErrorResult(c)}return u.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const o=n;throw u.LogError(`[FireAndForget:${t}] Error: ${o.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(o=>{try{const i=JSON.parse(o);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),u.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class L{static{p(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.gql`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const s={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},r=await this._provider.ExecuteGQL(e,s);if(r&&r.ExecuteTransactionGroup){const n=r.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],c=v.SafeJSONParse(a),l=this.PendingTransactions[i];o.push(new u.TransactionResult(l,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class ${static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let s,r;try{const{promise:n,resolve:o,reject:i}=$.createCompletionPromise();r=$.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),s=$.subscribeToPubSub(e,o,r);const a=await $.executeMutation(e);if(!e.validateAck(a)){r&&clearTimeout(r);const c=a?.errorMessage??"Server rejected the request";return u.LogError(`[FireAndForget:${t}] Server rejected: ${c}`),e.createErrorResult(c)}return u.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){r&&clearTimeout(r);const o=n;throw u.LogError(`[FireAndForget:${t}] Error: ${o.message}`),n}finally{r&&clearTimeout(r),s&&s.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,s){const r=t??O,n=s??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},r)}static subscribeToPubSub(e,t,s){const r=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe(o=>{try{const i=JSON.parse(o);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(s),u.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class L{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=d.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@
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,n;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&&(n=JSON.parse(t.chatResult))}catch{n=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:n}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:p(o=>o?.success===!0,"validateAck"),isCompletionEvent:p(o=>this.isAgentCompletionEvent(o),"isCompletionEvent"),extractResult:p(o=>this.extractAgentResult(o),"extractResult"),onMessage:e.onProgress?o=>this.forwardAgentProgress(o,e.onProgress):void 0,createErrorResult:p(o=>this.createAgentErrorResult(o),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return y.gql`
68
+ `,s=this.preparePromptVariables(e),r=await this._dataProvider.ExecuteGQL(t,s);return this.processPromptResult(r)}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 s,r,n;try{t.parsedResult&&(s=JSON.parse(t.parsedResult))}catch{s=t.parsedResult}try{t.validationResult&&(r=JSON.parse(t.validationResult))}catch{r=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:s,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:r,chatResult:n}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,s){try{const r=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,s);return n.fireAndForget=!0,await $.Execute({dataProvider:this._dataProvider,mutation:r,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:g(o=>o?.success===!0,"validateAck"),isCompletionEvent:g(o=>this.isAgentCompletionEvent(o),"isCompletionEvent"),extractResult:g(o=>this.extractAgentResult(o),"extractResult"),onMessage:e.onProgress?o=>this.forwardAgentProgress(o,e.onProgress):void 0,createErrorResult:g(o=>this.createAgentErrorResult(o),"createErrorResult")})}catch(r){return this.handleAgentError(r)}}buildRunAIAgentMutation(){return d.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -106,7 +106,7 @@
106
106
  result
107
107
  }
108
108
  }
109
- `}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 w.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);u.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let o;return s?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=r,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:p(s=>s?.success===!0,"validateAck"),isCompletionEvent:p(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:p(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,createErrorResult:p(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return y.gql`
109
+ `}prepareAgentVariables(e,t,s){const r={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(r.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(r.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(r.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(r.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(r.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(r.conversationDetailId=e.conversationDetailId,r.createArtifacts=!0,r.createNotification=!0),t!==void 0&&(r.sourceArtifactId=t),s!==void 0&&(r.sourceArtifactVersionId=s),r}processAgentResult(e){return v.SafeJSONParse(e)}handleAgentError(e){const s=e?.message||String(e);u.LogError(`Error running AI agent: ${s}`);const r=s.includes("Failed to fetch")||s.includes("NetworkError"),n=s.includes("timed out")||s.includes("timeout");let o;return r?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=s,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isConversationDetailCompletionEvent(r,e.conversationDetailId),"isCompletionEvent"),extractResult:g(r=>this.extractAgentResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardConversationDetailProgress(r,e.onProgress):void 0,createErrorResult:g(r=>this.createAgentErrorResult(r),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return d.gql`
110
110
  mutation RunAIAgentFromConversationDetail(
111
111
  $conversationDetailId: String!,
112
112
  $agentId: String!,
@@ -145,7 +145,7 @@
145
145
  result
146
146
  }
147
147
  }
148
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?w.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=y.gql`
148
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const s=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&s?.type==="complete"&&s?.conversationDetailId===t}extractAgentResult(e){const t=e.data,s=t.result;return s?v.SafeJSONParse(s):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data,r=s?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:{...r,agentRun:s?.agentRun,agentRunId:s?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=d.gql`
149
149
  mutation ExecuteSimplePrompt(
150
150
  $systemPrompt: String!,
151
151
  $messages: String,
@@ -168,7 +168,7 @@
168
168
  executionTimeMs
169
169
  }
170
170
  }
171
- `,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 n=s.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=y.gql`
171
+ `,s={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(s.messages=JSON.stringify(e.messages)),e.preferredModels&&(s.preferredModels=e.preferredModels),e.modelPower&&(s.modelPower=e.modelPower),e.responseFormat&&(s.responseFormat=e.responseFormat);const r=await this._dataProvider.ExecuteGQL(t,s);if(!r?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=r.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const s=t;return u.LogError(`Error executing simple prompt: ${s}`),{success:!1,modelName:"Unknown",error:s.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=d.gql`
172
172
  mutation EmbedText(
173
173
  $textToEmbed: [String!]!,
174
174
  $modelSize: String!
@@ -183,15 +183,15 @@
183
183
  error
184
184
  }
185
185
  }
186
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.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 u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const C="default";class T{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||C;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||C).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||C).set(e,t)}async Remove(e,t){this.getCategoryMap(t||C).delete(e)}async ClearCategory(e){const t=e||C;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||C);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class Q extends T{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||C;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||C;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){u.LogErrorEx({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),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||C,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||C,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const a=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends u.ProviderConfigDataBase{static{p(this,"GraphQLProviderConfigData")}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 UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,o,i,a,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:s},n,o,i)}}class f extends u.ProviderBase{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
186
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,r);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const s=t;return u.LogError(`Error generating embeddings: ${s}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:s.message||"Unknown error occurred"}}}}const P="default";class T{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||P;let s=this._storage.get(t);return s||(s=new Map,this._storage.set(t,s)),s}async GetItem(e,t){return this.getCategoryMap(t||P).get(e)??null}async SetItem(e,t,s){this.getCategoryMap(s||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class Q extends T{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const s=t||P;return this.isKnownCategory(s)?e:`[${s}]:${e}`}async SetItem(e,t,s){try{const r=await this.dbPromise,n=this.getStoreName(s),o=this.getStoreKey(e,s),i=r.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.SetItem(e,t,s)}}async GetItem(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t);return await s.transaction(r).objectStore(r).get(n)??null}catch(s){return u.LogErrorEx({error:s,message:s?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t),o=s.transaction(r,"readwrite");await o.objectStore(r).delete(n),await o.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,s=e||P,r=this.getStoreName(e);if(this.isKnownCategory(s)){const n=t.transaction(r,"readwrite");await n.objectStore(r).clear(),await n.done}else{const n=`[${s}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,s=e||P,r=this.getStoreName(e),i=await t.transaction(r,"readonly").objectStore(r).getAllKeys();if(this.isKnownCategory(s))return i.map(c=>String(c));const a=`[${s}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends u.ProviderConfigDataBase{static{g(this,"GraphQLProviderConfigData")}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 UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,s,r,n,o,i,a,c){super({Token:e,URL:t,WSURL:s,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:r},n,o,i)}}class f extends u.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
187
187
  ${this.userInfoString()}
188
188
  MJUserRoles_UserIDArray {
189
189
  ${this.userRoleInfoString()}
190
190
  }
191
191
  }
192
- `,this._currentUserQuery=y.gql`query CurrentUserAndRoles {
192
+ `,this._currentUserQuery=d.gql`query CurrentUserAndRoles {
193
193
  ${this._innerCurrentUserQueryString}
194
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*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 L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}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,e.UserAPIKey),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,e.UserAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}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.MJUserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.MJUserRoles_UserIDArray=r,new u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=y.gql`
194
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null,f._instance||(f._instance=this)}static get Instance(){return f._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}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 s=this.LocalStoragePrefix+"sessionId";await t.SetItem(s,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,s,r){try{return this._configData=e,s?(this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(f.Instance._configData=e,f.Instance._sessionId===void 0&&(f.Instance._sessionId=await this.GetPreferredUUID(r)),f.Instance._client||(f.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,f.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}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),s=t.MJUserRoles_UserIDArray.map(r=>this.ConvertBackToMJFields(r));return t.MJUserRoles_UserIDArray=s,new u.UserInfo(this,{...t,UserRoles:s})}}async RunReport(e,t){const s=d.gql`
195
195
  query GetReportDataQuery ($ReportID: String!) {
196
196
  GetReportData(ReportID: $ReportID) {
197
197
  Success
@@ -200,31 +200,31 @@
200
200
  ExecutionTime
201
201
  ErrorMessage
202
202
  }
203
- }`,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.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);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 SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r){const s=y.gql`
203
+ }`,r=await this.ExecuteGQL(s,{ReportID:e.ReportID});if(r&&r.GetReportData)return{ReportID:e.ReportID,Success:r.GetReportData.Success,Results:JSON.parse(r.GetReportData.Results),RowCount:r.GetReportData.RowCount,ExecutionTime:r.GetReportData.ExecutionTime,ErrorMessage:r.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);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 SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,s){const r=d.gql`
204
204
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
205
205
  ExecuteAdhocQuery(input: $input) {
206
206
  ${this.QueryReturnFieldList}
207
207
  }
208
208
  }
209
- `,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const o=await this.ExecuteGQL(s,{input:n});return o?.ExecuteAdhocQuery?this.TransformQueryPayload(o.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=y.gql`
209
+ `,n={SQL:e};s!==void 0&&(n.TimeoutSeconds=s);const o=await this.ExecuteGQL(r,{input:n});return o?.ExecuteAdhocQuery?this.TransformQueryPayload(o.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const s=d.gql`
210
210
  query RunQueriesBatch($input: [RunQueryInput!]!) {
211
211
  RunQueries(input: $input) {
212
212
  ${this.QueryReturnFieldList}
213
213
  }
214
214
  }
215
- `,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})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i){const a=y.gql`
215
+ `,r=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})),n=await this.ExecuteGQL(s,{input:r});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,s,r,n,o,i){const a=d.gql`
216
216
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
217
217
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
218
218
  ${this.QueryReturnFieldList}
219
219
  }
220
220
  }
221
- `,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const d=await this.ExecuteGQL(a,c);if(d&&d.GetQueryData)return this.TransformQueryPayload(d.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i){const a=y.gql`
221
+ `,c={QueryID:e};t!==void 0&&(c.CategoryID=t),s!==void 0&&(c.CategoryPath=s),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const l=await this.ExecuteGQL(a,c);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,s,r,n,o,i){const a=d.gql`
222
222
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
223
223
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
224
224
  ${this.QueryReturnFieldList}
225
225
  }
226
226
  }
227
- `,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const d=await this.ExecuteGQL(a,c);if(d&&d.GetQueryDataByName)return this.TransformQueryPayload(d.GetQueryDataByName)}get QueryReturnFieldList(){return`
227
+ `,c={QueryName:e};t!==void 0&&(c.CategoryID=t),s!==void 0&&(c.CategoryPath=s),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const l=await this.ExecuteGQL(a,c);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
228
228
  Success
229
229
  QueryID
230
230
  QueryName
@@ -233,7 +233,7 @@
233
233
  TotalRowCount
234
234
  ExecutionTime
235
235
  ErrorMessage
236
- 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 u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=y.gql`
236
+ 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 u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const s=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),r=d.gql`
237
237
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
238
238
  RunQueriesWithCacheCheck(input: $input) {
239
239
  success
@@ -249,16 +249,16 @@
249
249
  }
250
250
  }
251
251
  }
252
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const c=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:c,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(`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 n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:m,v:I}=await this.getEntityNameAndUserView(e,t);i=I,o=m}const a=this.Entities.find(m=>m.Name===o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const d=u.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${d}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${d}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(m=>({expression:m.expression,alias:m.alias})));const S=this.getViewRunTimeFieldList(a,i,e,c),R=e.Aggregates&&e.Aggregates.length>0?`
252
+ `,o=(await this.ExecuteGQL(r,{input:s}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const c=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:c,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(s){return u.LogError(`Error in RunQueriesWithCacheCheck: ${s}`),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async InternalRunView(e,t){try{let s="",r="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:p,v:I}=await this.getEntityNameAndUserView(e,t);i=I,o=p}const a=this.Entities.find(p=>p.Name===o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const l=u.getGraphQLTypeNameBase(a);e.ViewID?(s=`Run${l}ViewByID`,r="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(s=`Run${l}ViewByName`,r="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,s=`Run${l}DynamicView`,r="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const S=this.getViewRunTimeFieldList(a,i,e,c),E=e.Aggregates&&e.Aggregates.length>0?`
253
253
  AggregateResults {
254
254
  alias
255
255
  expression
256
256
  value
257
257
  error
258
258
  }
259
- AggregateExecutionTime`:"",l=y.gql`
260
- query RunViewQuery ($input: ${s}!) {
261
- ${r}(input: $input) {
259
+ AggregateExecutionTime`:"",y=d.gql`
260
+ query RunViewQuery ($input: ${r}!) {
261
+ ${s}(input: $input) {
262
262
  Results {
263
263
  ${S.join(`
264
264
  `)}
@@ -268,16 +268,16 @@
268
268
  TotalRowCount
269
269
  ExecutionTime
270
270
  Success
271
- ErrorMessage${R}
271
+ ErrorMessage${E}
272
272
  }
273
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(l,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const I=g[r].Results;if(I&&I.length>0){const v=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),v.forEach(N=>{D[N.Name]=D[N.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let S="",R="";const l={};let g=null,m=null;if(d.ViewEntity)m=d.ViewEntity,g=m.Get("Entity");else{const{entityName:D,v:N}=await this.getEntityNameAndUserView(d,t);m=N,g=D}const I=this.Entities.find(D=>D.Name===g);if(!I)throw new Error(`Entity ${g} not found in metadata`);s.push(I);let E=!1;const v=u.getGraphQLTypeNameBase(I);d.ViewID?(S=`Run${v}ViewByID`,R="RunViewByIDInput",l.ViewID=d.ViewID):d.ViewName?(S=`Run${v}ViewByName`,R="RunViewByNameInput",l.ViewName=d.ViewName):(E=!0,S=`Run${v}DynamicView`,R="RunDynamicViewInput",l.EntityName=d.EntityName),l.ExtraFilter=d.ExtraFilter||"",l.OrderBy=d.OrderBy||"",l.UserSearchString=d.UserSearchString||"",l.Fields=d.Fields,l.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(l.MaxRows=d.MaxRows),d.StartRow!==void 0&&(l.StartRow=d.StartRow),l.ForceAuditLog=d.ForceAuditLog||!1,l.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(l.AuditLogDescription=d.AuditLogDescription),E||(l.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",l.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,l.OverrideExcludeFilter=d.OverrideExcludeFilter||"",l.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(l.Aggregates=d.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(l),n.push(...this.getViewRunTimeFieldList(I,m,d,E))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
273
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:s,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[s]){const p=m[s].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[s].AggregateExecutionTime});const I=m[s].Results;if(I&&I.length>0){const C=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),C.forEach(A=>{D[A.Name]=D[A.CodeName]})})}return m[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw u.LogError(s),s}}async InternalRunViews(e,t){try{let s=[],r=[],n=[];for(const l of e){let S="",E="";const y={};let m=null,p=null;if(l.ViewEntity)p=l.ViewEntity,m=p.Get("Entity");else{const{entityName:D,v:A}=await this.getEntityNameAndUserView(l,t);p=A,m=D}const I=this.Entities.find(D=>D.Name===m);if(!I)throw new Error(`Entity ${m} not found in metadata`);r.push(I);let R=!1;const C=u.getGraphQLTypeNameBase(I);l.ViewID?(S=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=l.ViewID):l.ViewName?(S=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=l.ViewName):(R=!0,S=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=l.EntityName),y.ExtraFilter=l.ExtraFilter||"",y.OrderBy=l.OrderBy||"",y.UserSearchString=l.UserSearchString||"",y.Fields=l.Fields,y.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(y.MaxRows=l.MaxRows),l.StartRow!==void 0&&(y.StartRow=l.StartRow),y.ForceAuditLog=l.ForceAuditLog||!1,y.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(y.AuditLogDescription=l.AuditLogDescription),R||(y.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=l.OverrideExcludeFilter||"",y.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(y.Aggregates=l.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),s.push(y),n.push(...this.getViewRunTimeFieldList(I,p,l,R))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
274
274
  AggregateResults {
275
275
  alias
276
276
  expression
277
277
  value
278
278
  error
279
279
  }
280
- AggregateExecutionTime`:"",a=y.gql`
280
+ AggregateExecutionTime`:"",a=d.gql`
281
281
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
282
282
  RunViews(input: $input) {
283
283
  Results {
@@ -295,7 +295,7 @@
295
295
  Success
296
296
  ErrorMessage${i}
297
297
  }
298
- }`,c=await this.ExecuteGQL(a,{input:r});if(c&&c.RunViews){const d=c.RunViews;for(const[S,R]of d.entries())R.Results=R.Results.map(l=>{let g=JSON.parse(l.Data);return this.ConvertBackToMJFields(g),g});return d}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=y.gql`
298
+ }`,c=await this.ExecuteGQL(a,{input:s});if(c&&c.RunViews){const l=c.RunViews;for(const[S,E]of l.entries())E.Results=E.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return l}return null}catch(s){throw u.LogError(s),s}}async RunViewsWithCacheCheck(e,t){try{const s=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),r=d.gql`
299
299
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
300
300
  RunViewsWithCacheCheck(input: $input) {
301
301
  success
@@ -328,7 +328,7 @@
328
328
  }
329
329
  }
330
330
  }
331
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,c)=>{const d=e[c];if(a.status==="differential"&&a.differentialData){const S=a.differentialData.updatedRows.map(R=>{const l=JSON.parse(R.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:S,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const S=a.Results.map(R=>{const l=JSON.parse(R.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:a.viewIndex,status:a.status,results:S,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(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 b.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await b.ViewInfo.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 n=[],o=new A;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(o.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
331
+ `,o=(await this.ExecuteGQL(r,{input:s}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,c)=>{const l=e[c];if(a.status==="differential"&&a.differentialData){const S=a.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:S,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const S=a.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:S,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(s){return u.LogError(s),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async getEntityNameAndUserView(e,t){let s,r;if(e.EntityName)s=e.EntityName;else if(e.ViewID)r=await N.ViewInfo.GetViewEntity(e.ViewID,t),s=r.Entity;else if(e.ViewName)r=await N.ViewInfo.GetViewEntityByName(e.ViewName,t),s=r.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:r}}getViewRunTimeFieldList(e,t,s,r){const n=[],o=new w;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);s.Fields.forEach(i=>{n.push(o.MapFieldName(i))})}else if(r)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(o.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const s={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},r=await this.RunView(s);return r?r.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(s){throw u.LogError(s),s}}async GetRecordDependencies(e,t){try{const s=d.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
332
332
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
333
333
  EntityName
334
334
  RelatedEntityName
@@ -340,7 +340,7 @@
340
340
  }
341
341
  }
342
342
  }
343
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(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=y.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
343
+ }`,r={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(s,r))?.GetRecordDependencies}catch(s){throw u.LogError(s),s}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const s=d.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
344
344
  GetRecordDuplicates(params: $params) {
345
345
  Status
346
346
  ErrorMessage
@@ -362,7 +362,7 @@
362
362
  }
363
363
  }
364
364
  }
365
- }`;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 n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.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 n=y.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
365
+ }`;let r={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const n=await this.ExecuteGQL(s,{params:r});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,s){const r=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!r||!r.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=d.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
366
366
  MergeRecords(request: $request) {
367
367
  Success
368
368
  OverallStatus
@@ -379,32 +379,32 @@
379
379
  Message
380
380
  }
381
381
  }
382
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={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=u.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,c=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),d=new A,S=` ${a}(input: $input) {
383
- ${e.Fields.map(l=>d.MapFieldName(l.CodeName)).join(`
382
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,s){if(s?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const r=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";r.StartedAt=new Date,r.Type=e.IsSaved?"update":"create",r.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(r);const i=u.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),l=new w,S=` ${a}(input: $input) {
383
+ ${e.Fields.map(y=>l.MapFieldName(y.CodeName)).join(`
384
384
  `)}
385
- }`,R=y.gql`mutation ${o}${i} ($input: ${a}Input!) {
385
+ }`,E=d.gql`mutation ${o}${i} ($input: ${a}Input!) {
386
386
  ${S}
387
387
  }
388
- `;for(let l=0;l<c.length;l++){const g=c[l];let m=e.Get(g.Name);if(m)switch(g.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:m=m.getTime();break;case u.EntityFieldTSType.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case u.EntityFieldTSType.Number:if(typeof m!="number"){const I=Number(m);isNaN(I)||(m=I)}break}m===null&&g.EntityFieldInfo.AllowsNull===!1&&(g.EntityFieldInfo.DefaultValue!==null?m=g.EntityFieldInfo.DefaultValue:g.FieldType===u.EntityFieldTSType.Number||g.FieldType===u.EntityFieldTSType.Boolean?m=0:m=""),n.input[g.CodeName]=m}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const l=[];e.Fields.forEach(g=>{let m=null;g.OldValue!==null&&g.OldValue!==void 0&&(g.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?m=g.OldValue.getTime().toString():g.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?m=g.OldValue===!0?"1":"0":typeof g.OldValue!="string"?m=g.OldValue.toString():m=g.OldValue),l.push({Key:g.CodeName,Value:m})}),n.input.OldValues___=l}if(e.TransactionGroup){const l=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",S,n,{mutationName:a,mutationInputTypes:l},(g,m)=>{s.EndedAt=new Date,m&&g?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(g)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const l=await this.ExecuteGQL(R,n);if(l&&l[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(l[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let l=0;l<t.KeyValuePairs.length;l++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(l),I=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${g.CodeName}: $${g.CodeName}`,g.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(l)))throw new Error(`Primary Key value ${m} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(m)}else n[g.CodeName]=m}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),d=new A,S=y.gql`query Single${c}${a.length>0?"Full":""} (${i}) {
388
+ `;for(let y=0;y<c.length;y++){const m=c[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:p=p.getTime();break;case u.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case u.EntityFieldTSType.Number:if(typeof p!="number"){const I=Number(p);isNaN(I)||(p=I)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===u.EntityFieldTSType.Number||m.FieldType===u.EntityFieldTSType.Boolean?p=0:p=""),n.input[l.MapFieldName(m.CodeName)]=p}if(o.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:l.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,r.Type==="create"?"Create":"Update",S,n,{mutationName:a,mutationInputTypes:y},(m,p)=>{r.EndedAt=new Date,p&&m?(r.Success=!0,r.NewValues=this.ConvertBackToMJFields(m)):(r.Success=!1,r.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[a])return r.Success=!0,r.EndedAt=new Date,r.NewValues=this.ConvertBackToMJFields(y[a]),r.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return r.Success=!1,r.EndedAt=new Date,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,s=null,r){try{const n={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),I=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${m.CodeName}: $${m.CodeName}`,m.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const a=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),l=new w,S=d.gql`query Single${c}${a.length>0?"Full":""} (${i}) {
389
389
  ${c}(${o}) {
390
- ${e.Fields.filter(l=>!l.EntityFieldInfo.IsBinaryFieldType).map(l=>l.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?l.CodeName.replace("__mj_","_mj__"):l.CodeName).join(`
390
+ ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
391
391
  `)}
392
392
  ${a}
393
393
  }
394
394
  }
395
- `,R=await this.ExecuteGQL(S,n);return R&&R[c]?this.ConvertBackToMJFields(R[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new A().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 n=e.RelatedEntities[s],o=this.Entities.find(a=>w.UUIDsEqual(a.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
395
+ `,E=await this.ExecuteGQL(S,n);return E&&E[c]?this.ConvertBackToMJFields(E[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new w().ReverseMapFields(e),e}getRelatedEntityString(e,t){let s="";for(let r=0;r<e.RelatedEntities.length;r++)if(t.indexOf(e.RelatedEntities[r].RelatedEntity)>=0){const n=e.RelatedEntities[r],o=this.Entities.find(a=>v.UUIDsEqual(a.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
396
396
  ${i} {
397
397
  ${o.Fields.map(a=>a.CodeName).join(`
398
398
  `)}
399
399
  }
400
- `}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.ResultHistory.push(s);const n={},o=[];let i="",a="",c="";for(let g of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(I=>I.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());n[m.CodeName]=m.Value,o.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,a.length>0&&(a+=", "),a+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
401
- `),c+=`${m.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const S="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),R=y.gql`${S}(${i}, options___: $options___) {
400
+ `}return s}async Delete(e,t,s){const r=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),r.StartedAt=new Date,r.Type="delete",r.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.ResultHistory.push(r);const n={},o=[];let i="",a="",c="";for(let m of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(I=>I.Name.trim().toLowerCase()===m.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,o.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,a.length>0&&(a+=", "),a+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
401
+ `),c+=`${p.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const S="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),E=d.gql`${S}(${i}, options___: $options___) {
402
402
  ${c}
403
403
  }
404
- `,l=y.gql`mutation ${S} (${a}, $options___: DeleteOptionsInput!) {
405
- ${R}
404
+ `,y=d.gql`mutation ${S} (${a}, $options___: DeleteOptionsInput!) {
405
+ ${E}
406
406
  }
407
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,n,{mutationName:S,mutationInputTypes:o},(g,m)=>{if(s.EndedAt=new Date,m&&g){let I=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==g[E.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(l,n);if(g&&g[S]){const m=g[S];for(let I of e.PrimaryKey.KeyValuePairs){let E=m[I.FieldName],v=I.Value;if(typeof v=="number"&&(v=v.toString()),typeof E=="number"&&(E=E.toString()),v!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${v}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
407
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",E,n,{mutationName:S,mutationInputTypes:o},(m,p)=>{if(r.EndedAt=new Date,p&&m){let I=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==m[R.FieldName]&&(I=!1);I?r.Success=!0:(r.Success=!1,r.Message="Transaction failed to commit")}else r.Success=!1,r.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[S]){const p=m[S];for(let I of e.PrimaryKey.KeyValuePairs){let R=p[I.FieldName],C=I.Value;if(typeof C=="number"&&(C=C.toString()),typeof R=="number"&&(R=R.toString()),C!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${C}, Returned: ${R}`)}return r.Success=!0,r.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return r.EndedAt=new Date,r.Success=!1,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const s=d.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
408
408
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
409
409
  DatasetID
410
410
  DatasetName
@@ -413,7 +413,7 @@
413
413
  LatestUpdateDate
414
414
  Results
415
415
  }
416
- }`,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=y.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
416
+ }`,r=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:t});return r&&r.GetDatasetByName&&r.GetDatasetByName.Success?{DatasetID:r.GetDatasetByName.DatasetID,DatasetName:r.GetDatasetByName.DatasetName,Success:r.GetDatasetByName.Success,Status:r.GetDatasetByName.Status,LatestUpdateDate:new Date(r.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(r.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const s=d.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
417
417
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
418
418
  DatasetID
419
419
  DatasetName
@@ -422,22 +422,22 @@
422
422
  LatestUpdateDate
423
423
  EntityUpdateDates
424
424
  }
425
- }`,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 x(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(a=>a.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
425
+ }`,r=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:t});return r&&r.GetDatasetStatusByName&&r.GetDatasetStatusByName.Success?{DatasetID:r.GetDatasetStatusByName.DatasetID,DatasetName:r.GetDatasetStatusByName.DatasetName,Success:r.GetDatasetStatusByName.Success,Status:r.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(r.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(r.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new x(this)}async GetRecordFavoriteStatus(e,t,s){if(!s.Validate().IsValid)return!1;const n=this.Entities.find(a=>a.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=d.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
426
426
  GetRecordFavoriteStatus(params: $params) {
427
427
  Success
428
428
  IsFavorite
429
429
  }
430
- }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=y.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
430
+ }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,s,r,n){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=d.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
431
431
  SetRecordFavoriteStatus(params: $params){
432
432
  Success
433
433
  }
434
- }`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(a&&a.SetRecordFavoriteStatus!==null)return a.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=y.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
434
+ }`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:r}});if(a&&a.SetRecordFavoriteStatus!==null)return a.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const s=d.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
435
435
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
436
436
  Success
437
437
  Status
438
438
  RecordName
439
439
  }
440
- }`,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 InternalGetEntityRecordNames(e){if(!e)return null;const t=y.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
440
+ }`,r=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(r&&r.GetEntityRecordName&&r.GetEntityRecordName.Success)return r.GetEntityRecordName.RecordName}async InternalGetEntityRecordNames(e){if(!e)return null;const t=d.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
441
441
  GetEntityRecordNames(info: $info) {
442
442
  Success
443
443
  Status
@@ -450,47 +450,57 @@
450
450
  EntityName
451
451
  RecordName
452
452
  }
453
- }`,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.map(s=>({...s,CompositeKey:new u.CompositeKey(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=y.gql`query GetDataContextData ($DataContextID: String!) {
453
+ }`,s=await this.ExecuteGQL(t,{info:e.map(r=>({EntityName:r.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames.map(r=>({...r,CompositeKey:new u.CompositeKey(r.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=d.gql`query GetDataContextData ($DataContextID: String!) {
454
454
  GetDataContextData(DataContextID: $DataContextID) {
455
455
  Success
456
456
  ErrorMessages
457
457
  Results
458
458
  }
459
- }`,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 u.LogError(t),t}}async GetDataContextItemData(e){try{const t=y.gql`query GetDataContextItemData ($DataContextItemID: String!) {
459
+ }`,s=await this.ExecuteGQL(t,{DataContextID:e});if(s&&s.GetDataContextData){if(s.GetDataContextData.Success)return s.GetDataContextData.Results.map(r=>JSON.parse(r));throw new Error(s.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=d.gql`query GetDataContextItemData ($DataContextItemID: String!) {
460
460
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
461
461
  Success
462
462
  ErrorMessage
463
463
  Result
464
464
  }
465
- }`,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 u.LogError(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 u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(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._configData.UserAPIKey);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,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n),new y.GraphQLClient(e,{headers:o})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
466
- `:s.startsWith("_")||(t+=s+`
467
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new u.InMemoryLocalStorageProvider),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=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),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(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,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 $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:p(o=>{r.next(o.data)},"next"),error:p(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(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(a=>{r.activeSubscribers++;const c=r.subject.subscribe(a);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,c.unsubscribe()}});const s=y.gql`subscription StatusUpdates($sessionId: String!) {
465
+ }`,s=await this.ExecuteGQL(t,{DataContextItemID:e});if(s&&s.GetDataContextItemData){if(s.GetDataContextItemData.Success)return JSON.parse(s.GetDataContextItemData.Result);throw new Error(s.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,s=!0){return f.Instance.ExecuteGQL(e,t,s)}async ExecuteGQL(e,t,s=!0){try{return await this._client.request(e,t)}catch(r){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!r?.response,hasErrors:!!r?.response?.errors,errorCount:r?.response?.errors?.length,firstError:r?.response?.errors?.[0],errorCode:r?.response?.errors?.[0]?.extensions?.code,errorMessage:r?.response?.errors?.[0]?.message,fullError:r}),r&&r.response&&r.response.errors?.length>0)if(r.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),r}else throw r;else throw u.LogError(r),r}}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._configData.UserAPIKey);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,s,r,n){const o={"x-session-id":s};return t&&(o.authorization="Bearer "+t),r&&(o["x-mj-api-key"]=r),n&&(o["x-api-key"]=n),new d.GraphQLClient(e,{headers:o})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const s=Object.keys(e);for(const r of s)r.startsWith("__mj_")?t+=r.replace("__mj_","_mj__")+`
466
+ `:r.startsWith("_")||(t+=r+`
467
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new u.InMemoryLocalStorageProvider),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=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!0,"shouldRetry")}),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(s){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,s)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,s=Array.from(this._pushStatusSubjects.entries()),r=[];s.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),r.push(n))}),r.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.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 b.Observable(s=>{const r=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=r.subscribe({query:e,variables:t},{next:g(o=>{s.next(o.data)},"next"),error:g(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(),s.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),s.error(c)}}else s.error(o)},"error"),complete:g(()=>{s.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),s=this._pushStatusSubjects.get(e);if(s)return s.lastRequestedAt=t,new b.Observable(a=>{s.activeSubscribers++;const c=s.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,c.unsubscribe()}});const r=d.gql`subscription StatusUpdates($sessionId: String!) {
468
468
  statusUpdates(sessionId: $sessionId) {
469
469
  date
470
470
  message
471
471
  sessionId
472
472
  }
473
473
  }
474
- `,n=new $.Subject,o=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(a=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:p(d=>{const S=this._pushStatusSubjects.get(e);S&&(S.lastEmissionAt=Date.now()),a.next(d.data.statusUpdates.message)},"next"),error:p(async d=>{const S=d;if(S?.extensions?.code==="JWT_EXPIRED"||S?.message?.includes("token has expired")||S?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",l),a.error(l)}}else a.error(d)},"error"),complete:p(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:p(a=>n.next(a),"next"),error:p(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(a=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const d=n.subscribe(a);return()=>{const S=this._pushStatusSubjects.get(e);S&&S.activeSubscribers>0&&S.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
474
+ `,n=new b.Subject,o=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(a=>{const c=o.subscribe({query:r,variables:{sessionId:e}},{next:g(l=>{const S=this._pushStatusSubjects.get(e);S&&(S.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:g(async l=>{const S=l;if(S?.extensions?.code==="JWT_EXPIRED"||S?.message?.includes("token has expired")||S?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(l)},"error"),complete:g(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:g(a=>n.next(a),"next"),error:g(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(a=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const l=n.subscribe(a);return()=>{const S=this._pushStatusSubjects.get(e);S&&S.activeSubscribers>0&&S.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=d.gql`subscription CacheInvalidation {
475
+ cacheInvalidation {
476
+ EntityName
477
+ PrimaryKeyValues
478
+ Action
479
+ SourceServerID
480
+ Timestamp
481
+ OriginSessionID
482
+ RecordData
483
+ }
484
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(s=>{const r=s?.cacheInvalidation;if(!r)return;if(r.OriginSessionID&&r.OriginSessionID===this.sessionId){console.log(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${r.EntityName}" (action: ${r.Action})`);return}console.log(`[GraphQLDataProvider] Cache invalidation received: ${r.Action} for "${r.EntityName}" from server ${r.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:r.EntityName,baseEntity:null,payload:{primaryKeyValues:r.PrimaryKeyValues,action:r.Action,sourceServerId:r.SourceServerID,timestamp:r.Timestamp,recordData:r.RecordData}};v.MJGlobal.Instance.RaiseEvent({event:v.MJEventType.ComponentEvent,eventCode:u.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(s=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",s),this._cacheInvalidationSubscription=null},"error"),complete:g(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,s){if(!e.IsParentType)return null;const r=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
475
485
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
476
486
  Success
477
487
  ChildEntityName
478
488
  ErrorMessage
479
489
  }
480
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return u.LogError(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
490
+ }`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return u.LogError(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,s){if(!e.IsParentType)return[];const r=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
481
491
  FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
482
492
  Success
483
493
  ChildEntityNames
484
494
  ErrorMessage
485
495
  }
486
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new f;return u.SetProvider(e),await e.Config(h),await u.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}p(j,"setupGraphQLClient");class J{static{p(this,"SyncRolesAndUsersResult")}}class W{static{p(this,"RoleInput")}}class z{static{p(this,"UserInput")}}class H{static{p(this,"RolesAndUsersInput")}}var U=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(U||{});class X{static{p(this,"ActionItemInput")}}class Y{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{p(this,"ActionItemOutput")}}class ee{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new y.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return u.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
496
+ }`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new f;return u.SetProvider(e),await e.Config(h),await u.StartupManager.Instance.Startup(),v.MJGlobal.Instance.RaiseEvent({event:v.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class z{static{g(this,"UserInput")}}class H{static{g(this,"RolesAndUsersInput")}}var U=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(U||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,s,r){const n={"x-session-id":s};this._sessionId=s,t&&(n.authorization="Bearer "+t),r&&(n["x-mj-api-key"]=r),this._client=new d.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return u.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request(`query GetData($input: GetDataInputType!) {
487
497
  GetData(input: $input) {
488
498
  Success
489
499
  ErrorMessages
490
500
  Queries
491
501
  Results
492
502
  }
493
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?w.SafeJSONParse(n):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 n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
503
+ }`,{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(n=>n?v.SafeJSONParse(n):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(s){let r=s instanceof Error?s.message:String(s);const n=r.match(/Error: ([^:]+)\./);if(n&&(r=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${s}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
494
504
  GetAllEntities {
495
505
  Success
496
506
  ErrorMessage
@@ -513,7 +523,7 @@
513
523
  }
514
524
  }
515
525
  }
516
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u.LogError(`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!]!) {
526
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const s=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
517
527
  SyncData(items: $items) {
518
528
  Success
519
529
  Results {
@@ -537,11 +547,11 @@
537
547
  RecordJSON
538
548
  }
539
549
  }
540
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
550
+ }`,{items:e});return s&&s.SyncData?s.SyncData:{Success:!1,Results:[]}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const s=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
541
551
  SyncRolesAndUsers(data: $data) {
542
552
  Success
543
553
  }
544
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
554
+ }`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
545
555
  RunViewByNameSystemUser(input: $input) {
546
556
  Results {
547
557
  PrimaryKey {
@@ -558,7 +568,7 @@
558
568
  ErrorMessage
559
569
  Success
560
570
  }
561
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
571
+ }`,s={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},r=await this.Client.request(t,{input:s});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
562
572
  RunViewByIDSystemUser(input: $input) {
563
573
  Results {
564
574
  PrimaryKey {
@@ -575,7 +585,7 @@
575
585
  ErrorMessage
576
586
  Success
577
587
  }
578
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
588
+ }`,s={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},r=await this.Client.request(t,{input:s});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
579
589
  RunDynamicViewSystemUser(input: $input) {
580
590
  Results {
581
591
  PrimaryKey {
@@ -592,7 +602,7 @@
592
602
  ErrorMessage
593
603
  Success
594
604
  }
595
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
605
+ }`,s={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},r=await this.Client.request(t,{input:s});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
596
606
  RunViewsSystemUser(input: $input) {
597
607
  Results {
598
608
  PrimaryKey {
@@ -609,7 +619,7 @@
609
619
  ErrorMessage
610
620
  Success
611
621
  }
612
- }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return u.LogError(`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) {
622
+ }`,s=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),r=await this.Client.request(t,{input:s});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return u.LogError(`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) {
613
623
  GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
614
624
  QueryID
615
625
  QueryName
@@ -621,7 +631,7 @@
621
631
  ErrorMessage
622
632
  AppliedParameters
623
633
  }
624
- }`,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?w.SafeJSONParse(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 u.LogError(`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) {
634
+ }`,s={QueryID:e.QueryID};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataSystemUser?{...r.GetQueryDataSystemUser,Results:r.GetQueryDataSystemUser.Results?v.SafeJSONParse(r.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`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) {
625
635
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
626
636
  QueryID
627
637
  QueryName
@@ -633,7 +643,7 @@
633
643
  ErrorMessage
634
644
  AppliedParameters
635
645
  }
636
- }`,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?w.SafeJSONParse(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 u.LogError(`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!) {
646
+ }`,s={QueryName:e.QueryName};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataByNameSystemUser?{...r.GetQueryDataByNameSystemUser,Results:r.GetQueryDataByNameSystemUser.Results?v.SafeJSONParse(r.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`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 s=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
637
647
  CreateQuerySystemUser(input: $input) {
638
648
  Success
639
649
  ErrorMessage
@@ -688,7 +698,7 @@
688
698
  Role
689
699
  }
690
700
  }
691
- }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return u.LogError(`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!) {
701
+ }`,{input:e});return s&&s.CreateQuerySystemUser?s.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const s=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
692
702
  UpdateQuerySystemUser(input: $input) {
693
703
  Success
694
704
  ErrorMessage
@@ -743,14 +753,14 @@
743
753
  Role
744
754
  }
745
755
  }
746
- }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return u.LogError("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) {
756
+ }`,{input:e});return s&&s.UpdateQuerySystemUser?s.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return u.LogError("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const s=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
747
757
  DeleteQuerySystemResolver(ID: $ID, options: $options) {
748
758
  Success
749
759
  ErrorMessage
750
760
  ID
751
761
  Name
752
762
  }
753
- }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=y.gql`
763
+ }`,r={ID:e};t!==void 0&&(r.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(s,r);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(s){let r="";if(s instanceof Error){if(r=s.message,"cause"in s&&s.cause){const n=s.cause;r+=` | Cause: ${n.message||n}`,"code"in n&&(r+=` | Code: ${n.code}`)}if("response"in s){const n=s.response;n?.status&&(r+=` | HTTP Status: ${n.status}`),n?.errors&&(r+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}s.stack&&console.error("DeleteQuery stack trace:",s.stack)}else r=String(s);return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r}}}async RunAIPrompt(e){try{const t=d.gql`
754
764
  query RunAIPromptSystemUser(
755
765
  $promptId: String!,
756
766
  $data: String,
@@ -809,7 +819,7 @@
809
819
  chatResult
810
820
  }
811
821
  }
812
- `,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 u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=y.gql`
822
+ `,s=this.preparePromptVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIPromptSystemUser?this.processPromptResult(r.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=d.gql`
813
823
  query RunAIAgentSystemUser(
814
824
  $agentId: String!,
815
825
  $messages: String!,
@@ -836,7 +846,7 @@
836
846
  result
837
847
  }
838
848
  }
839
- `,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 u.LogError(`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 w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=y.gql`
849
+ `,s=this.prepareAgentVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIAgentSystemUser?this.processAgentResult(r.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`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,s,r;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(s=JSON.parse(e.validationResult))}catch{s=e.validationResult}try{e.chatResult&&(r=JSON.parse(e.chatResult))}catch{r=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:s,chatResult:r}}processAgentResult(e){return v.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=d.gql`
840
850
  query ExecuteSimplePromptSystemUser(
841
851
  $systemPrompt: String!,
842
852
  $messages: String,
@@ -859,7 +869,7 @@
859
869
  executionTimeMs
860
870
  }
861
871
  }
862
- `,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 n=s.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=y.gql`
872
+ `,s={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(s.messages=JSON.stringify(e.messages)),e.preferredModels&&(s.preferredModels=e.preferredModels),e.modelPower&&(s.modelPower=e.modelPower),e.responseFormat&&(s.responseFormat=e.responseFormat);const r=await this.Client.request(t,s);if(!r?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=r.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=d.gql`
863
873
  query EmbedTextSystemUser(
864
874
  $textToEmbed: [String!]!,
865
875
  $modelSize: String!
@@ -874,7 +884,7 @@
874
884
  error
875
885
  }
876
886
  }
877
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class te{static{p(this,"GetDataOutput")}}class re{static{p(this,"SimpleRemoteEntityOutput")}}class se{static{p(this,"SimpleRemoteEntity")}}class ne{static{p(this,"SimpleRemoteEntityField")}}class oe{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);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=y.gql`
887
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,r);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class te{static{g(this,"GetDataOutput")}}class re{static{g(this,"SimpleRemoteEntityOutput")}}class se{static{g(this,"SimpleRemoteEntity")}}class ne{static{g(this,"SimpleRemoteEntityField")}}class oe{static{g(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,s=!1){try{const r=this.serializeActionParameters(t),n=this.createActionVariables(e,r,s),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(r){return this.handleActionError(r,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let s=t.Value;return s!=null&&typeof s=="object"&&(s=JSON.stringify(s)),{...t,Value:s}})}createActionVariables(e,t,s=!1){return{input:{ActionID:e,Params:t,SkipActionLog:s}}}async executeActionMutation(e){const t=d.gql`
878
888
  mutation RunAction($input: RunActionInput!) {
879
889
  RunAction(input: $input) {
880
890
  Success
@@ -883,7 +893,7 @@
883
893
  ResultData
884
894
  }
885
895
  }
886
- `;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){u.LogError(`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 u.LogError(`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=y.gql`
896
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let s;try{e.RunAction.ResultData&&(s=JSON.parse(e.RunAction.ResultData))}catch(r){u.LogError(`Failed to parse action result data: ${r}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:s,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const s=e;return u.LogError(`Error running action: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),s=await this.executeEntityActionMutation(t);return this.processEntityActionResult(s)}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 s=t.Value;return s!=null&&typeof s=="object"&&(s=JSON.stringify(s)),{Name:t.Name,Value:s,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=d.gql`
887
897
  mutation RunEntityAction($input: EntityActionInput!) {
888
898
  RunEntityAction(input: $input) {
889
899
  Success
@@ -891,7 +901,7 @@
891
901
  ResultData
892
902
  }
893
903
  }
894
- `;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){u.LogError(`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 u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ae{static{p(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=y.gql`
904
+ `;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(s){u.LogError(`Failed to parse entity action result data: ${s}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ae{static{g(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),s=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(s)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=d.gql`
895
905
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
896
906
  CreateAPIKey(input: $input) {
897
907
  Success
@@ -900,18 +910,18 @@
900
910
  Error
901
911
  }
902
912
  }
903
- `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return u.LogError(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=y.gql`
913
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return u.LogError(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=d.gql`
904
914
  mutation RevokeAPIKey($apiKeyId: String!) {
905
915
  RevokeAPIKey(apiKeyId: $apiKeyId) {
906
916
  Success
907
917
  Error
908
918
  }
909
919
  }
910
- `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ie{static{p(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:p(s=>s?.success===!0,"validateAck"),isCompletionEvent:p(s=>this.isTestCompletionEvent(s,e.testId),"isCompletionEvent"),extractResult:p(s=>this.extractTestResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:p(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:p(s=>s?.success===!0,"validateAck"),isCompletionEvent:p(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:p(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:p(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=y.gql`
920
+ `,r=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return r?.RevokeAPIKey?{Success:r.RevokeAPIKey.Success,Error:r.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const s=t;return u.LogError(`Error revoking API key: ${s.message}`),{Success:!1,Error:`Error: ${s.message}`}}}}class ie{static{g(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),s=this.buildRunTestVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isTestCompletionEvent(r,e.testId),"isCompletionEvent"),extractResult:g(r=>this.extractTestResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),s=this.buildRunTestSuiteVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isSuiteCompletionEvent(r,e.suiteId),"isCompletionEvent"),extractResult:g(r=>this.extractSuiteResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=d.gql`
911
921
  query IsTestRunning($testId: String!) {
912
922
  IsTestRunning(testId: $testId)
913
923
  }
914
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return y.gql`
924
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return d.gql`
915
925
  mutation RunTest(
916
926
  $testId: String!,
917
927
  $verbose: Boolean,
@@ -934,7 +944,7 @@
934
944
  result
935
945
  }
936
946
  }
937
- `}buildRunTestSuiteMutation(){return y.gql`
947
+ `}buildRunTestSuiteMutation(){return d.gql`
938
948
  mutation RunTestSuite(
939
949
  $suiteId: String!,
940
950
  $verbose: Boolean,
@@ -965,7 +975,7 @@
965
975
  result
966
976
  }
967
977
  }
968
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?w.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?w.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class ue{static{p(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
978
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:s,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0,r=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:s,selectedTestIds:r,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&s?.type==="complete"&&s?.testId===t}isSuiteCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&s?.type==="complete"&&s?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const s=e.message;return u.LogError(`${t} failed: ${s}`),{success:!1,errorMessage:s.includes("Failed to fetch")||s.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":s,result:null}}}class ue{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=d.gql`
969
979
  query GetRegistryComponent(
970
980
  $registryName: String!,
971
981
  $namespace: String!,
@@ -986,7 +996,7 @@
986
996
  specification
987
997
  }
988
998
  }
989
- `,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 n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(o){return u.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=y.gql`
999
+ `,s={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(s.version=e.version),e.hash!==void 0&&(s.hash=e.hash);const r=await this._dataProvider.ExecuteGQL(t,s);if(r&&r.GetRegistryComponent){const n=r.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(o){return u.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=d.gql`
990
1000
  query GetRegistryComponent(
991
1001
  $registryName: String!,
992
1002
  $namespace: String!,
@@ -1007,7 +1017,7 @@
1007
1017
  specification
1008
1018
  }
1009
1019
  }
1010
- `,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 n=s.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=y.gql`
1020
+ `,s={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(s.version=e.version),e.hash!==void 0&&(s.hash=e.hash);const r=await this._dataProvider.ExecuteGQL(t,s);if(r&&r.GetRegistryComponent){const n=r.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=d.gql`
1011
1021
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
1012
1022
  SearchRegistryComponents(params: $params) {
1013
1023
  components
@@ -1016,7 +1026,7 @@
1016
1026
  limit
1017
1027
  }
1018
1028
  }
1019
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=y.gql`
1029
+ `,s=await this._dataProvider.ExecuteGQL(t,{params:e});if(s&&s.SearchRegistryComponents){const r=s.SearchRegistryComponents;return{components:r.components.map(n=>JSON.parse(n)),total:r.total,offset:r.offset,limit:r.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const s=d.gql`
1020
1030
  query ResolveComponentDependencies(
1021
1031
  $registryId: String!,
1022
1032
  $componentId: String!
@@ -1041,7 +1051,7 @@
1041
1051
  }
1042
1052
  }
1043
1053
  }
1044
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(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 u.LogError(s),null}}async SendComponentFeedback(e){try{const t=y.gql`
1054
+ `,r=await this._dataProvider.ExecuteGQL(s,{registryId:e,componentId:t});return r&&r.ResolveComponentDependencies?r.ResolveComponentDependencies:null}catch(s){throw u.LogError(s),new Error(`Failed to resolve component dependencies: ${s instanceof Error?s.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,s){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:s,version:"latest"}))?.version||null}catch(r){return u.LogError(r),null}}async SendComponentFeedback(e){try{const t=d.gql`
1045
1055
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
1046
1056
  SendComponentFeedback(feedback: $feedback) {
1047
1057
  success
@@ -1049,7 +1059,7 @@
1049
1059
  error
1050
1060
  }
1051
1061
  }
1052
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ce{static{p(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=y.gql`
1062
+ `,s=await this._dataProvider.ExecuteGQL(t,{feedback:e});return s&&s.SendComponentFeedback?s.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ce{static{g(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const s=d.gql`
1053
1063
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1054
1064
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1055
1065
  Success
@@ -1065,7 +1075,7 @@
1065
1075
  }
1066
1076
  }
1067
1077
  }
1068
- `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class le{static{p(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=y.gql`
1078
+ `,r={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(s,r);return this.processResult(n)}catch(s){const r=s instanceof Error?s.message:String(s);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${r}`),{Success:!1,Error:r}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(s=>({Key:s.Key,Value:s.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const s=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(r=>({EntityName:r.EntityName??"",RecordID:r.RecordID??"",ErrorMessage:r.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:s}}}class le{static{g(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",s){try{const r=d.gql`
1069
1079
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1070
1080
  ListStorageObjects(input: $input) {
1071
1081
  objects {
@@ -1082,34 +1092,34 @@
1082
1092
  prefixes
1083
1093
  }
1084
1094
  }
1085
- `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(s){const n=s;throw u.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return u.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=y.gql`
1095
+ `,n={input:{AccountID:e,Prefix:t,Delimiter:s||"/"}},o=await this._dataProvider.ExecuteGQL(r,n);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(r){const n=r;throw u.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const s=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return s.objects.length>0||s.prefixes.length>0}catch(s){const r=s;return u.LogError(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const s=d.gql`
1086
1096
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1087
1097
  CreateDirectory(input: $input)
1088
1098
  }
1089
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return u.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(o=>o.name===s||o.fullPath===t)}catch(r){const s=r;return u.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=y.gql`
1099
+ `,r={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(s,r))?.CreateDirectory??!1}catch(s){const r=s;return u.LogError(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const s=t.substring(0,t.lastIndexOf("/")+1),r=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,s,"/")).objects.some(o=>o.name===r||o.fullPath===t)}catch(s){const r=s;return u.LogError(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,s){try{const r=d.gql`
1090
1100
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1091
1101
  CreatePreAuthUploadUrl(input: $input) {
1092
1102
  UploadUrl
1093
1103
  ProviderKey
1094
1104
  }
1095
1105
  }
1096
- `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw u.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=y.gql`
1106
+ `,n={input:{AccountID:e,ObjectName:t,ContentType:s}},o=await this._dataProvider.ExecuteGQL(r,n);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(r){const n=r;throw u.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const s=d.gql`
1097
1107
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1098
1108
  CreatePreAuthDownloadUrl(input: $input)
1099
1109
  }
1100
- `,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw u.LogError(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=y.gql`
1110
+ `,r={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(s,r);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(s){const r=s;throw u.LogError(`Error creating pre-auth download URL: ${r}`),r}}async DeleteObject(e,t){try{const s=d.gql`
1101
1111
  mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
1102
1112
  DeleteStorageObject(input: $input)
1103
1113
  }
1104
- `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return u.LogError(`Error deleting storage object: ${s}`),!1}}async MoveObject(e,t,r){try{const s=y.gql`
1114
+ `,r={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(s,r))?.DeleteStorageObject??!1}catch(s){const r=s;return u.LogError(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,s){try{const r=d.gql`
1105
1115
  mutation MoveStorageObject($input: MoveStorageObjectInput!) {
1106
1116
  MoveStorageObject(input: $input)
1107
1117
  }
1108
- `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){const n=s;return u.LogError(`Error moving storage object: ${n}`),!1}}async CopyObject(e,t,r){try{const s=y.gql`
1118
+ `,n={input:{AccountID:e,OldName:t,NewName:s}};return(await this._dataProvider.ExecuteGQL(r,n))?.MoveStorageObject??!1}catch(r){const n=r;return u.LogError(`Error moving storage object: ${n}`),!1}}async CopyObject(e,t,s){try{const r=d.gql`
1109
1119
  mutation CopyStorageObject($input: CopyStorageObjectInput!) {
1110
1120
  CopyStorageObject(input: $input)
1111
1121
  }
1112
- `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){const n=s;return u.LogError(`Error copying storage object: ${n}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=y.gql`
1122
+ `,n={input:{AccountID:e,SourceName:t,DestinationName:s}};return(await this._dataProvider.ExecuteGQL(r,n))?.CopyStorageObject??!1}catch(r){const n=r;return u.LogError(`Error copying storage object: ${n}`),!1}}async CopyObjectBetweenAccounts(e,t,s,r){try{const n=d.gql`
1113
1123
  mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
1114
1124
  CopyObjectBetweenAccounts(input: $input) {
1115
1125
  success
@@ -1121,7 +1131,7 @@
1121
1131
  destinationPath
1122
1132
  }
1123
1133
  }
1124
- `,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,o);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const o=n;return u.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=y.gql`
1134
+ `,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:s,DestinationPath:r}},i=await this._dataProvider.ExecuteGQL(n,o);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const o=n;return u.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:s,destinationPath:r}}}async SearchFiles(e,t,s){try{const r=d.gql`
1125
1135
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1126
1136
  SearchAcrossAccounts(input: $input) {
1127
1137
  accountResults {
@@ -1149,5 +1159,99 @@
1149
1159
  failedAccounts
1150
1160
  }
1151
1161
  }
1152
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:p(function(){return y.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=Q,exports.BrowserStorageProviderBase=T,exports.FieldMapper=A,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=U,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1162
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:s?.maxResultsPerAccount,FileTypes:s?.fileTypes,SearchContent:s?.searchContent}},o=await this._dataProvider.ExecuteGQL(r,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(r){const n=r;return u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class de{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=d.gql`
1163
+ query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1164
+ IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1165
+ Success
1166
+ Message
1167
+ Objects {
1168
+ Name
1169
+ Label
1170
+ SupportsIncrementalSync
1171
+ SupportsWrite
1172
+ }
1173
+ }
1174
+ }
1175
+ `,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationDiscoverObjects;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,Data:r.Objects??[]}}catch(t){return this.handleError(t,[])}}async DiscoverFields(e,t){try{const s=d.gql`
1176
+ query IntegrationDiscoverFields($companyIntegrationID: String!, $objectName: String!) {
1177
+ IntegrationDiscoverFields(companyIntegrationID: $companyIntegrationID, objectName: $objectName) {
1178
+ Success
1179
+ Message
1180
+ Fields {
1181
+ Name
1182
+ Label
1183
+ DataType
1184
+ IsRequired
1185
+ IsUniqueKey
1186
+ IsReadOnly
1187
+ }
1188
+ }
1189
+ }
1190
+ `,n=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t}))?.IntegrationDiscoverFields;if(!n)throw new Error("Invalid response from server");return{Success:n.Success,Message:n.Message,Data:n.Fields??[]}}catch(s){return this.handleError(s,[])}}async TestConnection(e){try{const t=d.gql`
1191
+ query IntegrationTestConnection($companyIntegrationID: String!) {
1192
+ IntegrationTestConnection(companyIntegrationID: $companyIntegrationID) {
1193
+ Success
1194
+ Message
1195
+ ServerVersion
1196
+ }
1197
+ }
1198
+ `,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,ServerVersion:r.ServerVersion??null}}catch(t){const s=t;return u.LogError(`Error testing integration connection: ${s}`),{Success:!1,Message:`Error: ${s.message}`,ServerVersion:null}}}async SchemaPreview(e,t,s="sqlserver"){try{const r=d.gql`
1199
+ query IntegrationSchemaPreview(
1200
+ $companyIntegrationID: String!,
1201
+ $objects: [SchemaPreviewObjectInput!]!,
1202
+ $platform: String!
1203
+ ) {
1204
+ IntegrationSchemaPreview(
1205
+ companyIntegrationID: $companyIntegrationID,
1206
+ objects: $objects,
1207
+ platform: $platform
1208
+ ) {
1209
+ Success
1210
+ Message
1211
+ Files {
1212
+ FilePath
1213
+ Content
1214
+ Description
1215
+ }
1216
+ Warnings
1217
+ }
1218
+ }
1219
+ `,o=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objects:t,platform:s}))?.IntegrationSchemaPreview;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Files:o.Files??[],Warnings:o.Warnings??[]}}catch(r){const n=r;return u.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,s=5){try{const r=d.gql`
1220
+ query IntegrationPreviewData(
1221
+ $companyIntegrationID: String!,
1222
+ $objectName: String!,
1223
+ $limit: Float!
1224
+ ) {
1225
+ IntegrationPreviewData(
1226
+ companyIntegrationID: $companyIntegrationID,
1227
+ objectName: $objectName,
1228
+ limit: $limit
1229
+ ) {
1230
+ Success
1231
+ Message
1232
+ Records {
1233
+ Data
1234
+ }
1235
+ }
1236
+ }
1237
+ `,o=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objectName:t,limit:s}))?.IntegrationPreviewData;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Records:o.Records??[]}}catch(r){const n=r;return u.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=d.gql`
1238
+ query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
1239
+ IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
1240
+ Success
1241
+ Message
1242
+ DefaultSchemaName
1243
+ DefaultObjects {
1244
+ SourceObjectName
1245
+ TargetTableName
1246
+ TargetEntityName
1247
+ SyncEnabled
1248
+ FieldMappings {
1249
+ SourceFieldName
1250
+ DestinationFieldName
1251
+ IsKeyField
1252
+ }
1253
+ }
1254
+ }
1255
+ }
1256
+ `,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,DefaultSchemaName:r.DefaultSchemaName,DefaultObjects:r.DefaultObjects??[]}}catch(t){const s=t;return u.LogError(`Error getting default config: ${s}`),{Success:!1,Message:`Error: ${s.message}`}}}handleError(e,t){const s=e;return u.LogError(`Error in integration discovery: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return d.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=Q,exports.BrowserStorageProviderBase=T,exports.FieldMapper=w,exports.FireAndForgetHelper=$,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=de,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=U,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1153
1257
  //# sourceMappingURL=index.cjs.map