@memberjunction/graphql-dataprovider 5.43.0 → 5.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var j=Object.defineProperty;var l=(m,e)=>j(m,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),R=require("@memberjunction/global"),G=require("@memberjunction/core-entities"),L=require("rxjs"),J=require("graphql-ws"),W=require("uuid"),z=require("@tempfix/idb");class P{static{l(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(P.DB_PREFIX)?P.GQL_PREFIX+e.substring(P.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(P.GQL_PREFIX)?P.DB_PREFIX+e.substring(P.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 q extends c.TransactionGroupBase{static{l(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
1
+ "use strict";var j=Object.defineProperty;var d=(m,e)=>j(m,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),R=require("@memberjunction/global"),G=require("@memberjunction/core-entities"),L=require("rxjs"),J=require("graphql-ws"),W=require("uuid"),z=require("@tempfix/idb");class P{static{d(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(P.DB_PREFIX)?P.GQL_PREFIX+e.substring(P.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(P.GQL_PREFIX)?P.DB_PREFIX+e.substring(P.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 q extends c.TransactionGroupBase{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],g=R.SafeJSONParse(a),d=this.PendingTransactions[i];o.push(new c.TransactionResult(d,g,g!==null))}return o}else throw new Error("Failed to execute transaction group")}}const H=720*1e3,X=6;class ${static{l(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??H,s=e.maxStallReconciles??X;let n,o=!1,i=0;const{promise:a,resolve:g,reject:d}=$.createCompletionPromise(),f=l(E=>{o||(o=!0,S.clear(),E())},"finish"),I=l(E=>f(()=>g(E)),"settleResolve"),y=l(E=>f(()=>d(E)),"settleReject"),p=l(async()=>{if(o)return;if(!e.onStall){y(new Error($.timeoutMessage(e.timeoutErrorMessage,r)));return}let E;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){y(D);return}o||(E==="continue"?++i>s?y(new Error(`The operation is still reported as running but no signal has arrived after ${i} checks. Please refresh the page to check the latest status.`)):S.reset():"resolve"in E?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),I(E.resolve)):y(E.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:l(()=>{i=0,S.reset()},"onActivity"),onCompletion:l(D=>I(D),"onCompletion"),onStreamEnd:l(()=>{p()},"onStreamEnd")});const E=await $.executeMutation(e);if(!e.validateAck(E)){S.clear();const D=E?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await a}catch(E){const D=E;throw c.LogError(`[FireAndForget:${t}] Error: ${D.message}`),E}finally{S.clear(),n&&n.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:l(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:l(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:l(n=>{t.onActivity();try{const o=JSON.parse(n);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(o)))}catch(o){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,o)}},"next"),error:l(()=>t.onStreamEnd(),"error"),complete:l(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class U{static{l(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],g=R.SafeJSONParse(a),l=this.PendingTransactions[i];o.push(new c.TransactionResult(l,g,g!==null))}return o}else throw new Error("Failed to execute transaction group")}}const H=720*1e3,X=6;class ${static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??H,s=e.maxStallReconciles??X;let n,o=!1,i=0;const{promise:a,resolve:g,reject:l}=$.createCompletionPromise(),h=d(E=>{o||(o=!0,S.clear(),E())},"finish"),f=d(E=>h(()=>g(E)),"settleResolve"),y=d(E=>h(()=>l(E)),"settleReject"),p=d(async()=>{if(o)return;if(!e.onStall){y(new Error($.timeoutMessage(e.timeoutErrorMessage,r)));return}let E;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){y(D);return}o||(E==="continue"?++i>s?y(new Error(`The operation is still reported as running but no signal has arrived after ${i} checks. Please refresh the page to check the latest status.`)):S.reset():"resolve"in E?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),f(E.resolve)):y(E.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:d(()=>{i=0,S.reset()},"onActivity"),onCompletion:d(D=>f(D),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const E=await $.executeMutation(e);if(!e.validateAck(E)){S.clear();const D=E?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await a}catch(E){const D=E;throw c.LogError(`[FireAndForget:${t}] Error: ${D.message}`),E}finally{S.clear(),n&&n.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:d(n=>{t.onActivity();try{const o=JSON.parse(n);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(o)))}catch(o){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,o)}},"next"),error:d(()=>t.onStreamEnd(),"error"),complete:d(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class U{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=R.CleanAndParseJSON(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const o={};return await $.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:l(i=>i?.success===!0,"validateAck"),isCompletionEvent:l(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:l(i=>this.extractAgentResult(i),"extractResult"),onMessage:l(i=>{this.captureAgentRunId(i,o),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileAgentRun(o.id?`ID='${o.id}'`:void 0),"onStall"),createErrorResult:l(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=R.CleanAndParseJSON(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const o={};return await $.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:d(i=>i?.success===!0,"validateAck"),isCompletionEvent:d(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:d(i=>this.extractAgentResult(i),"extractResult"),onMessage:d(i=>{this.captureAgentRunId(i,o),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(o.id?`ID='${o.id}'`:void 0),"onStall"),createErrorResult:d(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -81,7 +81,9 @@
81
81
  $createNotification: Boolean,
82
82
  $sourceArtifactId: String,
83
83
  $sourceArtifactVersionId: String,
84
- $fireAndForget: Boolean
84
+ $fireAndForget: Boolean,
85
+ $planMode: Boolean,
86
+ $requestedSkillIDs: [String!]
85
87
  ) {
86
88
  RunAIAgent(
87
89
  agentId: $agentId,
@@ -98,7 +100,9 @@
98
100
  createNotification: $createNotification,
99
101
  sourceArtifactId: $sourceArtifactId,
100
102
  sourceArtifactVersionId: $sourceArtifactVersionId,
101
- fireAndForget: $fireAndForget
103
+ fireAndForget: $fireAndForget,
104
+ planMode: $planMode,
105
+ requestedSkillIDs: $requestedSkillIDs
102
106
  ) {
103
107
  success
104
108
  errorMessage
@@ -106,7 +110,7 @@
106
110
  result
107
111
  }
108
112
  }
109
- `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let o;return s?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=r,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:l(s=>s?.success===!0,"validateAck"),isCompletionEvent:l(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:l(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:l(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:l(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return u.gql`
113
+ `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let o;return s?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=r,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:d(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:d(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:d(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return u.gql`
110
114
  mutation RunAIAgentFromConversationDetail(
111
115
  $conversationDetailId: String!,
112
116
  $agentId: String!,
@@ -117,6 +121,8 @@
117
121
  $lastRunId: String,
118
122
  $autoPopulateLastRunPayload: Boolean,
119
123
  $configurationId: String,
124
+ $planMode: Boolean,
125
+ $requestedSkillIDs: [String!],
120
126
  $createArtifacts: Boolean,
121
127
  $createNotification: Boolean,
122
128
  $sourceArtifactId: String,
@@ -133,6 +139,8 @@
133
139
  lastRunId: $lastRunId,
134
140
  autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
135
141
  configurationId: $configurationId,
142
+ planMode: $planMode,
143
+ requestedSkillIDs: $requestedSkillIDs,
136
144
  createArtifacts: $createArtifacts,
137
145
  createNotification: $createNotification,
138
146
  sourceArtifactId: $sourceArtifactId,
@@ -145,7 +153,7 @@
145
153
  result
146
154
  }
147
155
  }
148
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?R.SafeJSONParse(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?R.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=u.gql`
156
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?R.SafeJSONParse(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?R.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=u.gql`
149
157
  mutation ExecuteSimplePrompt(
150
158
  $systemPrompt: String!,
151
159
  $messages: String,
@@ -297,12 +305,12 @@
297
305
  }
298
306
  }
299
307
  }
300
- `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const M="5.43.0",w="default";class V{static{l(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||w;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||w).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||w);for(const n of new Set(e)){const o=s.get(n);r.set(n,o===void 0?null:o)}return r}async SetItem(e,t,r){this.getCategoryMap(r||w).set(e,t)}async Remove(e,t){this.getCategoryMap(t||w).delete(e)}async ClearCategory(e){const t=e||w;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||w);return t?Array.from(t.keys()):[]}}const Y="MJ_Metadata",Z=0;function ee(){try{const m=M.split("."),e=parseInt(m[0],10),t=parseInt(m[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${M}"`);return e*1e3+t+Z}catch(m){return c.LogErrorEx({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}l(ee,"computeIdbVersion");const te=ee(),_=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class O extends V{static{l(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=z.openDB(Y,te,{upgrade:l((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${M}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of _)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:l((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return _.includes(t)}getStoreName(e){const t=e||w;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||w;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=await r.transaction(s).objectStore(s).get(n);return o===void 0?null:o}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),o=Array.from(new Set(e)),i=o.map(I=>this.getStoreKey(I,t)),a=s.transaction(n,"readonly"),g=a.objectStore(n),d=i.map(I=>g.get(I)),f=await Promise.all(d);await a.done;for(let I=0;I<o.length;I++){const y=f[I];r.set(o[I],y===void 0?null:y)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||w,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const g of a)typeof g=="string"&&g.startsWith(n)&&await i.delete(g);await o.done}}catch(t){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||w,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(g=>String(g));const a=`[${r}]:`;return i.map(g=>String(g)).filter(g=>g.startsWith(a)).map(g=>g.slice(a.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}const A=new P,re=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
308
+ `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const A="5.44.0",w="default";class V{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||w;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||w).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||w);for(const n of new Set(e)){const o=s.get(n);r.set(n,o===void 0?null:o)}return r}async SetItem(e,t,r){this.getCategoryMap(r||w).set(e,t)}async Remove(e,t){this.getCategoryMap(t||w).delete(e)}async ClearCategory(e){const t=e||w;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||w);return t?Array.from(t.keys()):[]}}const Y="MJ_Metadata",Z=0;function ee(){try{const m=A.split("."),e=parseInt(m[0],10),t=parseInt(m[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${A}"`);return e*1e3+t+Z}catch(m){return c.LogErrorEx({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ee,"computeIdbVersion");const te=ee(),_=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class O extends V{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=z.openDB(Y,te,{upgrade:d((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${A}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of _)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return _.includes(t)}getStoreName(e){const t=e||w;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||w;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=await r.transaction(s).objectStore(s).get(n);return o===void 0?null:o}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),o=Array.from(new Set(e)),i=o.map(f=>this.getStoreKey(f,t)),a=s.transaction(n,"readonly"),g=a.objectStore(n),l=i.map(f=>g.get(f)),h=await Promise.all(l);await a.done;for(let f=0;f<o.length;f++){const y=h[f];r.set(o[f],y===void 0?null:y)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||w,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const g of a)typeof g=="string"&&g.startsWith(n)&&await i.delete(g);await o.done}}catch(t){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||w,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(g=>String(g));const a=`[${r}]:`;return i.map(g=>String(g)).filter(g=>g.startsWith(a)).map(g=>g.slice(a.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}const M=new P,re=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
301
309
  RemoteOperationProgress(channelId: $channelId) {
302
310
  ChannelId
303
311
  ProgressJSON
304
312
  }
305
- }`;class se extends c.ProviderConfigDataBase{static{l(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}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,o,i,a,g,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:g,RefreshTokenFunction:s,OnAuthenticationError:d},n,o,i)}}class h extends c.ProviderBase{static{l(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
313
+ }`;class se extends c.ProviderConfigDataBase{static{d(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}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,o,i,a,g,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:g,RefreshTokenFunction:s,OnAuthenticationError:l},n,o,i)}}class I extends c.ProviderBase{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
306
314
  ${this.userInfoString()}
307
315
  MJUserRoles_UserIDArray {
308
316
  ${this.userRoleInfoString()}
@@ -311,7 +319,7 @@
311
319
  `,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
312
320
  ${this._innerCurrentUserQueryString}
313
321
  CurrentUserTenantContext
314
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new L.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=R.GetGlobalObjectStore();if(e&&e[h._globalStoreKey])return e[h._globalStoreKey];e&&(e[h._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=R.GetGlobalObjectStore();return e?e[h._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new U(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return W.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.set(e,t),h.Instance._client&&h.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.delete(e),h.Instance._client&&h.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
322
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new L.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=R.GetGlobalObjectStore();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=R.GetGlobalObjectStore();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new U(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return W.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
315
323
  query GetReportDataQuery ($ReportID: String!) {
316
324
  GetReportData(ReportID: $ReportID) {
317
325
  Success
@@ -320,7 +328,7 @@
320
328
  ExecutionTime
321
329
  ErrorMessage
322
330
  }
323
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=u.gql`
331
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=u.gql`
324
332
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
325
333
  ExecuteAdhocQuery(input: $input) {
326
334
  ${this.QueryReturnFieldList}
@@ -332,19 +340,19 @@
332
340
  ${this.QueryReturnFieldList}
333
341
  }
334
342
  }
335
- `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i){const a=u.gql`
336
- query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
337
- GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
343
+ `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription,Enrichment:o.Enrichment})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i,a){const g=u.gql`
344
+ query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
345
+ GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
338
346
  ${this.QueryReturnFieldList}
339
347
  }
340
348
  }
341
- `,g={QueryID:e};t!==void 0&&(g.CategoryID=t),r!==void 0&&(g.CategoryPath=r),n!==void 0&&(g.Parameters=n),o!==void 0&&(g.MaxRows=o),i!==void 0&&(g.StartRow=i);const d=await this.ExecuteGQL(a,g);if(d&&d.GetQueryData)return this.TransformQueryPayload(d.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i){const a=u.gql`
342
- query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
343
- GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
349
+ `,l={QueryID:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),o!==void 0&&(l.MaxRows=o),i!==void 0&&(l.StartRow=i),a!==void 0&&(l.Enrichment=a);const h=await this.ExecuteGQL(g,l);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i,a){const g=u.gql`
350
+ query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
351
+ GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
344
352
  ${this.QueryReturnFieldList}
345
353
  }
346
354
  }
347
- `,g={QueryName:e};t!==void 0&&(g.CategoryID=t),r!==void 0&&(g.CategoryPath=r),n!==void 0&&(g.Parameters=n),o!==void 0&&(g.MaxRows=o),i!==void 0&&(g.StartRow=i);const d=await this.ExecuteGQL(a,g);if(d&&d.GetQueryDataByName)return this.TransformQueryPayload(d.GetQueryDataByName)}get QueryReturnFieldList(){return`
355
+ `,l={QueryName:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),o!==void 0&&(l.MaxRows=o),i!==void 0&&(l.StartRow=i),a!==void 0&&(l.Enrichment=a);const h=await this.ExecuteGQL(g,l);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
348
356
  Success
349
357
  QueryID
350
358
  QueryName
@@ -353,7 +361,7 @@
353
361
  TotalRowCount
354
362
  ExecutionTime
355
363
  ErrorMessage
356
- AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
364
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null,Enrichment:a.params.Enrichment||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
357
365
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
358
366
  RunQueriesWithCacheCheck(input: $input) {
359
367
  success
@@ -369,7 +377,7 @@
369
377
  }
370
378
  }
371
379
  }
372
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const g=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:g,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:S,v:E}=await this.getEntityNameAndUserView(e,t);i=E,o=S}const a=this.EntityByName(o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let g=!1;const d=c.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${d}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(g=!0,r=`Run${d}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),g||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(S=>({expression:S.expression,alias:S.alias})));const f=this.getViewRunTimeFieldList(a,i,e,g),I=e.Aggregates&&e.Aggregates.length>0?`
380
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const g=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:g,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:S,v:E}=await this.getEntityNameAndUserView(e,t);i=E,o=S}const a=this.EntityByName(o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let g=!1;const l=c.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(g=!0,r=`Run${l}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),g||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(S=>({expression:S.expression,alias:S.alias})));const h=this.getViewRunTimeFieldList(a,i,e,g),f=e.Aggregates&&e.Aggregates.length>0?`
373
381
  AggregateResults {
374
382
  alias
375
383
  expression
@@ -380,7 +388,7 @@
380
388
  query RunViewQuery ($input: ${s}!) {
381
389
  ${r}(input: $input) {
382
390
  Results {
383
- ${f.join(`
391
+ ${h.join(`
384
392
  `)}
385
393
  }
386
394
  UserViewRunID
@@ -388,9 +396,9 @@
388
396
  TotalRowCount
389
397
  ExecutionTime
390
398
  Success
391
- ErrorMessage${I}
399
+ ErrorMessage${f}
392
400
  }
393
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const p=await this.ExecuteGQL(y,{input:n});if(p&&p[r]){const S=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:p[r].AggregateExecutionTime});const E=p[r].Results;if(E&&E.length>0){const C=a.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);E.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(N=>{v[N.Name]=v[N.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let f="",I="";const y={};let p=null,S=null;if(d.ViewEntity)S=d.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:N}=await this.getEntityNameAndUserView(d,t);S=N,p=v}const E=this.EntityByName(p);if(!E)throw new Error(`Entity ${p} not found in metadata`);s.push(E);let D=!1;const C=c.getGraphQLTypeNameBase(E);d.ViewID?(f=`Run${C}ViewByID`,I="RunViewByIDInput",y.ViewID=d.ViewID):d.ViewName?(f=`Run${C}ViewByName`,I="RunViewByNameInput",y.ViewName=d.ViewName):(D=!0,f=`Run${C}DynamicView`,I="RunDynamicViewInput",y.EntityName=d.EntityName),y.ExtraFilter=d.ExtraFilter||"",y.OrderBy=d.OrderBy||"",y.UserSearchString=d.UserSearchString||"",y.Fields=d.Fields,y.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(y.MaxRows=d.MaxRows),d.StartRow!==void 0&&(y.StartRow=d.StartRow),d.AfterKey&&(y.AfterKey={KeyValuePairs:d.AfterKey.KeyValuePairs}),y.ForceAuditLog=d.ForceAuditLog||!1,y.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(y.AuditLogDescription=d.AuditLogDescription),d.BypassCache!==void 0&&(y.BypassCache=d.BypassCache),D||(y.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=d.OverrideExcludeFilter||"",y.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(y.Aggregates=d.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(E,S,d,D))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
401
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const p=await this.ExecuteGQL(y,{input:n});if(p&&p[r]){const S=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:p[r].AggregateExecutionTime});const E=p[r].Results;if(E&&E.length>0){const C=a.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);E.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(N=>{v[N.Name]=v[N.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let h="",f="";const y={};let p=null,S=null;if(l.ViewEntity)S=l.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:N}=await this.getEntityNameAndUserView(l,t);S=N,p=v}const E=this.EntityByName(p);if(!E)throw new Error(`Entity ${p} not found in metadata`);s.push(E);let D=!1;const C=c.getGraphQLTypeNameBase(E);l.ViewID?(h=`Run${C}ViewByID`,f="RunViewByIDInput",y.ViewID=l.ViewID):l.ViewName?(h=`Run${C}ViewByName`,f="RunViewByNameInput",y.ViewName=l.ViewName):(D=!0,h=`Run${C}DynamicView`,f="RunDynamicViewInput",y.EntityName=l.EntityName),y.ExtraFilter=l.ExtraFilter||"",y.OrderBy=l.OrderBy||"",y.UserSearchString=l.UserSearchString||"",y.Fields=l.Fields,y.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(y.MaxRows=l.MaxRows),l.StartRow!==void 0&&(y.StartRow=l.StartRow),l.AfterKey&&(y.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),y.ForceAuditLog=l.ForceAuditLog||!1,y.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(y.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(y.BypassCache=l.BypassCache),D||(y.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=l.OverrideExcludeFilter||"",y.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(y.Aggregates=l.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(E,S,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
394
402
  AggregateResults {
395
403
  alias
396
404
  expression
@@ -415,7 +423,7 @@
415
423
  Success
416
424
  ErrorMessage${i}
417
425
  }
418
- }`,g=await this.ExecuteGQL(a,{input:r});if(g&&g.RunViews){const d=g.RunViews;for(const[f,I]of d.entries())I.Results=I.Results.map(y=>{let p=JSON.parse(y.Data);return this.ConvertBackToMJFields(p),p});return d}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,AfterKey:a.params.AfterKey?{KeyValuePairs:a.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
426
+ }`,g=await this.ExecuteGQL(a,{input:r});if(g&&g.RunViews){const l=g.RunViews;for(const[h,f]of l.entries())f.Results=f.Results.map(y=>{let p=JSON.parse(y.Data);return this.ConvertBackToMJFields(p),p});return l}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,AfterKey:a.params.AfterKey?{KeyValuePairs:a.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
419
427
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
420
428
  RunViewsWithCacheCheck(input: $input) {
421
429
  success
@@ -448,7 +456,7 @@
448
456
  }
449
457
  }
450
458
  }
451
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,g)=>{const d=e[g];if(a.status==="differential"&&a.differentialData){const f=a.differentialData.updatedRows.map(I=>{const y=JSON.parse(I.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const f=a.Results.map(I=>{const y=JSON.parse(I.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:f,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await G.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await G.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(A.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(A.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(A.MapFieldName(o.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
459
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,g)=>{const l=e[g];if(a.status==="differential"&&a.differentialData){const h=a.differentialData.updatedRows.map(f=>{const y=JSON.parse(f.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:h,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const h=a.Results.map(f=>{const y=JSON.parse(f.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:h,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await G.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await G.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(M.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(M.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(M.MapFieldName(o.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
452
460
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
453
461
  EntityName
454
462
  RelatedEntityName
@@ -506,7 +514,7 @@
506
514
  handle
507
515
  errorMessage
508
516
  }
509
- }`;let n,o;r.onProgress&&(n=this.GenerateUUID(),o=this.subscribe(re,{channelId:n}).subscribe({next:l(i=>{const a=i?.RemoteOperationProgress?.ProgressJSON;if(a)try{r.onProgress(JSON.parse(a))}catch{}},"next"),error:l(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const a=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return a?{Success:!!a.success,ResultCode:a.resultCode??void 0,Output:a.outputJSON!=null?JSON.parse(a.outputJSON):void 0,Handle:a.handle??void 0,ErrorMessage:a.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{o?.unsubscribe()}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
517
+ }`;let n,o;r.onProgress&&(n=this.GenerateUUID(),o=this.subscribe(re,{channelId:n}).subscribe({next:d(i=>{const a=i?.RemoteOperationProgress?.ProgressJSON;if(a)try{r.onProgress(JSON.parse(a))}catch{}},"next"),error:d(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const a=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return a?{Success:!!a.success,ResultCode:a.resultCode??void 0,Output:a.outputJSON!=null?JSON.parse(a.outputJSON):void 0,Handle:a.handle??void 0,ErrorMessage:a.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{o?.unsubscribe()}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
510
518
  MergeRecords(request: $request) {
511
519
  Success
512
520
  OverallStatus
@@ -523,32 +531,32 @@
523
531
  Message
524
532
  }
525
533
  }
526
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,g=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),d=` ${a}(input: $input) {
527
- ${e.Fields.map(y=>A.MapFieldName(y.CodeName)).join(`
534
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,g=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),l=` ${a}(input: $input) {
535
+ ${e.Fields.map(y=>M.MapFieldName(y.CodeName)).join(`
528
536
  `)}
529
- }`,f=u.gql`mutation ${o}${i} ($input: ${a}Input!) {
530
- ${d}
537
+ }`,h=u.gql`mutation ${o}${i} ($input: ${a}Input!) {
538
+ ${l}
531
539
  }
532
- `;for(let y=0;y<g.length;y++){const p=g[y];let S=e.Get(p.Name);if(S)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:S=S.getTime();break;case c.EntityFieldTSType.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case c.EntityFieldTSType.Number:if(typeof S!="number"){const E=Number(S);isNaN(E)||(S=E)}break}S===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?S=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?S=0:S=""),n.input[A.MapFieldName(p.CodeName)]=S}const I=e.RestoreContext;if(I&&(n.input.RestoreContext___={SourceChangeID:I.SourceChangeID,Reason:I.Reason}),o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(p=>{let S=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?S=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?S=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?S=p.OldValue.toString():S=p.OldValue),y.push({Key:A.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",d,n,{mutationName:a,mutationInputTypes:y},(p,S)=>{s.EndedAt=new Date,S&&p?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(p)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(f,n);if(y&&y[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let I=0;I<t.KeyValuePairs.length;I++){const y=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[I].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(I),S=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${S}!`,o.length>0&&(o+=", "),o+=`${y.CodeName}: $${y.CodeName}`,y.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(I)))throw new Error(`Primary Key value ${p} (${y.Name}) is not a valid number`);n[y.CodeName]=parseInt(p)}else n[y.CodeName]=p}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",g=c.getGraphQLTypeNameBase(e.EntityInfo),d=u.gql`query Single${g}${a.length>0?"Full":""} (${i}) {
540
+ `;for(let y=0;y<g.length;y++){const p=g[y];let S=e.Get(p.Name);if(S)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:S=S.getTime();break;case c.EntityFieldTSType.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case c.EntityFieldTSType.Number:if(typeof S!="number"){const E=Number(S);isNaN(E)||(S=E)}break}S===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?S=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?S=0:S=""),n.input[M.MapFieldName(p.CodeName)]=S}const f=e.RestoreContext;if(f&&(n.input.RestoreContext___={SourceChangeID:f.SourceChangeID,Reason:f.Reason}),o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(p=>{let S=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?S=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?S=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?S=p.OldValue.toString():S=p.OldValue),y.push({Key:M.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",l,n,{mutationName:a,mutationInputTypes:y},(p,S)=>{s.EndedAt=new Date,S&&p?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(p)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(h,n);if(y&&y[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let f=0;f<t.KeyValuePairs.length;f++){const y=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[f].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(f),S=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${S}!`,o.length>0&&(o+=", "),o+=`${y.CodeName}: $${y.CodeName}`,y.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(f)))throw new Error(`Primary Key value ${p} (${y.Name}) is not a valid number`);n[y.CodeName]=parseInt(p)}else n[y.CodeName]=p}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",g=c.getGraphQLTypeNameBase(e.EntityInfo),l=u.gql`query Single${g}${a.length>0?"Full":""} (${i}) {
533
541
  ${g}(${o}) {
534
- ${e.Fields.filter(I=>!I.EntityFieldInfo.IsBinaryFieldType).map(I=>I.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?I.CodeName.replace("__mj_","_mj__"):I.CodeName).join(`
542
+ ${e.Fields.filter(f=>!f.EntityFieldInfo.IsBinaryFieldType).map(f=>f.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?f.CodeName.replace("__mj_","_mj__"):f.CodeName).join(`
535
543
  `)}
536
544
  ${a}
537
545
  }
538
546
  }
539
- `,f=await this.ExecuteGQL(d,n);return f&&f[g]?this.ConvertBackToMJFields(f[g]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return A.ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],o=this.EntityByID(n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
547
+ `,h=await this.ExecuteGQL(l,n);return h&&h[g]?this.ConvertBackToMJFields(h[g]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return M.ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],o=this.EntityByID(n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
540
548
  ${i} {
541
549
  ${o.Fields.map(a=>a.CodeName).join(`
542
550
  `)}
543
551
  }
544
552
  `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(p=>({FieldName:p.CodeName,Value:p.Value})),e.RegisterResultHistoryEntry(s);const n={},o=[];let i="",a="",g="";for(let p of e.PrimaryKey.KeyValuePairs){const S=e.Fields.find(E=>E.Name.trim().toLowerCase()===p.FieldName.trim().toLowerCase());n[S.CodeName]=S.Value,o.push({varName:S.CodeName,inputType:S.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${S.CodeName}: $${S.CodeName}`,a.length>0&&(a+=", "),a+=`$${S.CodeName}: ${S.EntityFieldInfo.GraphQLType}!`,g.length>0&&(g+=`
545
- `),g+=`${S.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),I=u.gql`${f}(${i}, options___: $options___) {
553
+ `),g+=`${S.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const h="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),f=u.gql`${h}(${i}, options___: $options___) {
546
554
  ${g}
547
555
  }
548
- `,y=u.gql`mutation ${f} (${a}, $options___: DeleteOptionsInput!) {
549
- ${I}
556
+ `,y=u.gql`mutation ${h} (${a}, $options___: DeleteOptionsInput!) {
557
+ ${f}
550
558
  }
551
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",I,n,{mutationName:f,mutationInputTypes:o},(p,S)=>{if(s.EndedAt=new Date,S&&p){let E=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==p[D.FieldName]&&(E=!1);E?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(y,n);if(p&&p[f]){const S=p[f];for(let E of e.PrimaryKey.KeyValuePairs){let D=S[E.FieldName],C=E.Value;if(typeof C=="number"&&(C=C.toString()),typeof D=="number"&&(D=D.toString()),C!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${E.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
559
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",f,n,{mutationName:h,mutationInputTypes:o},(p,S)=>{if(s.EndedAt=new Date,S&&p){let E=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==p[D.FieldName]&&(E=!1);E?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(y,n);if(p&&p[h]){const S=p[h];for(let E of e.PrimaryKey.KeyValuePairs){let D=S[E.FieldName],C=E.Value;if(typeof C=="number"&&(C=C.toString()),typeof D=="number"&&(D=D.toString()),C!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${E.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
552
560
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
553
561
  DatasetID
554
562
  DatasetName
@@ -557,7 +565,7 @@
557
565
  LatestUpdateDate
558
566
  Results
559
567
  }
560
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return h._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{h._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),h._datasetStatusTimer||(h._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),h._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){h._datasetStatusTimer=null;const e=h._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);c.LogStatus(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=u.gql`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
568
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);c.LogStatus(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=u.gql`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
561
569
  GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
562
570
  DatasetID
563
571
  DatasetName
@@ -615,16 +623,16 @@
615
623
  ErrorMessage
616
624
  Result
617
625
  }
618
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return h.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:o});for(const[a,g]of this._dynamicHeaders)i.setHeader(a,g);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
626
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:o});for(const[a,g]of this._dynamicHeaders)i.setHeader(a,g);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
619
627
  `:s.startsWith("_")||(t+=s+`
620
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new O:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=J.createClient({url:this.ConfigData.WSURL,connectionParams:l(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:l(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new L.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:l(o=>{r.next(o.data)},"next"),error:l(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(g){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",g),r.error(g)}}else r.error(o)},"error"),complete:l(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new L.Observable(a=>{r.activeSubscribers++;const g=r.subject.subscribe(a);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,g.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
628
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new O:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=J.createClient({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new L.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(o=>{r.next(o.data)},"next"),error:d(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(g){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",g),r.error(g)}}else r.error(o)},"error"),complete:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new L.Observable(a=>{r.activeSubscribers++;const g=r.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,g.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
621
629
  statusUpdates(sessionId: $sessionId) {
622
630
  date
623
631
  message
624
632
  sessionId
625
633
  }
626
634
  }
627
- `,n=new L.Subject,o=this.getOrCreateWSClient(),i=new L.Subscription;return i.add(new L.Observable(a=>{const g=o.subscribe({query:s,variables:{sessionId:e}},{next:l(d=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),a.next(d.data.statusUpdates.message)},"next"),error:l(async d=>{const f=d;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(d)},"error"),complete:l(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,g()}}).subscribe({next:l(a=>n.next(a),"next"),error:l(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:l(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new L.Observable(a=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers++;const d=n.subscribe(a);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
635
+ `,n=new L.Subject,o=this.getOrCreateWSClient(),i=new L.Subscription;return i.add(new L.Observable(a=>{const g=o.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const h=this._pushStatusSubjects.get(e);h&&(h.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const h=l;if(h?.extensions?.code==="JWT_EXPIRED"||h?.message?.includes("token has expired")||h?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(l)},"error"),complete:d(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,g()}}).subscribe({next:d(a=>n.next(a),"next"),error:d(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new L.Observable(a=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers++;const l=n.subscribe(a);return()=>{const h=this._pushStatusSubjects.get(e);h&&h.activeSubscribers>0&&h.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
628
636
  subscription ClientToolRequest($sessionID: String!) {
629
637
  ClientToolRequest(sessionID: $sessionID) {
630
638
  AgentRunID
@@ -646,7 +654,7 @@
646
654
  OriginSessionID
647
655
  RecordData
648
656
  }
649
- }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:l(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){h.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}h.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:l(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:l(()=>{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;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
657
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:d(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:d(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:d(()=>{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;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
650
658
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
651
659
  Success
652
660
  ChildEntityName
@@ -658,7 +666,7 @@
658
666
  ChildEntityNames
659
667
  ErrorMessage
660
668
  }
661
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function ne(m){const e=new h;return c.SetProvider(e),await e.Config(m),await e.preValidateAndRefresh(),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}l(ne,"setupGraphQLClient");class oe{static{l(this,"SyncRolesAndUsersResult")}}class ae{static{l(this,"RoleInput")}}class ie{static{l(this,"UserInput")}}class ce{static{l(this,"RolesAndUsersInput")}}var k=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(k||{});class ue{static{l(this,"ActionItemInput")}}class le{static{l(this,"SyncDataResult")}constructor(){this.Results=[]}}class de{static{l(this,"ActionItemOutput")}}class ge{static{l(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
669
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function ne(m){const e=new I;return c.SetProvider(e),await e.Config(m),await e.preValidateAndRefresh(),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}d(ne,"setupGraphQLClient");class oe{static{d(this,"SyncRolesAndUsersResult")}}class ae{static{d(this,"RoleInput")}}class ie{static{d(this,"UserInput")}}class ce{static{d(this,"RolesAndUsersInput")}}var k=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(k||{});class ue{static{d(this,"ActionItemInput")}}class le{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class de{static{d(this,"ActionItemOutput")}}class ge{static{d(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
662
670
  GetData(input: $input) {
663
671
  Success
664
672
  ErrorMessages
@@ -784,8 +792,8 @@
784
792
  ErrorMessage
785
793
  Success
786
794
  }
787
- }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
788
- GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
795
+ }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
796
+ GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
789
797
  QueryID
790
798
  QueryName
791
799
  Success
@@ -796,8 +804,8 @@
796
804
  ErrorMessage
797
805
  AppliedParameters
798
806
  }
799
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?R.SafeJSONParse(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
800
- GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
807
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?R.SafeJSONParse(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
808
+ GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
801
809
  QueryID
802
810
  QueryName
803
811
  Success
@@ -808,7 +816,7 @@
808
816
  ErrorMessage
809
817
  AppliedParameters
810
818
  }
811
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?R.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
819
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?R.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
812
820
  CreateQuerySystemUser(input: $input) {
813
821
  Success
814
822
  ErrorMessage
@@ -1171,7 +1179,7 @@
1171
1179
  ErrorMessage
1172
1180
  }
1173
1181
  }
1174
- `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const o=n.CheckEntityPermissionsSystemUser;return{Success:o.Success,Results:(o.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:o.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class ye{static{l(this,"GetDataOutput")}}class me{static{l(this,"SimpleRemoteEntityOutput")}}class Se{static{l(this,"SimpleRemoteEntity")}}class pe{static{l(this,"SimpleRemoteEntityField")}}class he{static{l(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
1182
+ `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const o=n.CheckEntityPermissionsSystemUser;return{Success:o.Success,Results:(o.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:o.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class ye{static{d(this,"GetDataOutput")}}class me{static{d(this,"SimpleRemoteEntityOutput")}}class Se{static{d(this,"SimpleRemoteEntity")}}class pe{static{d(this,"SimpleRemoteEntityField")}}class he{static{d(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
1175
1183
  mutation RunAction($input: RunActionInput!) {
1176
1184
  RunAction(input: $input) {
1177
1185
  Success
@@ -1188,7 +1196,7 @@
1188
1196
  ResultData
1189
1197
  }
1190
1198
  }
1191
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ie{static{l(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
1199
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ie{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
1192
1200
  query PreviewListDelta($input: ComputeDeltaInput!) {
1193
1201
  PreviewListDelta(input: $input) {
1194
1202
  ...ListDeltaFields
@@ -1338,7 +1346,7 @@
1338
1346
  Message
1339
1347
  PermissionID
1340
1348
  }
1341
- `;function fe(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}l(fe,"serializeShareTarget");function F(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}l(F,"parseShareResult");function Ee(m){const e=m,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}l(Ee,"parseShareSummary");function Q(m){switch(m.kind){case"list":return{Kind:"list",ListID:m.listId};case"view":return{Kind:"view",ViewID:m.viewId};case"adhoc":return{Kind:"adhoc",EntityName:m.entityName,ExtraFilter:m.extraFilter}}}l(Q,"serializeListSource");function B(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=m;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(Re),DeltaToken:e.DeltaToken}}l(B,"parseListDelta");function Re(m){let e;if(m.DetailsJSON)try{e=JSON.parse(m.DetailsJSON)}catch(t){c.LogError(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:m.Code,Message:m.Message,Details:e}}l(Re,"parseWarning");function T(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}l(T,"parseApplyResult");class De{static{l(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
1349
+ `;function fe(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}d(fe,"serializeShareTarget");function F(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}d(F,"parseShareResult");function Ee(m){const e=m,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}d(Ee,"parseShareSummary");function Q(m){switch(m.kind){case"list":return{Kind:"list",ListID:m.listId};case"view":return{Kind:"view",ViewID:m.viewId};case"adhoc":return{Kind:"adhoc",EntityName:m.entityName,ExtraFilter:m.extraFilter}}}d(Q,"serializeListSource");function B(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=m;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(Re),DeltaToken:e.DeltaToken}}d(B,"parseListDelta");function Re(m){let e;if(m.DetailsJSON)try{e=JSON.parse(m.DetailsJSON)}catch(t){c.LogError(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:m.Code,Message:m.Message,Details:e}}d(Re,"parseWarning");function T(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}d(T,"parseApplyResult");class De{static{d(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
1342
1350
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1343
1351
  CreateAPIKey(input: $input) {
1344
1352
  Success
@@ -1354,7 +1362,7 @@
1354
1362
  Error
1355
1363
  }
1356
1364
  }
1357
- `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ve{static{l(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
1365
+ `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ve{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
1358
1366
  mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1359
1367
  RunClusterAnalysis(input: $input) {
1360
1368
  Success
@@ -1370,7 +1378,7 @@
1370
1378
  AnalysisID
1371
1379
  }
1372
1380
  }
1373
- `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=R.SafeJSONParse(e.ClustersJSON)??[],s=R.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=R.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class Ce{static{l(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
1381
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=R.SafeJSONParse(e.ClustersJSON)??[],s=R.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=R.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class Ce{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
1374
1382
  mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1375
1383
  MintLiveKitClientToken(input: $input) {
1376
1384
  Success
@@ -1432,9 +1440,10 @@
1432
1440
  ErrorMessage
1433
1441
  EgressID
1434
1442
  Status
1443
+ RecordingFileID
1435
1444
  }
1436
1445
  }
1437
- `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const o=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!o)throw new Error("Invalid response from server");return o}catch(n){const o=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,o),{Success:!1,ErrorMessage:o.message||"Unknown error",EgressID:s,Status:""}}}}class we{static{l(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
1446
+ `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const o=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!o)throw new Error("Invalid response from server");return o}catch(n){const o=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,o),{Success:!1,ErrorMessage:o.message||"Unknown error",EgressID:s,Status:""}}}}class we{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
1438
1447
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1439
1448
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1440
1449
  Success
@@ -1444,7 +1453,7 @@
1444
1453
  NodesJSON
1445
1454
  }
1446
1455
  }
1447
- `,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=R.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class $e{static{l(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:l(n=>n?.success===!0,"validateAck"),isCompletionEvent:l(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:l(n=>this.extractTestResult(n),"extractResult"),onMessage:l(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:l(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:l(s=>s?.success===!0,"validateAck"),isCompletionEvent:l(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:l(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:l(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
1456
+ `,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=R.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class $e{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:d(n=>n?.success===!0,"validateAck"),isCompletionEvent:d(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:d(n=>this.extractTestResult(n),"extractResult"),onMessage:d(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:d(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:d(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:d(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
1448
1457
  query IsTestRunning($testId: String!) {
1449
1458
  IsTestRunning(testId: $testId)
1450
1459
  }
@@ -1502,7 +1511,7 @@
1502
1511
  result
1503
1512
  }
1504
1513
  }
1505
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class Pe{static{l(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1514
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class Pe{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1506
1515
  query GetRegistryComponent(
1507
1516
  $registryName: String!,
1508
1517
  $namespace: String!,
@@ -1586,7 +1595,7 @@
1586
1595
  error
1587
1596
  }
1588
1597
  }
1589
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Le{static{l(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
1598
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Le{static{d(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
1590
1599
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1591
1600
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1592
1601
  Success
@@ -1602,7 +1611,7 @@
1602
1611
  }
1603
1612
  }
1604
1613
  }
1605
- `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class Ae{static{l(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
1614
+ `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class Me{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
1606
1615
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1607
1616
  ListStorageObjects(input: $input) {
1608
1617
  objects {
@@ -1686,7 +1695,7 @@
1686
1695
  failedAccounts
1687
1696
  }
1688
1697
  }
1689
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(g=>({path:g.path,name:g.name,size:g.size,contentType:g.contentType,lastModified:new Date(g.lastModified),relevance:g.relevance,excerpt:g.excerpt,matchInFilename:g.matchInFilename,objectId:g.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ne{static{l(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
1698
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(g=>({path:g.path,name:g.name,size:g.size,contentType:g.contentType,lastModified:new Date(g.lastModified),relevance:g.relevance,excerpt:g.excerpt,matchInFilename:g.matchInFilename,objectId:g.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ne{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
1690
1699
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1691
1700
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1692
1701
  Success
@@ -1825,7 +1834,7 @@
1825
1834
  ElapsedMs
1826
1835
  ErrorMessage
1827
1836
  }
1828
- }`;n=this._dataProvider.subscribe(a,{streamID:i.StreamID}).subscribe({next:l(g=>{const d=g?.SearchStreamEvents;d&&(t.next(d),d.Phase==="final"?(t.complete(),n?.unsubscribe()):d.Phase==="error"&&(t.error(new Error(d.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:l(g=>t.error(g),"error")})}catch(o){t.error(o)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class Me{static{l(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1837
+ }`;n=this._dataProvider.subscribe(a,{streamID:i.StreamID}).subscribe({next:d(g=>{const l=g?.SearchStreamEvents;l&&(t.next(l),l.Phase==="final"?(t.complete(),n?.unsubscribe()):l.Phase==="error"&&(t.error(new Error(l.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(g=>t.error(g),"error")})}catch(o){t.error(o)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class Ae{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1829
1838
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1830
1839
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1831
1840
  Success
@@ -1976,7 +1985,7 @@
1976
1985
  PipelineSteps { Name Status DurationMs Message }
1977
1986
  GitCommitSuccess APIRestarted
1978
1987
  }
1979
- }`,g={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(I=>({SourceObjectID:I.SourceObjectID??null,SourceObjectName:I.SourceObjectName??null,Fields:I.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},d=(await this._dataProvider.ExecuteGQL(a,{input:g,platform:n,skipGitCommit:o,skipRestart:i}))?.IntegrationApplyAllBatch;return d?{Success:d.Success,Message:d.Message,Steps:d.PipelineSteps,GitCommitSuccess:d.GitCommitSuccess,APIRestarted:d.APIRestarted,EntityMapsCreated:d.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:d.ConnectorResults?.[0]?.SyncRunID,Warnings:d.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplyAll(
1988
+ }`,g={Connectors:e.map(h=>({CompanyIntegrationID:h.CompanyIntegrationID,SourceObjects:h.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(a,{input:g,platform:n,skipGitCommit:o,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.ConnectorResults?.flatMap(h=>h.Warnings??[])}:{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplyAll(
1980
1989
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1981
1990
  ) {
1982
1991
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -2018,5 +2027,5 @@
2018
2027
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
2019
2028
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
2020
2029
  }
2021
- }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:l(function(){return u.gql},"get")}),exports.ActionItemInput=ue,exports.ActionItemOutput=de,exports.BrowserIndexedDBStorageProvider=O,exports.BrowserStorageProviderBase=V,exports.FieldMapper=P,exports.FireAndForgetHelper=$,exports.GetDataOutput=ye,exports.GraphQLAIClient=U,exports.GraphQLActionClient=he,exports.GraphQLClassifyClient=we,exports.GraphQLClusterClient=ve,exports.GraphQLComponentRegistryClient=Pe,exports.GraphQLDataProvider=h,exports.GraphQLEncryptionClient=De,exports.GraphQLFileStorageClient=Ae,exports.GraphQLIntegrationClient=Me,exports.GraphQLListsClient=Ie,exports.GraphQLLiveKitClient=Ce,exports.GraphQLProviderConfigData=se,exports.GraphQLSearchClient=Ne,exports.GraphQLSystemUserClient=ge,exports.GraphQLTestingClient=$e,exports.GraphQLTransactionGroup=q,exports.GraphQLVersionHistoryClient=Le,exports.PACKAGE_VERSION=M,exports.RoleInput=ae,exports.RolesAndUsersInput=ce,exports.SimpleRemoteEntity=Se,exports.SimpleRemoteEntityField=pe,exports.SimpleRemoteEntityOutput=me,exports.SyncDataAction=k,exports.SyncDataResult=le,exports.SyncRolesAndUsersResult=oe,exports.UserInput=ie,exports.setupGraphQLClient=ne;
2030
+ }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=ue,exports.ActionItemOutput=de,exports.BrowserIndexedDBStorageProvider=O,exports.BrowserStorageProviderBase=V,exports.FieldMapper=P,exports.FireAndForgetHelper=$,exports.GetDataOutput=ye,exports.GraphQLAIClient=U,exports.GraphQLActionClient=he,exports.GraphQLClassifyClient=we,exports.GraphQLClusterClient=ve,exports.GraphQLComponentRegistryClient=Pe,exports.GraphQLDataProvider=I,exports.GraphQLEncryptionClient=De,exports.GraphQLFileStorageClient=Me,exports.GraphQLIntegrationClient=Ae,exports.GraphQLListsClient=Ie,exports.GraphQLLiveKitClient=Ce,exports.GraphQLProviderConfigData=se,exports.GraphQLSearchClient=Ne,exports.GraphQLSystemUserClient=ge,exports.GraphQLTestingClient=$e,exports.GraphQLTransactionGroup=q,exports.GraphQLVersionHistoryClient=Le,exports.PACKAGE_VERSION=A,exports.RoleInput=ae,exports.RolesAndUsersInput=ce,exports.SimpleRemoteEntity=Se,exports.SimpleRemoteEntityField=pe,exports.SimpleRemoteEntityOutput=me,exports.SyncDataAction=k,exports.SyncDataResult=le,exports.SyncRolesAndUsersResult=oe,exports.UserInput=ie,exports.setupGraphQLClient=ne;
2022
2031
  //# sourceMappingURL=index.cjs.map