@memberjunction/react-runtime 5.7.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.
@@ -1,4 +1,4 @@
1
- "use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>F,ActionItemOutput:()=>T,BrowserIndexedDBStorageProvider:()=>f,BrowserStorageProviderBase:()=>D,FieldMapper:()=>g,FireAndForgetHelper:()=>I,GetDataOutput:()=>G,GraphQLAIClient:()=>S,GraphQLActionClient:()=>O,GraphQLComponentRegistryClient:()=>j,GraphQLDataProvider:()=>P,GraphQLEncryptionClient:()=>k,GraphQLFileStorageClient:()=>B,GraphQLProviderConfigData:()=>C,GraphQLSystemUserClient:()=>L,GraphQLTestingClient:()=>K,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>A,RolesAndUsersInput:()=>b,SimpleRemoteEntity:()=>U,SimpleRemoteEntityField:()=>_,SimpleRemoteEntityOutput:()=>V,SyncDataAction:()=>M,SyncDataResult:()=>Q,SyncRolesAndUsersResult:()=>$,UserInput:()=>N,gql:()=>s.J1,setupGraphQLClient:()=>v});var s=r(215),a=r(358),n=r(865),o=r(429),i=r(600),u=r(49),c=r(226),l=r(497),d=r(718),m=r(196),y=Object.defineProperty,p=(e,t)=>y(e,"name",{value:t,configurable:!0});class g{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(([e,t])=>[t,e]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}}class h extends a.VH{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
1
+ "use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>F,ActionItemOutput:()=>L,BrowserIndexedDBStorageProvider:()=>v,BrowserStorageProviderBase:()=>D,FieldMapper:()=>g,FireAndForgetHelper:()=>I,GetDataOutput:()=>G,GraphQLAIClient:()=>S,GraphQLActionClient:()=>O,GraphQLComponentRegistryClient:()=>k,GraphQLDataProvider:()=>P,GraphQLEncryptionClient:()=>K,GraphQLFileStorageClient:()=>B,GraphQLIntegrationClient:()=>q,GraphQLProviderConfigData:()=>f,GraphQLSystemUserClient:()=>T,GraphQLTestingClient:()=>j,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>A,RolesAndUsersInput:()=>b,SimpleRemoteEntity:()=>U,SimpleRemoteEntityField:()=>_,SimpleRemoteEntityOutput:()=>V,SyncDataAction:()=>M,SyncDataResult:()=>Q,SyncRolesAndUsersResult:()=>$,UserInput:()=>N,gql:()=>s.J1,setupGraphQLClient:()=>C});var s=r(215),a=r(654),n=r(865),o=r(429),i=r(600),u=r(49),c=r(226),l=r(497),d=r(718),m=r(196),p=Object.defineProperty,y=(e,t)=>p(e,"name",{value:t,configurable:!0});class g{static{y(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(g.DB_PREFIX)?g.GQL_PREFIX+e.substring(g.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(g.GQL_PREFIX)?g.DB_PREFIX+e.substring(g.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class h extends a.VH{static{y(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
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 e of this.PendingTransactions)t.push({EntityName:e.BaseEntity.EntityInfo.Name,EntityObjectJSON:await e.BaseEntity.GetDataObjectJSON(),OperationType:e.OperationType});const r={group:{Items:t,Variables:this.Variables.map(e=>({Name:e.Name,ItemIndex:this.MapVariableEntityObjectToPosition(e),FieldName:e.FieldName,Type:e.Type}))}},o=await this._provider.ExecuteGQL(e,r);if(o&&o.ExecuteTransactionGroup){const e=o.ExecuteTransactionGroup,t=[];for(let r=0;r<this.PendingTransactions.length;r++){const s=e.ResultsJSON[r],o=(0,n.NG)(s),i=this.PendingTransactions[r];t.push(new a.qT(i,o,null!==o))}return t}throw new Error("Failed to execute transaction group")}}class I{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}=I.createCompletionPromise();s=I.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=I.subscribeToPubSub(e,o,s);const u=await I.executeMutation(e);if(!e.validateAck(u)){s&&clearTimeout(s);const r=u?.errorMessage??"Server rejected the request";return(0,a.ZI)(`[FireAndForget:${t}] Server rejected: ${r}`),e.createErrorResult(r)}return(0,a.b0)(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(e){throw s&&clearTimeout(s),(0,a.ZI)(`[FireAndForget:${t}] Error: ${e.message}`),e}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=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(s))},t??9e5)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(s=>{try{const o=JSON.parse(s);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(clearTimeout(r),(0,a.b0)(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(o)))}catch(e){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,e)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class S{static{p(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=s.J1`
9
+ `,t=[];for(const e of this.PendingTransactions)t.push({EntityName:e.BaseEntity.EntityInfo.Name,EntityObjectJSON:await e.BaseEntity.GetDataObjectJSON(),OperationType:e.OperationType});const r={group:{Items:t,Variables:this.Variables.map(e=>({Name:e.Name,ItemIndex:this.MapVariableEntityObjectToPosition(e),FieldName:e.FieldName,Type:e.Type}))}},o=await this._provider.ExecuteGQL(e,r);if(o&&o.ExecuteTransactionGroup){const e=o.ExecuteTransactionGroup,t=[];for(let r=0;r<this.PendingTransactions.length;r++){const s=e.ResultsJSON[r],o=(0,n.NG)(s),i=this.PendingTransactions[r];t.push(new a.qT(i,o,null!==o))}return t}throw new Error("Failed to execute transaction group")}}class I{static{y(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:o,reject:i}=I.createCompletionPromise();s=I.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=I.subscribeToPubSub(e,o,s);const u=await I.executeMutation(e);if(!e.validateAck(u)){s&&clearTimeout(s);const r=u?.errorMessage??"Server rejected the request";return(0,a.ZI)(`[FireAndForget:${t}] Server rejected: ${r}`),e.createErrorResult(r)}return(0,a.b0)(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(e){throw s&&clearTimeout(s),(0,a.ZI)(`[FireAndForget:${t}] Error: ${e.message}`),e}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=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(s))},t??9e5)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(s=>{try{const o=JSON.parse(s);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(clearTimeout(r),(0,a.b0)(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(o)))}catch(e){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,e)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class S{static{y(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=s.J1`
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),a=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(a)}catch(e){return this.handlePromptError(e)}}preparePromptVariables(e){const t={promptId:e.promptId};return void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.templateData&&(t.templateData="object"==typeof e.templateData?JSON.stringify(e.templateData):e.templateData),void 0!==e.messages&&(t.messages=JSON.stringify(e.messages)),void 0!==e.overrideModelId&&(t.overrideModelId=e.overrideModelId),void 0!==e.overrideVendorId&&(t.overrideVendorId=e.overrideVendorId),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.skipValidation&&(t.skipValidation=e.skipValidation),void 0!==e.responseFormat&&(t.responseFormat=e.responseFormat),void 0!==e.temperature&&(t.temperature=e.temperature),void 0!==e.topP&&(t.topP=e.topP),void 0!==e.topK&&(t.topK=e.topK),void 0!==e.minP&&(t.minP=e.minP),void 0!==e.frequencyPenalty&&(t.frequencyPenalty=e.frequencyPenalty),void 0!==e.presencePenalty&&(t.presencePenalty=e.presencePenalty),void 0!==e.seed&&(t.seed=e.seed),void 0!==e.stopSequences&&(t.stopSequences=e.stopSequences),void 0!==e.includeLogProbs&&(t.includeLogProbs=e.includeLogProbs),void 0!==e.topLogProbs&&(t.topLogProbs=e.topLogProbs),void 0!==e.rerunFromPromptRunID&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),void 0!==e.systemPromptOverride&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return(0,a.ZI)(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),a=this.prepareAgentVariables(e,t,r);return a.fireAndForget=!0,await I.Execute({dataProvider:this._dataProvider,mutation:s,variables:a,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:p(e=>!0===e?.success,"validateAck"),isCompletionEvent:p(e=>this.isAgentCompletionEvent(e),"isCompletionEvent"),extractResult:p(e=>this.extractAgentResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardAgentProgress(t,e.onProgress):void 0,createErrorResult:p(e=>this.createAgentErrorResult(e),"createErrorResult")})}catch(e){return this.handleAgentError(e)}}buildRunAIAgentMutation(){return s.J1`
68
+ `,r=this.preparePromptVariables(e),a=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(a)}catch(e){return this.handlePromptError(e)}}preparePromptVariables(e){const t={promptId:e.promptId};return void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.templateData&&(t.templateData="object"==typeof e.templateData?JSON.stringify(e.templateData):e.templateData),void 0!==e.messages&&(t.messages=JSON.stringify(e.messages)),void 0!==e.overrideModelId&&(t.overrideModelId=e.overrideModelId),void 0!==e.overrideVendorId&&(t.overrideVendorId=e.overrideVendorId),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.skipValidation&&(t.skipValidation=e.skipValidation),void 0!==e.responseFormat&&(t.responseFormat=e.responseFormat),void 0!==e.temperature&&(t.temperature=e.temperature),void 0!==e.topP&&(t.topP=e.topP),void 0!==e.topK&&(t.topK=e.topK),void 0!==e.minP&&(t.minP=e.minP),void 0!==e.frequencyPenalty&&(t.frequencyPenalty=e.frequencyPenalty),void 0!==e.presencePenalty&&(t.presencePenalty=e.presencePenalty),void 0!==e.seed&&(t.seed=e.seed),void 0!==e.stopSequences&&(t.stopSequences=e.stopSequences),void 0!==e.includeLogProbs&&(t.includeLogProbs=e.includeLogProbs),void 0!==e.topLogProbs&&(t.topLogProbs=e.topLogProbs),void 0!==e.rerunFromPromptRunID&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),void 0!==e.systemPromptOverride&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return(0,a.ZI)(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),a=this.prepareAgentVariables(e,t,r);return a.fireAndForget=!0,await I.Execute({dataProvider:this._dataProvider,mutation:s,variables:a,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(e=>this.isAgentCompletionEvent(e),"isCompletionEvent"),extractResult:y(e=>this.extractAgentResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardAgentProgress(t,e.onProgress):void 0,createErrorResult:y(e=>this.createAgentErrorResult(e),"createErrorResult")})}catch(e){return this.handleAgentError(e)}}buildRunAIAgentMutation(){return s.J1`
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 void 0!==e.data&&(s.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(s.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(s.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(s.configurationId=e.configurationId),void 0!==e.conversationDetailId&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),void 0!==t&&(s.sourceArtifactId=t),void 0!==r&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return(0,n.NG)(e)}handleAgentError(e){const t=e?.message||String(e);(0,a.ZI)(`Error running AI agent: ${t}`);const r=t.includes("Failed to fetch")||t.includes("NetworkError");let s;return t.includes("timed out")||t.includes("timeout"),s=r?"Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":t,{success:!1,agentRun:void 0,errorMessage:s}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:p(e=>!0===e?.success,"validateAck"),isCompletionEvent:p(t=>this.isConversationDetailCompletionEvent(t,e.conversationDetailId),"isCompletionEvent"),extractResult:p(e=>this.extractAgentResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardConversationDetailProgress(t,e.onProgress):void 0,createErrorResult:p(e=>this.createAgentErrorResult(e),"createErrorResult")})}catch(e){return this.handleAgentError(e)}}buildConversationDetailMutation(){return s.J1`
109
+ `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return void 0!==e.data&&(s.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(s.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(s.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(s.configurationId=e.configurationId),void 0!==e.conversationDetailId&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),void 0!==t&&(s.sourceArtifactId=t),void 0!==r&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return(0,n.NG)(e)}handleAgentError(e){const t=e?.message||String(e);(0,a.ZI)(`Error running AI agent: ${t}`);const r=t.includes("Failed to fetch")||t.includes("NetworkError");let s;return t.includes("timed out")||t.includes("timeout"),s=r?"Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":t,{success:!1,agentRun:void 0,errorMessage:s}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(t=>this.isConversationDetailCompletionEvent(t,e.conversationDetailId),"isCompletionEvent"),extractResult:y(e=>this.extractAgentResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardConversationDetailProgress(t,e.onProgress):void 0,createErrorResult:y(e=>this.createAgentErrorResult(e),"createErrorResult")})}catch(e){return this.handleAgentError(e)}}buildConversationDetailMutation(){return s.J1`
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 void 0!==e.maxHistoryMessages&&(t.maxHistoryMessages=e.maxHistoryMessages),void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(t.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(t.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.createArtifacts&&(t.createArtifacts=e.createArtifacts),void 0!==e.createNotification&&(t.createNotification=e.createNotification),void 0!==e.sourceArtifactId&&(t.sourceArtifactId=e.sourceArtifactId),void 0!==e.sourceArtifactVersionId&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return"RunAIAgentResolver"===e.resolver&&"StreamingContent"===e.type&&"complete"===t?.type}isConversationDetailCompletionEvent(e,t){const r=e.data;return"RunAIAgentResolver"===e.resolver&&"StreamingContent"===e.type&&"complete"===r?.type&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?(0,n.NG)(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if("RunAIAgentResolver"!==e.resolver||"ExecutionProgress"!==e.type||"ok"!==e.status)return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if("RunAIAgentResolver"!==e.resolver||"ExecutionProgress"!==e.type||"ok"!==e.status)return;const r=e.data?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=s.J1`
148
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return void 0!==e.maxHistoryMessages&&(t.maxHistoryMessages=e.maxHistoryMessages),void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(t.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(t.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.createArtifacts&&(t.createArtifacts=e.createArtifacts),void 0!==e.createNotification&&(t.createNotification=e.createNotification),void 0!==e.sourceArtifactId&&(t.sourceArtifactId=e.sourceArtifactId),void 0!==e.sourceArtifactVersionId&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return"RunAIAgentResolver"===e.resolver&&"StreamingContent"===e.type&&"complete"===t?.type}isConversationDetailCompletionEvent(e,t){const r=e.data;return"RunAIAgentResolver"===e.resolver&&"StreamingContent"===e.type&&"complete"===r?.type&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?(0,n.NG)(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if("RunAIAgentResolver"!==e.resolver||"ExecutionProgress"!==e.type||"ok"!==e.status)return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if("RunAIAgentResolver"!==e.resolver||"ExecutionProgress"!==e.type||"ok"!==e.status)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=s.J1`
149
149
  mutation ExecuteSimplePrompt(
150
150
  $systemPrompt: String!,
151
151
  $messages: String,
@@ -183,9 +183,9 @@
183
183
  error
184
184
  }
185
185
  }
186
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const R="default";class D{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||R;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||R).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||R).set(e,t)}async Remove(e,t){this.getCategoryMap(t||R).delete(e)}async ClearCategory(e){const t=e||R;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||R);return t?Array.from(t.keys()):[]}}const E=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],w="Metadata_KVPairs";class f extends D{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(w)&&e.deleteObjectStore(w);for(const t of E)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return E.includes(t)}getStoreName(e){const t=e||R;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||R;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||R,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||R,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class C extends a.dZ{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,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class P extends a.Dn{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
186
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const R="default";class D{static{y(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||R;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||R).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||R).set(e,t)}async Remove(e,t){this.getCategoryMap(t||R).delete(e)}async ClearCategory(e){const t=e||R;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||R);return t?Array.from(t.keys()):[]}}const E=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],w="Metadata_KVPairs";class v extends D{static{y(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(w)&&e.deleteObjectStore(w);for(const t of E)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return E.includes(t)}getStoreName(e){const t=e||R;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||R;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||R,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||R,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class f extends a.dZ{static{y(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,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class P extends a.Dn{static{y(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
187
187
  ${this._innerCurrentUserQueryString}
188
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,P._instance||(P._instance=this)}static get Instance(){return P._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new S(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,d.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)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)):(P.Instance._configData=e,void 0===P.Instance._sessionId&&(P.Instance._sessionId=await this.GetPreferredUUID(s)),P.Instance._client||(P.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,P.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await P.Instance.SaveStoredSessionID(P.Instance._sessionId),this._sessionId=P.Instance._sessionId,this._client=P.Instance._client),super.Config(e)}catch(e){throw(0,a.ZI)(e),e}}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(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
188
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null,P._instance||(P._instance=this)}static get Instance(){return P._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new S(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,d.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)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)):(P.Instance._configData=e,void 0===P.Instance._sessionId&&(P.Instance._sessionId=await this.GetPreferredUUID(s)),P.Instance._client||(P.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,P.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await P.Instance.SaveStoredSessionID(P.Instance._sessionId),this._sessionId=P.Instance._sessionId,this._client=P.Instance._client),super.Config(e)}catch(e){throw(0,a.ZI)(e),e}}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(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
189
189
  query GetReportDataQuery ($ReportID: String!) {
190
190
  GetReportData(ReportID: $ReportID) {
191
191
  Success
@@ -234,7 +234,7 @@
234
234
  }
235
235
  }
236
236
  }
237
- `,a=(await this.ExecuteGQL(r,{input:t}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const n=a.results.map(e=>{if(("stale"===e.status||"no_validation"===e.status)&&e.Results){const t=JSON.parse(e.Results);return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,results:t,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}}return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}});return{success:a.success,results:n,errorMessage:a.errorMessage}}catch(e){return(0,a.ZI)(`Error in RunQueriesWithCacheCheck: ${e}`),{success:!1,results:[],errorMessage:e instanceof Error?e.message:String(e)}}}async InternalRunView(e,t){try{let r="",n="";if(!e)throw"No parameters passed to RunView";{const o={};let i,u;if(e.ViewEntity)u=e.ViewEntity,i=u.Entity;else{const{entityName:r,v:s}=await this.getEntityNameAndUserView(e,t);u=s,i=r}const c=this.Entities.find(e=>e.Name===i);if(!c)throw new Error(`Entity ${i} not found in metadata`);let l=!1;const d=(0,a.I)(c);e.ViewID?(r=`Run${d}ViewByID`,n="RunViewByIDInput",o.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,n="RunViewByNameInput",o.ViewName=e.ViewName):(l=!0,r=`Run${d}DynamicView`,n="RunDynamicViewInput",o.EntityName=e.EntityName),o.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",o.OrderBy=e.OrderBy?e.OrderBy:"",o.UserSearchString=e.UserSearchString?e.UserSearchString:"",o.Fields=e.Fields,o.IgnoreMaxRows=!!e.IgnoreMaxRows&&e.IgnoreMaxRows,void 0!==e.MaxRows&&(o.MaxRows=e.MaxRows),void 0!==e.StartRow&&(o.StartRow=e.StartRow),o.ForceAuditLog=!!e.ForceAuditLog&&e.ForceAuditLog,o.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(o.AuditLogDescription=e.AuditLogDescription),l||(o.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",o.ExcludeDataFromAllPriorViewRuns=!!e.ExcludeDataFromAllPriorViewRuns&&e.ExcludeDataFromAllPriorViewRuns,o.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",o.SaveViewResults=!!e.SaveViewResults&&e.SaveViewResults),e.Aggregates&&e.Aggregates.length>0&&(o.Aggregates=e.Aggregates.map(e=>({expression:e.expression,alias:e.alias})));const m=this.getViewRunTimeFieldList(c,u,e,l),y=e.Aggregates&&e.Aggregates.length>0?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",p=s.J1`
237
+ `,a=(await this.ExecuteGQL(r,{input:t}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const n=a.results.map(e=>{if(("stale"===e.status||"no_validation"===e.status)&&e.Results){const t=JSON.parse(e.Results);return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,results:t,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}}return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}});return{success:a.success,results:n,errorMessage:a.errorMessage}}catch(e){return(0,a.ZI)(`Error in RunQueriesWithCacheCheck: ${e}`),{success:!1,results:[],errorMessage:e instanceof Error?e.message:String(e)}}}async InternalRunView(e,t){try{let r="",n="";if(!e)throw"No parameters passed to RunView";{const o={};let i,u;if(e.ViewEntity)u=e.ViewEntity,i=u.Entity;else{const{entityName:r,v:s}=await this.getEntityNameAndUserView(e,t);u=s,i=r}const c=this.Entities.find(e=>e.Name===i);if(!c)throw new Error(`Entity ${i} not found in metadata`);let l=!1;const d=(0,a.I)(c);e.ViewID?(r=`Run${d}ViewByID`,n="RunViewByIDInput",o.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,n="RunViewByNameInput",o.ViewName=e.ViewName):(l=!0,r=`Run${d}DynamicView`,n="RunDynamicViewInput",o.EntityName=e.EntityName),o.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",o.OrderBy=e.OrderBy?e.OrderBy:"",o.UserSearchString=e.UserSearchString?e.UserSearchString:"",o.Fields=e.Fields,o.IgnoreMaxRows=!!e.IgnoreMaxRows&&e.IgnoreMaxRows,void 0!==e.MaxRows&&(o.MaxRows=e.MaxRows),void 0!==e.StartRow&&(o.StartRow=e.StartRow),o.ForceAuditLog=!!e.ForceAuditLog&&e.ForceAuditLog,o.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(o.AuditLogDescription=e.AuditLogDescription),l||(o.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",o.ExcludeDataFromAllPriorViewRuns=!!e.ExcludeDataFromAllPriorViewRuns&&e.ExcludeDataFromAllPriorViewRuns,o.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",o.SaveViewResults=!!e.SaveViewResults&&e.SaveViewResults),e.Aggregates&&e.Aggregates.length>0&&(o.Aggregates=e.Aggregates.map(e=>({expression:e.expression,alias:e.alias})));const m=this.getViewRunTimeFieldList(c,u,e,l),p=e.Aggregates&&e.Aggregates.length>0?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",y=s.J1`
238
238
  query RunViewQuery ($input: ${n}!) {
239
239
  ${r}(input: $input) {
240
240
  Results {
@@ -245,9 +245,9 @@
245
245
  TotalRowCount
246
246
  ExecutionTime
247
247
  Success
248
- ErrorMessage${y}
248
+ ErrorMessage${p}
249
249
  }
250
- }`;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:i,queryName:r,aggregateCount:o.Aggregates.length,aggregates:o.Aggregates});const g=await this.ExecuteGQL(p,{input:o});if(g&&g[r]){const e=g[r].AggregateResults;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:i,aggregateResultCount:e?.length||0,aggregateResults:e,aggregateExecutionTime:g[r].AggregateExecutionTime});const t=g[r].Results;if(t&&t.length>0){const e=c.Fields.filter(e=>e.CodeName!==e.Name&&void 0!==e.CodeName);t.forEach(t=>{this.ConvertBackToMJFields(t),e.forEach(e=>{t[e.Name]=t[e.CodeName]})})}return g[r]}}return null}catch(e){throw(0,a.ZI)(e),e}}async InternalRunViews(e,t){try{let r=[],n=[],o=[];for(const s of e){let e="",i="";const u={};let c=null,l=null;if(s.ViewEntity)l=s.ViewEntity,c=l.Get("Entity");else{const{entityName:e,v:r}=await this.getEntityNameAndUserView(s,t);l=r,c=e}const d=this.Entities.find(e=>e.Name===c);if(!d)throw new Error(`Entity ${c} not found in metadata`);n.push(d);let m=!1;const y=(0,a.I)(d);s.ViewID?(e=`Run${y}ViewByID`,i="RunViewByIDInput",u.ViewID=s.ViewID):s.ViewName?(e=`Run${y}ViewByName`,i="RunViewByNameInput",u.ViewName=s.ViewName):(m=!0,e=`Run${y}DynamicView`,i="RunDynamicViewInput",u.EntityName=s.EntityName),u.ExtraFilter=s.ExtraFilter||"",u.OrderBy=s.OrderBy||"",u.UserSearchString=s.UserSearchString||"",u.Fields=s.Fields,u.IgnoreMaxRows=s.IgnoreMaxRows||!1,void 0!==s.MaxRows&&(u.MaxRows=s.MaxRows),void 0!==s.StartRow&&(u.StartRow=s.StartRow),u.ForceAuditLog=s.ForceAuditLog||!1,u.ResultType=s.ResultType||"simple",s.AuditLogDescription&&s.AuditLogDescription.length>0&&(u.AuditLogDescription=s.AuditLogDescription),m||(u.ExcludeUserViewRunID=s.ExcludeUserViewRunID||"",u.ExcludeDataFromAllPriorViewRuns=s.ExcludeDataFromAllPriorViewRuns||!1,u.OverrideExcludeFilter=s.OverrideExcludeFilter||"",u.SaveViewResults=s.SaveViewResults||!1),s.Aggregates&&s.Aggregates.length>0&&(u.Aggregates=s.Aggregates.map(e=>({expression:e.expression,alias:e.alias}))),r.push(u),o.push(...this.getViewRunTimeFieldList(d,l,s,m))}const i=e.some(e=>e.Aggregates&&e.Aggregates.length>0)?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",u=s.J1`
250
+ }`;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:i,queryName:r,aggregateCount:o.Aggregates.length,aggregates:o.Aggregates});const g=await this.ExecuteGQL(y,{input:o});if(g&&g[r]){const e=g[r].AggregateResults;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:i,aggregateResultCount:e?.length||0,aggregateResults:e,aggregateExecutionTime:g[r].AggregateExecutionTime});const t=g[r].Results;if(t&&t.length>0){const e=c.Fields.filter(e=>e.CodeName!==e.Name&&void 0!==e.CodeName);t.forEach(t=>{this.ConvertBackToMJFields(t),e.forEach(e=>{t[e.Name]=t[e.CodeName]})})}return g[r]}}return null}catch(e){throw(0,a.ZI)(e),e}}async InternalRunViews(e,t){try{let r=[],n=[],o=[];for(const s of e){let e="",i="";const u={};let c=null,l=null;if(s.ViewEntity)l=s.ViewEntity,c=l.Get("Entity");else{const{entityName:e,v:r}=await this.getEntityNameAndUserView(s,t);l=r,c=e}const d=this.Entities.find(e=>e.Name===c);if(!d)throw new Error(`Entity ${c} not found in metadata`);n.push(d);let m=!1;const p=(0,a.I)(d);s.ViewID?(e=`Run${p}ViewByID`,i="RunViewByIDInput",u.ViewID=s.ViewID):s.ViewName?(e=`Run${p}ViewByName`,i="RunViewByNameInput",u.ViewName=s.ViewName):(m=!0,e=`Run${p}DynamicView`,i="RunDynamicViewInput",u.EntityName=s.EntityName),u.ExtraFilter=s.ExtraFilter||"",u.OrderBy=s.OrderBy||"",u.UserSearchString=s.UserSearchString||"",u.Fields=s.Fields,u.IgnoreMaxRows=s.IgnoreMaxRows||!1,void 0!==s.MaxRows&&(u.MaxRows=s.MaxRows),void 0!==s.StartRow&&(u.StartRow=s.StartRow),u.ForceAuditLog=s.ForceAuditLog||!1,u.ResultType=s.ResultType||"simple",s.AuditLogDescription&&s.AuditLogDescription.length>0&&(u.AuditLogDescription=s.AuditLogDescription),m||(u.ExcludeUserViewRunID=s.ExcludeUserViewRunID||"",u.ExcludeDataFromAllPriorViewRuns=s.ExcludeDataFromAllPriorViewRuns||!1,u.OverrideExcludeFilter=s.OverrideExcludeFilter||"",u.SaveViewResults=s.SaveViewResults||!1),s.Aggregates&&s.Aggregates.length>0&&(u.Aggregates=s.Aggregates.map(e=>({expression:e.expression,alias:e.alias}))),r.push(u),o.push(...this.getViewRunTimeFieldList(d,l,s,m))}const i=e.some(e=>e.Aggregates&&e.Aggregates.length>0)?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",u=s.J1`
251
251
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
252
252
  RunViews(input: $input) {
253
253
  Results {
@@ -352,7 +352,7 @@
352
352
  }`,r={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(e=>({FieldName:e.FieldName,Value:e.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(e=>e.Copy())};return(await this.ExecuteGQL(t,{request:r}))?.MergeRecords}catch(t){return(0,a.ZI)(t),{Success:!1,OverallStatus:t&&t.message?t.message:t,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const t=new a.KV;return t.StartedAt=new Date,t.EndedAt=new Date,t.Type=e.IsSaved?"update":"create",t.Success=!0,t.NewValues=e.GetAll(),e.ResultHistory.push(t),t.NewValues}const n=new a.KV;try{e.RegisterTransactionPreprocessing();const t={input:{}},o=e.IsSaved?"Update":"Create";n.StartedAt=new Date,n.Type=e.IsSaved?"update":"create",n.OriginalValues=e.Fields.map(e=>({FieldName:e.CodeName,Value:e.Value})),e.ResultHistory.push(n);const i=(0,a.I)(e.EntityInfo),u=`${o}${i}`,c=e.Fields.filter(t=>!t.ReadOnly||t.IsPrimaryKey&&e.IsSaved),l=new g,d=` ${u}(input: $input) {\n ${e.Fields.map(e=>l.MapFieldName(e.CodeName)).join("\n ")}\n }`,m=s.J1`mutation ${o}${i} ($input: ${u}Input!) {
353
353
  ${d}
354
354
  }
355
- `;for(let r=0;r<c.length;r++){const s=c[r];let n=e.Get(s.Name);if(n)switch(s.EntityFieldInfo.TSType){case a.$S.Date:n=n.getTime();break;case a.$S.Boolean:"boolean"!=typeof n&&(n=0!==parseInt(n));break;case a.$S.Number:if("number"!=typeof n){const e=Number(n);isNaN(e)||(n=e)}}null===n&&!1===s.EntityFieldInfo.AllowsNull&&(n=null!==s.EntityFieldInfo.DefaultValue?s.EntityFieldInfo.DefaultValue:s.FieldType===a.$S.Number||s.FieldType===a.$S.Boolean?0:""),t.input[s.CodeName]=n}if("update"===o.trim().toLowerCase()&&!1===r.SkipOldValuesCheck){const r=[];e.Fields.forEach(e=>{let t=null;null!==e.OldValue&&void 0!==e.OldValue&&(t=e.EntityFieldInfo.TSType===a.$S.Date?e.OldValue.getTime().toString():e.EntityFieldInfo.TSType===a.$S.Boolean?!0===e.OldValue?"1":"0":"string"!=typeof e.OldValue?e.OldValue.toString():e.OldValue),r.push({Key:e.CodeName,Value:t})}),t.input.OldValues___=r}if(e.TransactionGroup){const r=[{varName:"input",inputType:u+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new a.U1(e,"create"===n.Type?"Create":"Update",d,t,{mutationName:u,mutationInputTypes:r},(e,t)=>{n.EndedAt=new Date,t&&e?(n.Success=!0,n.NewValues=this.ConvertBackToMJFields(e)):(n.Success=!1,n.Message="Transaction failed")})),!0}{const r=await this.ExecuteGQL(m,t);if(r&&r[u])return n.Success=!0,n.EndedAt=new Date,n.NewValues=this.ConvertBackToMJFields(r[u]),n.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(e){return n.Success=!1,n.EndedAt=new Date,n.Message=e.response?.errors?.length>0?e.response.errors[0].message:e.message,(0,a.ZI)(e),null}}async Load(e,t,r=null,n){try{const n={};let o="",i="";for(let r=0;r<t.KeyValuePairs.length;r++){const s=e.Fields.find(e=>e.Name.trim().toLowerCase()===t.KeyValuePairs[r].FieldName.trim().toLowerCase()).EntityFieldInfo,u=t.GetValueByIndex(r),c=s.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${s.CodeName}: ${c}!`,o.length>0&&(o+=", "),o+=`${s.CodeName}: $${s.CodeName}`,s.TSType===a.$S.Number){if(isNaN(t.GetValueByIndex(r)))throw new Error(`Primary Key value ${u} (${s.Name}) is not a valid number`);n[s.CodeName]=parseInt(u)}else n[s.CodeName]=u}const u=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=(0,a.I)(e.EntityInfo),l=(new g,s.J1`query Single${c}${u.length>0?"Full":""} (${i}) {
355
+ `;for(let r=0;r<c.length;r++){const s=c[r];let n=e.Get(s.Name);if(n)switch(s.EntityFieldInfo.TSType){case a.$S.Date:n=n.getTime();break;case a.$S.Boolean:"boolean"!=typeof n&&(n=0!==parseInt(n));break;case a.$S.Number:if("number"!=typeof n){const e=Number(n);isNaN(e)||(n=e)}}null===n&&!1===s.EntityFieldInfo.AllowsNull&&(n=null!==s.EntityFieldInfo.DefaultValue?s.EntityFieldInfo.DefaultValue:s.FieldType===a.$S.Number||s.FieldType===a.$S.Boolean?0:""),t.input[l.MapFieldName(s.CodeName)]=n}if("update"===o.trim().toLowerCase()&&!1===r.SkipOldValuesCheck){const r=[];e.Fields.forEach(e=>{let t=null;null!==e.OldValue&&void 0!==e.OldValue&&(t=e.EntityFieldInfo.TSType===a.$S.Date?e.OldValue.getTime().toString():e.EntityFieldInfo.TSType===a.$S.Boolean?!0===e.OldValue?"1":"0":"string"!=typeof e.OldValue?e.OldValue.toString():e.OldValue),r.push({Key:l.MapFieldName(e.CodeName),Value:t})}),t.input.OldValues___=r}if(e.TransactionGroup){const r=[{varName:"input",inputType:u+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new a.U1(e,"create"===n.Type?"Create":"Update",d,t,{mutationName:u,mutationInputTypes:r},(e,t)=>{n.EndedAt=new Date,t&&e?(n.Success=!0,n.NewValues=this.ConvertBackToMJFields(e)):(n.Success=!1,n.Message="Transaction failed")})),!0}{const r=await this.ExecuteGQL(m,t);if(r&&r[u])return n.Success=!0,n.EndedAt=new Date,n.NewValues=this.ConvertBackToMJFields(r[u]),n.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(e){return n.Success=!1,n.EndedAt=new Date,n.Message=e.response?.errors?.length>0?e.response.errors[0].message:e.message,(0,a.ZI)(e),null}}async Load(e,t,r=null,n){try{const n={};let o="",i="";for(let r=0;r<t.KeyValuePairs.length;r++){const s=e.Fields.find(e=>e.Name.trim().toLowerCase()===t.KeyValuePairs[r].FieldName.trim().toLowerCase()).EntityFieldInfo,u=t.GetValueByIndex(r),c=s.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${s.CodeName}: ${c}!`,o.length>0&&(o+=", "),o+=`${s.CodeName}: $${s.CodeName}`,s.TSType===a.$S.Number){if(isNaN(t.GetValueByIndex(r)))throw new Error(`Primary Key value ${u} (${s.Name}) is not a valid number`);n[s.CodeName]=parseInt(u)}else n[s.CodeName]=u}const u=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=(0,a.I)(e.EntityInfo),l=(new g,s.J1`query Single${c}${u.length>0?"Full":""} (${i}) {
356
356
  ${c}(${o}) {
357
357
  ${e.Fields.filter(e=>!e.EntityFieldInfo.IsBinaryFieldType).map(e=>e.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?e.CodeName.replace("__mj_","_mj__"):e.CodeName).join("\n ")}
358
358
  ${u}
@@ -422,14 +422,24 @@
422
422
  ErrorMessage
423
423
  Result
424
424
  }
425
- }`,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)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return P.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("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}async RefreshToken(){const e=P.Instance&&P.Instance._configData===this._configData;if(e&&P.Instance._refreshPromise)return P.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(P.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&P.Instance&&(P.Instance._refreshPromise=null)}}async performTokenRefresh(){if(!this._configData.Data.RefreshTokenFunction)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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,P.Instance&&P.Instance._configData===this._configData&&(P.Instance._client=t)}}}static async RefreshToken(){return P.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new f:this._localStorageProvider=new a.KW),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&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,l.UU)({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(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 i.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:p(e=>{r.next(e.data)},"next"),error:p(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new i.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
425
+ }`,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)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return P.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("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}async RefreshToken(){const e=P.Instance&&P.Instance._configData===this._configData;if(e&&P.Instance._refreshPromise)return P.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(P.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&P.Instance&&(P.Instance._refreshPromise=null)}}async performTokenRefresh(){if(!this._configData.Data.RefreshTokenFunction)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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,P.Instance&&P.Instance._configData===this._configData&&(P.Instance._client=t)}}}static async RefreshToken(){return P.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new v:this._localStorageProvider=new a.KW),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&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,l.UU)({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!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(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 i.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:y(e=>{r.next(e.data)},"next"),error:y(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:y(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new i.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
426
426
  statusUpdates(sessionId: $sessionId) {
427
427
  date
428
428
  message
429
429
  sessionId
430
430
  }
431
431
  }
432
- `,n=new u.B,o=this.getOrCreateWSClient(),l=new c.yU;return l.add(new i.c(t=>{const r=o.subscribe({query:a,variables:{sessionId:e}},{next:p(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:p(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:p(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:p(e=>n.next(e),"next"),error:p(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new i.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.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;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function v(e){const t=new P;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),n.rt.Instance.RaiseEvent({event:n.UK.LoggedIn,eventCode:null,component:this,args:null}),t}p(v,"setupGraphQLClient");class ${static{p(this,"SyncRolesAndUsersResult")}}class A{static{p(this,"RoleInput")}}class N{static{p(this,"UserInput")}}class b{static{p(this,"RolesAndUsersInput")}}var x,M=((x=M||{}).Create="Create",x.Update="Update",x.CreateOrUpdate="CreateOrUpdate",x.Delete="Delete",x.DeleteWithFilter="DeleteWithFilter",x);class F{static{p(this,"ActionItemInput")}}class Q{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class T{static{p(this,"ActionItemOutput")}}class L{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}resolvePlatformSQL(e){if(null!=e)return(0,a.WV)(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,n.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t="query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",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(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t="query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",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(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t="query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",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(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t="query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",r=e.map(e=>({...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&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) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,n.NG)(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(0,a.ZI)(`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(void 0!==e.Parameters&&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) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,n.NG)(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(0,a.ZI)(`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 t=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("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) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(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(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
432
+ `,n=new u.B,o=this.getOrCreateWSClient(),l=new c.yU;return l.add(new i.c(t=>{const r=o.subscribe({query:a,variables:{sessionId:e}},{next:y(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:y(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:y(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:y(e=>n.next(e),"next"),error:y(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:y(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new i.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.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=s.J1`subscription CacheInvalidation {
433
+ cacheInvalidation {
434
+ EntityName
435
+ PrimaryKeyValues
436
+ Action
437
+ SourceServerID
438
+ Timestamp
439
+ OriginSessionID
440
+ RecordData
441
+ }
442
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:y(e=>{const t=e?.cacheInvalidation;if(!t)return;if(t.OriginSessionID&&t.OriginSessionID===this.sessionId)return void console.log(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${t.EntityName}" (action: ${t.Action})`);console.log(`[GraphQLDataProvider] Cache invalidation received: ${t.Action} for "${t.EntityName}" from server ${t.SourceServerID?.substring(0,8)||"unknown"}`);const r={type:"remote-invalidate",entityName:t.EntityName,baseEntity:null,payload:{primaryKeyValues:t.PrimaryKeyValues,action:t.Action,sourceServerId:t.SourceServerID,timestamp:t.Timestamp,recordData:t.RecordData}};n.rt.Instance.RaiseEvent({event:n.UK.ComponentEvent,eventCode:a.HC.BaseEventCode,args:r,component:this})},"next"),error:y(e=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",e),this._cacheInvalidationSubscription=null},"error"),complete:y(()=>{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,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function C(e){const t=new P;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),n.rt.Instance.RaiseEvent({event:n.UK.LoggedIn,eventCode:null,component:this,args:null}),t}y(C,"setupGraphQLClient");class ${static{y(this,"SyncRolesAndUsersResult")}}class A{static{y(this,"RoleInput")}}class N{static{y(this,"UserInput")}}class b{static{y(this,"RolesAndUsersInput")}}var x,M=((x=M||{}).Create="Create",x.Update="Update",x.CreateOrUpdate="CreateOrUpdate",x.Delete="Delete",x.DeleteWithFilter="DeleteWithFilter",x);class F{static{y(this,"ActionItemInput")}}class Q{static{y(this,"SyncDataResult")}constructor(){this.Results=[]}}class L{static{y(this,"ActionItemOutput")}}class T{static{y(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}resolvePlatformSQL(e){if(null!=e)return(0,a.WV)(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,n.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t="query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",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(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t="query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",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(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t="query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",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(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t="query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",r=e.map(e=>({...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&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) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,n.NG)(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(0,a.ZI)(`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(void 0!==e.Parameters&&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) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,n.NG)(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(0,a.ZI)(`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 t=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("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) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(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(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
433
443
  query RunAIPromptSystemUser(
434
444
  $promptId: String!,
435
445
  $data: String,
@@ -553,7 +563,7 @@
553
563
  error
554
564
  }
555
565
  }
556
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,r);if(!a?.EmbedTextSystemUser)return{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class G{static{p(this,"GetDataOutput")}}class V{static{p(this,"SimpleRemoteEntityOutput")}}class U{static{p(this,"SimpleRemoteEntity")}}class _{static{p(this,"SimpleRemoteEntityField")}}class O{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(e){return this.handleActionError(e,t)}}serializeActionParameters(e){if(e)return e.map(e=>{let t=e.Value;return null!=t&&"object"==typeof t&&(t=JSON.stringify(t)),{...e,Value:t}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=s.J1`
566
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,r);if(!a?.EmbedTextSystemUser)return{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class G{static{y(this,"GetDataOutput")}}class V{static{y(this,"SimpleRemoteEntityOutput")}}class U{static{y(this,"SimpleRemoteEntity")}}class _{static{y(this,"SimpleRemoteEntityField")}}class O{static{y(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(e){return this.handleActionError(e,t)}}serializeActionParameters(e){if(e)return e.map(e=>{let t=e.Value;return null!=t&&"object"==typeof t&&(t=JSON.stringify(t)),{...e,Value:t}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=s.J1`
557
567
  mutation RunAction($input: RunActionInput!) {
558
568
  RunAction(input: $input) {
559
569
  Success
@@ -570,7 +580,7 @@
570
580
  ResultData
571
581
  }
572
582
  }
573
- `;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(e){(0,a.ZI)(`Failed to parse entity action result data: ${e}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return(0,a.ZI)(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class k{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(e){return this.handleCreateAPIKeyError(e)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=s.J1`
583
+ `;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(e){(0,a.ZI)(`Failed to parse entity action result data: ${e}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return(0,a.ZI)(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class K{static{y(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(e){return this.handleCreateAPIKeyError(e)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=s.J1`
574
584
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
575
585
  CreateAPIKey(input: $input) {
576
586
  Success
@@ -586,7 +596,7 @@
586
596
  Error
587
597
  }
588
598
  }
589
- `,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(e){const t=e;return(0,a.ZI)(`Error revoking API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}}}class K{static{p(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:p(e=>!0===e?.success,"validateAck"),isCompletionEvent:p(t=>this.isTestCompletionEvent(t,e.testId),"isCompletionEvent"),extractResult:p(e=>this.extractTestResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardTestProgress(t,e.onProgress):void 0,createErrorResult:p(e=>({success:!1,errorMessage:e,result:null}),"createErrorResult")})}catch(e){return this.handleError(e,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:p(e=>!0===e?.success,"validateAck"),isCompletionEvent:p(t=>this.isSuiteCompletionEvent(t,e.suiteId),"isCompletionEvent"),extractResult:p(e=>this.extractSuiteResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardTestProgress(t,e.onProgress):void 0,createErrorResult:p(e=>({success:!1,errorMessage:e,result:null}),"createErrorResult")})}catch(e){return this.handleError(e,"RunTestSuite")}}async IsTestRunning(e){try{const t=s.J1`
599
+ `,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(e){const t=e;return(0,a.ZI)(`Error revoking API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}}}class j{static{y(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(t=>this.isTestCompletionEvent(t,e.testId),"isCompletionEvent"),extractResult:y(e=>this.extractTestResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardTestProgress(t,e.onProgress):void 0,createErrorResult:y(e=>({success:!1,errorMessage:e,result:null}),"createErrorResult")})}catch(e){return this.handleError(e,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(t=>this.isSuiteCompletionEvent(t,e.suiteId),"isCompletionEvent"),extractResult:y(e=>this.extractSuiteResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardTestProgress(t,e.onProgress):void 0,createErrorResult:y(e=>({success:!1,errorMessage:e,result:null}),"createErrorResult")})}catch(e){return this.handleError(e,"RunTestSuite")}}async IsTestRunning(e){try{const t=s.J1`
590
600
  query IsTestRunning($testId: String!) {
591
601
  IsTestRunning(testId: $testId)
592
602
  }
@@ -644,7 +654,7 @@
644
654
  result
645
655
  }
646
656
  }
647
- `}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"RunTestResolver"===e.resolver&&"FireAndForgetComplete"===e.type&&"complete"===r?.type&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return"RunTestResolver"===e.resolver&&"FireAndForgetSuiteComplete"===e.type&&"complete"===r?.type&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?(0,n.NG)(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?(0,n.NG)(t.result):null}}forwardTestProgress(e,t){if("RunTestResolver"===e.resolver&&"TestExecutionProgress"===e.type&&"ok"===e.status){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const r=e.message;return(0,a.ZI)(`${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 j{static{p(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=s.J1`
657
+ `}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"RunTestResolver"===e.resolver&&"FireAndForgetComplete"===e.type&&"complete"===r?.type&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return"RunTestResolver"===e.resolver&&"FireAndForgetSuiteComplete"===e.type&&"complete"===r?.type&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?(0,n.NG)(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?(0,n.NG)(t.result):null}}forwardTestProgress(e,t){if("RunTestResolver"===e.resolver&&"TestExecutionProgress"===e.type&&"ok"===e.status){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const r=e.message;return(0,a.ZI)(`${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 k{static{y(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=s.J1`
648
658
  query GetRegistryComponent(
649
659
  $registryName: String!,
650
660
  $namespace: String!,
@@ -728,7 +738,7 @@
728
738
  error
729
739
  }
730
740
  }
731
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(e){return(0,a.ZI)(e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}}class J{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(t=>{try{const r=JSON.parse(t);"VersionHistoryResolver"===r.resolver&&"CreateLabelProgress"===r.type&&"ok"===r.status&&r.data&&e.OnProgress(r.data)}catch{}}));const r=s.J1`
741
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(e){return(0,a.ZI)(e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}}class J{static{y(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const r=JSON.parse(t);"VersionHistoryResolver"===r.resolver&&"CreateLabelProgress"===r.type&&"ok"===r.status&&r.data&&e.OnProgress(r.data)}catch{}}));const r=s.J1`
732
742
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
733
743
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
734
744
  Success
@@ -744,7 +754,7 @@
744
754
  }
745
755
  }
746
756
  }
747
- `,a={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,a);return this.processResult(n)}catch(e){const t=e instanceof Error?e.message:String(e);return(0,a.ZI)(`GraphQLVersionHistoryClient.CreateLabel error: ${t}`),{Success:!1,Error:t}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return null!=e.Description&&(t.Description=e.Description),null!=e.Scope&&(t.Scope=e.Scope),null!=e.EntityName&&(t.EntityName=e.EntityName),null!=e.ParentID&&(t.ParentID=e.ParentID),null!=e.ExternalSystemID&&(t.ExternalSystemID=e.ExternalSystemID),null!=e.IncludeDependencies&&(t.IncludeDependencies=e.IncludeDependencies),null!=e.MaxDepth&&(t.MaxDepth=e.MaxDepth),null!=e.ExcludeEntities&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(e=>({Key:e.Key,Value:e.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(e=>({EntityName:e.EntityName??"",RecordID:e.RecordID??"",ErrorMessage:e.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 B{static{p(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const a=s.J1`
757
+ `,a={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,a);return this.processResult(n)}catch(e){const t=e instanceof Error?e.message:String(e);return(0,a.ZI)(`GraphQLVersionHistoryClient.CreateLabel error: ${t}`),{Success:!1,Error:t}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return null!=e.Description&&(t.Description=e.Description),null!=e.Scope&&(t.Scope=e.Scope),null!=e.EntityName&&(t.EntityName=e.EntityName),null!=e.ParentID&&(t.ParentID=e.ParentID),null!=e.ExternalSystemID&&(t.ExternalSystemID=e.ExternalSystemID),null!=e.IncludeDependencies&&(t.IncludeDependencies=e.IncludeDependencies),null!=e.MaxDepth&&(t.MaxDepth=e.MaxDepth),null!=e.ExcludeEntities&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(e=>({Key:e.Key,Value:e.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(e=>({EntityName:e.EntityName??"",RecordID:e.RecordID??"",ErrorMessage:e.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 B{static{y(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const a=s.J1`
748
758
  query ListStorageObjects($input: ListStorageObjectsInput!) {
749
759
  ListStorageObjects(input: $input) {
750
760
  objects {
@@ -828,4 +838,98 @@
828
838
  failedAccounts
829
839
  }
830
840
  }
831
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(a,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(e=>({accountId:e.accountID,accountName:e.accountName,success:e.success,errorMessage:e.errorMessage,results:e.results.map(e=>({path:e.path,name:e.name,size:e.size,contentType:e.contentType,lastModified:new Date(e.lastModified),relevance:e.relevance,excerpt:e.excerpt,matchInFilename:e.matchInFilename,objectId:e.objectId})),totalMatches:e.totalMatches,hasMore:e.hasMore,nextPageToken:e.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(t){return(0,a.ZI)(`Error searching across accounts: ${t}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}}}]);
841
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(a,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(e=>({accountId:e.accountID,accountName:e.accountName,success:e.success,errorMessage:e.errorMessage,results:e.results.map(e=>({path:e.path,name:e.name,size:e.size,contentType:e.contentType,lastModified:new Date(e.lastModified),relevance:e.relevance,excerpt:e.excerpt,matchInFilename:e.matchInFilename,objectId:e.objectId})),totalMatches:e.totalMatches,hasMore:e.hasMore,nextPageToken:e.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(t){return(0,a.ZI)(`Error searching across accounts: ${t}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class q{static{y(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=s.J1`
842
+ query IntegrationDiscoverObjects($companyIntegrationID: String!) {
843
+ IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
844
+ Success
845
+ Message
846
+ Objects {
847
+ Name
848
+ Label
849
+ SupportsIncrementalSync
850
+ SupportsWrite
851
+ }
852
+ }
853
+ }
854
+ `,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(e){return this.handleError(e,[])}}async DiscoverFields(e,t){try{const r=s.J1`
855
+ query IntegrationDiscoverFields($companyIntegrationID: String!, $objectName: String!) {
856
+ IntegrationDiscoverFields(companyIntegrationID: $companyIntegrationID, objectName: $objectName) {
857
+ Success
858
+ Message
859
+ Fields {
860
+ Name
861
+ Label
862
+ DataType
863
+ IsRequired
864
+ IsUniqueKey
865
+ IsReadOnly
866
+ }
867
+ }
868
+ }
869
+ `,a=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objectName:t}))?.IntegrationDiscoverFields;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Data:a.Fields??[]}}catch(e){return this.handleError(e,[])}}async TestConnection(e){try{const t=s.J1`
870
+ query IntegrationTestConnection($companyIntegrationID: String!) {
871
+ IntegrationTestConnection(companyIntegrationID: $companyIntegrationID) {
872
+ Success
873
+ Message
874
+ ServerVersion
875
+ }
876
+ }
877
+ `,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(e){const t=e;return(0,a.ZI)(`Error testing integration connection: ${t}`),{Success:!1,Message:`Error: ${t.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const a=s.J1`
878
+ query IntegrationSchemaPreview(
879
+ $companyIntegrationID: String!,
880
+ $objects: [SchemaPreviewObjectInput!]!,
881
+ $platform: String!
882
+ ) {
883
+ IntegrationSchemaPreview(
884
+ companyIntegrationID: $companyIntegrationID,
885
+ objects: $objects,
886
+ platform: $platform
887
+ ) {
888
+ Success
889
+ Message
890
+ Files {
891
+ FilePath
892
+ Content
893
+ Description
894
+ }
895
+ Warnings
896
+ }
897
+ }
898
+ `,n=(await this._dataProvider.ExecuteGQL(a,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!n)throw new Error("Invalid response from server");return{Success:n.Success,Message:n.Message,Files:n.Files??[],Warnings:n.Warnings??[]}}catch(e){const t=e;return(0,a.ZI)(`Error generating schema preview: ${t}`),{Success:!1,Message:`Error: ${t.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const a=s.J1`
899
+ query IntegrationPreviewData(
900
+ $companyIntegrationID: String!,
901
+ $objectName: String!,
902
+ $limit: Float!
903
+ ) {
904
+ IntegrationPreviewData(
905
+ companyIntegrationID: $companyIntegrationID,
906
+ objectName: $objectName,
907
+ limit: $limit
908
+ ) {
909
+ Success
910
+ Message
911
+ Records {
912
+ Data
913
+ }
914
+ }
915
+ }
916
+ `,n=(await this._dataProvider.ExecuteGQL(a,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!n)throw new Error("Invalid response from server");return{Success:n.Success,Message:n.Message,Records:n.Records??[]}}catch(e){const t=e;return(0,a.ZI)(`Error previewing integration data: ${t}`),{Success:!1,Message:`Error: ${t.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=s.J1`
917
+ query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
918
+ IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
919
+ Success
920
+ Message
921
+ DefaultSchemaName
922
+ DefaultObjects {
923
+ SourceObjectName
924
+ TargetTableName
925
+ TargetEntityName
926
+ SyncEnabled
927
+ FieldMappings {
928
+ SourceFieldName
929
+ DestinationFieldName
930
+ IsKeyField
931
+ }
932
+ }
933
+ }
934
+ }
935
+ `,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(e){const t=e;return(0,a.ZI)(`Error getting default config: ${t}`),{Success:!1,Message:`Error: ${t.message}`}}}handleError(e,t){const r=e;return(0,a.ZI)(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}}}]);