@memberjunction/graphql-dataprovider 5.41.0 → 5.43.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 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"),A=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`
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`
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,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],y=R.SafeJSONParse(o),l=this.PendingTransactions[i];a.push(new c.TransactionResult(l,y,y!==null))}return a}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,a=!1,i=0;const{promise:o,resolve:y,reject:l}=$.createCompletionPromise(),f=d(E=>{a||(a=!0,S.clear(),E())},"finish"),I=d(E=>f(()=>y(E)),"settleResolve"),g=d(E=>f(()=>l(E)),"settleReject"),p=d(async()=>{if(a)return;if(!e.onStall){g(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){g(D);return}a||(E==="continue"?++i>s?g(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)):g(E.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:d(()=>{i=0,S.reset()},"onActivity"),onCompletion:d(D=>I(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 o}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 a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"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`
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`
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 a={};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,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:d(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: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`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -106,7 +106,7 @@
106
106
  result
107
107
  }
108
108
  }
109
- `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return 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 a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}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`
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`
110
110
  mutation RunAIAgentFromConversationDetail(
111
111
  $conversationDetailId: String!,
112
112
  $agentId: String!,
@@ -168,7 +168,7 @@
168
168
  executionTimeMs
169
169
  }
170
170
  }
171
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=u.gql`
171
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=u.gql`
172
172
  mutation EmbedText(
173
173
  $textToEmbed: [String!]!,
174
174
  $modelSize: String!
@@ -183,7 +183,7 @@
183
183
  error
184
184
  }
185
185
  }
186
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=u.gql`
186
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=u.gql`
187
187
  mutation RunAutotagPipeline($contentSourceIDs: [String!], $forceReprocess: Boolean) {
188
188
  RunAutotagPipeline(contentSourceIDs: $contentSourceIDs, forceReprocess: $forceReprocess) {
189
189
  Success
@@ -297,7 +297,12 @@
297
297
  }
298
298
  }
299
299
  }
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 L="5.41.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 a=s.get(n);r.set(n,a===void 0?null:a)}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=L.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 "${L}"`);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 ${L}). 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),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),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),a=await r.transaction(s).objectStore(s).get(n);return a===void 0?null:a}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),a=Array.from(new Set(e)),i=a.map(I=>this.getStoreKey(I,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),l=i.map(I=>y.get(I)),f=await Promise.all(l);await o.done;for(let I=0;I<a.length;I++){const g=f[I];r.set(a[I],g===void 0?null:g)}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),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.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}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const y of o)typeof y=="string"&&y.startsWith(n)&&await i.delete(y);await a.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(y=>String(y));const o=`[${r}]:`;return i.map(y=>String(y)).filter(y=>y.startsWith(o)).map(y=>y.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}const N=new P;class re 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,a,i,o,y,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:l},n,a,i)}}class h extends c.ProviderBase{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
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!) {
301
+ RemoteOperationProgress(channelId: $channelId) {
302
+ ChannelId
303
+ ProgressJSON
304
+ }
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 {
301
306
  ${this.userInfoString()}
302
307
  MJUserRoles_UserIDArray {
303
308
  ${this.userRoleInfoString()}
@@ -306,7 +311,7 @@
306
311
  `,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
307
312
  ${this._innerCurrentUserQueryString}
308
313
  CurrentUserTenantContext
309
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new A.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`
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`
310
315
  query GetReportDataQuery ($ReportID: String!) {
311
316
  GetReportData(ReportID: $ReportID) {
312
317
  Success
@@ -321,25 +326,25 @@
321
326
  ${this.QueryReturnFieldList}
322
327
  }
323
328
  }
324
- `,a={SQL:e};r!==void 0&&(a.TimeoutSeconds=r),t!==void 0&&(a.MaxRows=t),s!==void 0&&(a.StartRow=s);const i=await this.ExecuteGQL(n,{input:a});return i?.ExecuteAdhocQuery?this.TransformQueryPayload(i.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=u.gql`
329
+ `,o={SQL:e};r!==void 0&&(o.TimeoutSeconds=r),t!==void 0&&(o.MaxRows=t),s!==void 0&&(o.StartRow=s);const i=await this.ExecuteGQL(n,{input:o});return i?.ExecuteAdhocQuery?this.TransformQueryPayload(i.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=u.gql`
325
330
  query RunQueriesBatch($input: [RunQueryInput!]!) {
326
331
  RunQueries(input: $input) {
327
332
  ${this.QueryReturnFieldList}
328
333
  }
329
334
  }
330
- `,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i){const o=u.gql`
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`
331
336
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
332
337
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
333
338
  ${this.QueryReturnFieldList}
334
339
  }
335
340
  }
336
- `,y={QueryID:e};t!==void 0&&(y.CategoryID=t),r!==void 0&&(y.CategoryPath=r),n!==void 0&&(y.Parameters=n),a!==void 0&&(y.MaxRows=a),i!==void 0&&(y.StartRow=i);const l=await this.ExecuteGQL(o,y);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=u.gql`
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`
337
342
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
338
343
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
339
344
  ${this.QueryReturnFieldList}
340
345
  }
341
346
  }
342
- `,y={QueryName:e};t!==void 0&&(y.CategoryID=t),r!==void 0&&(y.CategoryPath=r),n!==void 0&&(y.Parameters=n),a!==void 0&&(y.MaxRows=a),i!==void 0&&(y.StartRow=i);const l=await this.ExecuteGQL(o,y);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
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`
343
348
  Success
344
349
  QueryID
345
350
  QueryName
@@ -348,7 +353,7 @@
348
353
  TotalRowCount
349
354
  ExecutionTime
350
355
  ErrorMessage
351
- 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(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
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`
352
357
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
353
358
  RunQueriesWithCacheCheck(input: $input) {
354
359
  success
@@ -364,14 +369,14 @@
364
369
  }
365
370
  }
366
371
  }
367
- `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const y=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:y,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.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 a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:S,v:E}=await this.getEntityNameAndUserView(e,t);i=E,a=S}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const l=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!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),y||(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(o,i,e,y),I=e.Aggregates&&e.Aggregates.length>0?`
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?`
368
373
  AggregateResults {
369
374
  alias
370
375
  expression
371
376
  value
372
377
  error
373
378
  }
374
- AggregateExecutionTime`:"",g=u.gql`
379
+ AggregateExecutionTime`:"",y=u.gql`
375
380
  query RunViewQuery ($input: ${s}!) {
376
381
  ${r}(input: $input) {
377
382
  Results {
@@ -385,14 +390,14 @@
385
390
  Success
386
391
  ErrorMessage${I}
387
392
  }
388
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const p=await this.ExecuteGQL(g,{input:n});if(p&&p[r]){const S=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:p[r].AggregateExecutionTime});const E=p[r].Results;if(E&&E.length>0){const C=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);E.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(b=>{v[b.Name]=v[b.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 f="",I="";const g={};let p=null,S=null;if(l.ViewEntity)S=l.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:b}=await this.getEntityNameAndUserView(l,t);S=b,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?(f=`Run${C}ViewByID`,I="RunViewByIDInput",g.ViewID=l.ViewID):l.ViewName?(f=`Run${C}ViewByName`,I="RunViewByNameInput",g.ViewName=l.ViewName):(D=!0,f=`Run${C}DynamicView`,I="RunDynamicViewInput",g.EntityName=l.EntityName),g.ExtraFilter=l.ExtraFilter||"",g.OrderBy=l.OrderBy||"",g.UserSearchString=l.UserSearchString||"",g.Fields=l.Fields,g.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(g.MaxRows=l.MaxRows),l.StartRow!==void 0&&(g.StartRow=l.StartRow),l.AfterKey&&(g.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),g.ForceAuditLog=l.ForceAuditLog||!1,g.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(g.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(g.BypassCache=l.BypassCache),D||(g.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=l.OverrideExcludeFilter||"",g.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(g.Aggregates=l.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(g),n.push(...this.getViewRunTimeFieldList(E,S,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
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)?`
389
394
  AggregateResults {
390
395
  alias
391
396
  expression
392
397
  value
393
398
  error
394
399
  }
395
- AggregateExecutionTime`:"",o=u.gql`
400
+ AggregateExecutionTime`:"",a=u.gql`
396
401
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
397
402
  RunViews(input: $input) {
398
403
  Results {
@@ -410,7 +415,7 @@
410
415
  Success
411
416
  ErrorMessage${i}
412
417
  }
413
- }`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[f,I]of l.entries())I.Results=I.Results.map(g=>{let p=JSON.parse(g.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(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
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`
414
419
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
415
420
  RunViewsWithCacheCheck(input: $input) {
416
421
  success
@@ -443,7 +448,7 @@
443
448
  }
444
449
  }
445
450
  }
446
- `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,y)=>{const l=e[y];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(I=>{const g=JSON.parse(I.Data);return this.ConvertBackToMJFields(g),g});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(I=>{const g=JSON.parse(I.Data);return this.ConvertBackToMJFields(g),g});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.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 a of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);r.Fields.forEach(a=>{n.push(N.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(N.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&n.push(N.MapFieldName(a.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,a)=>n.ChangedAt>a.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!) {
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!) {
447
452
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
448
453
  EntityName
449
454
  RelatedEntityName
@@ -477,7 +482,7 @@
477
482
  }
478
483
  }
479
484
  }
480
- }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async SearchEntities(e){if(!e||e.length===0)return[];if(e.filter(i=>i?.entityName&&i?.searchText&&i.searchText.trim()).length===0)return e.map(()=>[]);const r=u.gql`query SearchEntitiesQuery($params: [SearchEntityInput!]!) {
485
+ }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async SearchEntities(e){if(!e||e.length===0)return[];if(e.filter(i=>i?.entityName&&i?.searchText&&i.searchText.trim()).length===0)return e.map(()=>[]);const r=u.gql`query SearchEntitiesQuery($params: [SearchEntityInput!]!) {
481
486
  SearchEntities(params: $params) {
482
487
  Success
483
488
  ErrorMessage
@@ -493,7 +498,15 @@
493
498
  }
494
499
  }
495
500
  }
496
- }`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(o=>({entityRecordDocumentId:o.EntityRecordDocumentID,recordId:o.RecordID,score:o.Score,matchType:o.MatchType,components:{lexical:o.LexicalScore??void 0,semantic:o.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&c.LogError(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}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!) {
501
+ }`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(a=>({entityRecordDocumentId:a.EntityRecordDocumentID,recordId:a.RecordID,score:a.Score,matchType:a.MatchType,components:{lexical:a.LexicalScore??void 0,semantic:a.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&c.LogError(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}async InternalRouteOperation(e,t,r){const s=u.gql`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!, $progressChannelId: String) {
502
+ ExecuteRemoteOperation(input: { operationKey: $operationKey, inputJSON: $inputJSON, invokeMode: $invokeMode, progressChannelId: $progressChannelId }) {
503
+ success
504
+ resultCode
505
+ outputJSON
506
+ handle
507
+ errorMessage
508
+ }
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!) {
497
510
  MergeRecords(request: $request) {
498
511
  Success
499
512
  OverallStatus
@@ -510,32 +523,32 @@
510
523
  Message
511
524
  }
512
525
  }
513
- }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.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:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,y=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),l=` ${o}(input: $input) {
514
- ${e.Fields.map(g=>N.MapFieldName(g.CodeName)).join(`
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(`
515
528
  `)}
516
- }`,f=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
517
- ${l}
529
+ }`,f=u.gql`mutation ${o}${i} ($input: ${a}Input!) {
530
+ ${d}
518
531
  }
519
- `;for(let g=0;g<y.length;g++){const p=y[g];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[N.MapFieldName(p.CodeName)]=S}const I=e.RestoreContext;if(I&&(n.input.RestoreContext___={SourceChangeID:I.SourceChangeID,Reason:I.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];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),g.push({Key:N.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",l,n,{mutationName:o,mutationInputTypes:g},(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 g=await this.ExecuteGQL(f,n);if(g&&g[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[o]),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 a="",i="";for(let I=0;I<t.KeyValuePairs.length;I++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[I].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(I),S=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${S}!`,a.length>0&&(a+=", "),a+=`${g.CodeName}: $${g.CodeName}`,g.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(I)))throw new Error(`Primary Key value ${p} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(p)}else n[g.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),l=u.gql`query Single${y}${o.length>0?"Full":""} (${i}) {
520
- ${y}(${a}) {
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}) {
533
+ ${g}(${o}) {
521
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(`
522
535
  `)}
523
- ${o}
536
+ ${a}
524
537
  }
525
538
  }
526
- `,f=await this.ExecuteGQL(l,n);return f&&f[y]?this.ConvertBackToMJFields(f[y]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return N.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],a=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+=`
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+=`
527
540
  ${i} {
528
- ${a.Fields.map(o=>o.CodeName).join(`
541
+ ${o.Fields.map(a=>a.CodeName).join(`
529
542
  `)}
530
543
  }
531
- `}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={},a=[];let i="",o="",y="";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,a.push({varName:S.CodeName,inputType:S.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${S.CodeName}: $${S.CodeName}`,o.length>0&&(o+=", "),o+=`$${S.CodeName}: ${S.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
532
- `),y+=`${S.CodeName}`}a.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___) {
533
- ${y}
544
+ `}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___) {
546
+ ${g}
534
547
  }
535
- `,g=u.gql`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
548
+ `,y=u.gql`mutation ${f} (${a}, $options___: DeleteOptionsInput!) {
536
549
  ${I}
537
550
  }
538
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",I,n,{mutationName:f,mutationInputTypes:a},(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(g,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!]) {
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!]) {
539
552
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
540
553
  DatasetID
541
554
  DatasetName
@@ -553,7 +566,7 @@
553
566
  LatestUpdateDate
554
567
  EntityUpdateDates
555
568
  }
556
- }`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(a=>({DatasetID:a.DatasetID,DatasetName:a.DatasetName,Success:a.Success,Status:a.Status,LatestUpdateDate:a.LatestUpdateDate?new Date(a.LatestUpdateDate):null,EntityUpdateDates:a.EntityUpdateDates?JSON.parse(a.EntityUpdateDates):null}));for(const a of e){const i=n.find(o=>o.DatasetName===a.datasetName);i?a.resolve(i):a.resolve({DatasetID:"",DatasetName:a.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){c.LogError(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const a=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(a)}catch(a){n.reject(a)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=u.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
569
+ }`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(o=>({DatasetID:o.DatasetID,DatasetName:o.DatasetName,Success:o.Success,Status:o.Status,LatestUpdateDate:o.LatestUpdateDate?new Date(o.LatestUpdateDate):null,EntityUpdateDates:o.EntityUpdateDates?JSON.parse(o.EntityUpdateDates):null}));for(const o of e){const i=n.find(a=>a.DatasetName===o.datasetName);i?o.resolve(i):o.resolve({DatasetID:"",DatasetName:o.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){c.LogError(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const o=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(o)}catch(o){n.reject(o)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=u.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
557
570
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
558
571
  DatasetID
559
572
  DatasetName
@@ -562,16 +575,16 @@
562
575
  LatestUpdateDate
563
576
  EntityUpdateDates
564
577
  }
565
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new q(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
578
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new q(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
566
579
  GetRecordFavoriteStatus(params: $params) {
567
580
  Success
568
581
  IsFavorite
569
582
  }
570
- }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.EntityByName(t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
583
+ }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const o=this.EntityByName(t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
571
584
  SetRecordFavoriteStatus(params: $params){
572
585
  Success
573
586
  }
574
- }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=u.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
587
+ }`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(a&&a.SetRecordFavoriteStatus!==null)return a.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=u.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
575
588
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
576
589
  Success
577
590
  Status
@@ -602,16 +615,16 @@
602
615
  ErrorMessage
603
616
  Result
604
617
  }
605
- }`,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 a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);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__")+`
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__")+`
606
619
  `:s.startsWith("_")||(t+=s+`
607
- `);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}),"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,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.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 A.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(a=>{r.next(a.data)},"next"),error:d(async a=>{const i=a;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(y){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",y),r.error(y)}}else r.error(a)},"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 A.Observable(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
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!) {
608
621
  statusUpdates(sessionId: $sessionId) {
609
622
  date
610
623
  message
611
624
  sessionId
612
625
  }
613
626
  }
614
- `,n=new A.Subject,a=this.getOrCreateWSClient(),i=new A.Subscription;return i.add(new A.Observable(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const f=l;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(),o.complete()}catch(g){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",g),o.error(g)}}else o.error(l)},"error"),complete:d(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(o=>n.next(o),"next"),error:d(o=>{n.error(o),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 A.Observable(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const l=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.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(`
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(`
615
628
  subscription ClientToolRequest($sessionID: String!) {
616
629
  ClientToolRequest(sessionID: $sessionID) {
617
630
  AgentRunID
@@ -633,7 +646,7 @@
633
646
  OriginSessionID
634
647
  RecordData
635
648
  }
636
- }`,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){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: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!) {
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!) {
637
650
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
638
651
  Success
639
652
  ChildEntityName
@@ -645,14 +658,14 @@
645
658
  ChildEntityNames
646
659
  ErrorMessage
647
660
  }
648
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function se(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}d(se,"setupGraphQLClient");class ne{static{d(this,"SyncRolesAndUsersResult")}}class ae{static{d(this,"RoleInput")}}class oe{static{d(this,"UserInput")}}class ie{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 ce{static{d(this,"ActionItemInput")}}class ue{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class le{static{d(this,"ActionItemOutput")}}class de{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!) {
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!) {
649
662
  GetData(input: $input) {
650
663
  Success
651
664
  ErrorMessages
652
665
  Queries
653
666
  Results
654
667
  }
655
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
668
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
656
669
  GetAllEntities {
657
670
  Success
658
671
  ErrorMessage
@@ -1038,7 +1051,7 @@
1038
1051
  executionTimeMs
1039
1052
  }
1040
1053
  }
1041
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=u.gql`
1054
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=u.gql`
1042
1055
  query EmbedTextSystemUser(
1043
1056
  $textToEmbed: [String!]!,
1044
1057
  $modelSize: String!
@@ -1053,7 +1066,7 @@
1053
1066
  error
1054
1067
  }
1055
1068
  }
1056
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=u.gql`
1069
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=u.gql`
1057
1070
  mutation SearchKnowledgeAsSystemUser($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
1058
1071
  SearchKnowledgeAsSystemUser(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
1059
1072
  Success
@@ -1158,7 +1171,7 @@
1158
1171
  ErrorMessage
1159
1172
  }
1160
1173
  }
1161
- `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const a=n.CheckEntityPermissionsSystemUser;return{Success:a.Success,Results:(a.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:a.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 ge{static{d(this,"SimpleRemoteEntityOutput")}}class me{static{d(this,"SimpleRemoteEntity")}}class Se{static{d(this,"SimpleRemoteEntityField")}}class pe{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),a=await this.executeActionMutation(n);return this.processActionResult(a,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`
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`
1162
1175
  mutation RunAction($input: RunActionInput!) {
1163
1176
  RunAction(input: $input) {
1164
1177
  Success
@@ -1175,56 +1188,56 @@
1175
1188
  ResultData
1176
1189
  }
1177
1190
  }
1178
- `;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 he{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
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`
1179
1192
  query PreviewListDelta($input: ComputeDeltaInput!) {
1180
1193
  PreviewListDelta(input: $input) {
1181
1194
  ...ListDeltaFields
1182
1195
  }
1183
1196
  }
1184
- ${B}
1185
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:Q(e.Source),Mode:e.Mode}});return K(r?.PreviewListDelta)}async ApplyListDelta(e){const t=u.gql`
1197
+ ${K}
1198
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:Q(e.Source),Mode:e.Mode}});return B(r?.PreviewListDelta)}async ApplyListDelta(e){const t=u.gql`
1186
1199
  mutation ApplyListDelta($input: ApplyDeltaInput!) {
1187
1200
  ApplyListDelta(input: $input) {
1188
1201
  ...ApplyResultFields
1189
1202
  }
1190
1203
  }
1191
- ${M}
1204
+ ${b}
1192
1205
  `,r=await this.dataProvider.ExecuteGQL(t,{input:{TargetListId:e.Delta.TargetListId,EntityName:e.Delta.EntityName,ToAdd:e.Delta.ToAdd,ToRemove:e.Delta.ToRemove,Unchanged:e.Delta.Unchanged,AddCount:e.Delta.Counts.Add,RemoveCount:e.Delta.Counts.Remove,UnchangedCount:e.Delta.Counts.Unchanged,SourceTotal:e.Delta.Counts.SourceTotal,TargetTotal:e.Delta.Counts.TargetTotal,DeltaToken:e.Delta.DeltaToken,ConfirmDrops:e.ConfirmDrops}});return T(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=u.gql`
1193
1206
  mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
1194
1207
  MaterializeListFromView(viewId: $viewId, options: $options) {
1195
1208
  ...ApplyResultFields
1196
1209
  }
1197
1210
  }
1198
- ${M}
1211
+ ${b}
1199
1212
  `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,options:{ListName:t.ListName,CategoryId:t.CategoryId,Description:t.Description,RememberLineage:t.RememberLineage,UseSnapshot:t.UseSnapshot,RefreshMode:t.RefreshMode}});return T(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=u.gql`
1200
1213
  mutation AddViewResultsToList($viewId: String!, $listId: String!) {
1201
1214
  AddViewResultsToList(viewId: $viewId, listId: $listId) {
1202
1215
  ...ApplyResultFields
1203
1216
  }
1204
1217
  }
1205
- ${M}
1218
+ ${b}
1206
1219
  `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return T(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=u.gql`
1207
1220
  mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
1208
1221
  RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
1209
1222
  ...ApplyResultFields
1210
1223
  }
1211
1224
  }
1212
- ${M}
1225
+ ${b}
1213
1226
  `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return T(r?.RefreshListFromSource)}async ComposeLists(e){const t=u.gql`
1214
1227
  mutation ComposeLists($input: ComposeListsInput!) {
1215
1228
  ComposeLists(input: $input) {
1216
1229
  ...ListDeltaFields
1217
1230
  }
1218
1231
  }
1219
- ${B}
1220
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(Q),Target:e.Target?Q(e.Target):null}});return K(r?.ComposeLists)}async Share(e){const t=u.gql`
1232
+ ${K}
1233
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(Q),Target:e.Target?Q(e.Target):null}});return B(r?.ComposeLists)}async Share(e){const t=u.gql`
1221
1234
  mutation ShareList($input: ShareListInput!) {
1222
1235
  ShareList(input: $input) {
1223
1236
  ...ShareResultFields
1224
1237
  }
1225
1238
  }
1226
1239
  ${x}
1227
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Ie(e.Target),PermissionLevel:e.PermissionLevel}});return F(r?.ShareList)}async Unshare(e){const t=u.gql`
1240
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:fe(e.Target),PermissionLevel:e.PermissionLevel}});return F(r?.ShareList)}async Unshare(e){const t=u.gql`
1228
1241
  mutation UnshareList($permissionId: String!) {
1229
1242
  UnshareList(permissionId: $permissionId) {
1230
1243
  ...ShareResultFields
@@ -1275,7 +1288,7 @@
1275
1288
  CreatedAt
1276
1289
  }
1277
1290
  }
1278
- `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(fe)}async ListsSharedWithMe(){const e=u.gql`
1291
+ `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Ee)}async ListsSharedWithMe(){const e=u.gql`
1279
1292
  query ListsSharedWithMe {
1280
1293
  ListsSharedWithMe {
1281
1294
  ListID
@@ -1285,7 +1298,7 @@
1285
1298
  SharedAt
1286
1299
  }
1287
1300
  }
1288
- `;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const B=u.gql`
1301
+ `;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const K=u.gql`
1289
1302
  fragment ListDeltaFields on ListDeltaType {
1290
1303
  TargetListId
1291
1304
  EntityName
@@ -1306,7 +1319,7 @@
1306
1319
  }
1307
1320
  DeltaToken
1308
1321
  }
1309
- `,M=u.gql`
1322
+ `,b=u.gql`
1310
1323
  fragment ApplyResultFields on ApplyListResultType {
1311
1324
  Success
1312
1325
  ResultCode
@@ -1325,7 +1338,7 @@
1325
1338
  Message
1326
1339
  PermissionID
1327
1340
  }
1328
- `;function Ie(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}d(Ie,"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 fe(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(fe,"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 K(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(Ee),DeltaToken:e.DeltaToken}}d(K,"parseListDelta");function Ee(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(Ee,"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 Re{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`
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`
1329
1342
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1330
1343
  CreateAPIKey(input: $input) {
1331
1344
  Success
@@ -1341,7 +1354,7 @@
1341
1354
  Error
1342
1355
  }
1343
1356
  }
1344
- `,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 De{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
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`
1345
1358
  mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1346
1359
  RunClusterAnalysis(input: $input) {
1347
1360
  Success
@@ -1357,7 +1370,71 @@
1357
1370
  AnalysisID
1358
1371
  }
1359
1372
  }
1360
- `,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 ve{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
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`
1374
+ mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1375
+ MintLiveKitClientToken(input: $input) {
1376
+ Success
1377
+ ErrorMessage
1378
+ ServerUrl
1379
+ Token
1380
+ Identity
1381
+ RoomName
1382
+ }
1383
+ }
1384
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.MintLiveKitClientToken;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return c.LogError("GraphQLLiveKitClient.MintClientToken failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",ServerUrl:"",Token:"",Identity:"",RoomName:e.RoomName}}}async StartAgentRoomSession(e){try{const t=u.gql`
1385
+ mutation StartLiveKitAgentRoomSession($input: StartLiveKitAgentRoomSessionInput!) {
1386
+ StartLiveKitAgentRoomSession(input: $input) {
1387
+ Success
1388
+ ErrorMessage
1389
+ SessionBridgeID
1390
+ RoomName
1391
+ ServerUrl
1392
+ ClientToken
1393
+ Identity
1394
+ }
1395
+ }
1396
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.StartLiveKitAgentRoomSession;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return c.LogError("GraphQLLiveKitClient.StartAgentRoomSession failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",SessionBridgeID:"",RoomName:"",ServerUrl:"",ClientToken:"",Identity:""}}}async StopAgentRoomSession(e){try{const t=u.gql`
1397
+ mutation StopLiveKitAgentRoomSession($sessionBridgeID: String!) {
1398
+ StopLiveKitAgentRoomSession(sessionBridgeID: $sessionBridgeID)
1399
+ }
1400
+ `;return(await this._dataProvider.ExecuteGQL(t,{sessionBridgeID:e}))?.StopLiveKitAgentRoomSession===!0}catch(t){return c.LogError("GraphQLLiveKitClient.StopAgentRoomSession failed",void 0,t),!1}}async EndRoom(e){try{const t=u.gql`
1401
+ mutation EndLiveKitRoom($roomName: String!) {
1402
+ EndLiveKitRoom(roomName: $roomName)
1403
+ }
1404
+ `;return(await this._dataProvider.ExecuteGQL(t,{roomName:e}))?.EndLiveKitRoom===!0}catch(t){return c.LogError("GraphQLLiveKitClient.EndRoom failed",void 0,t),!1}}async InviteUsers(e,t){try{const r=u.gql`
1405
+ mutation InviteUsersToLiveKitRoom($roomName: String!, $userIDs: [String!]!) {
1406
+ InviteUsersToLiveKitRoom(roomName: $roomName, userIDs: $userIDs)
1407
+ }
1408
+ `;return(await this._dataProvider.ExecuteGQL(r,{roomName:e,userIDs:t}))?.InviteUsersToLiveKitRoom===!0}catch(r){return c.LogError("GraphQLLiveKitClient.InviteUsers failed",void 0,r),!1}}async GetRealtimeModelVoices(){try{const e=u.gql`
1409
+ query GetRealtimeModelVoices {
1410
+ GetRealtimeModelVoices {
1411
+ ModelID
1412
+ ModelName
1413
+ Voices {
1414
+ ID
1415
+ Name
1416
+ }
1417
+ }
1418
+ }
1419
+ `;return(await this._dataProvider.ExecuteGQL(e,{}))?.GetRealtimeModelVoices??[]}catch(e){return c.LogError("GraphQLLiveKitClient.GetRealtimeModelVoices failed",void 0,e),[]}}async StartRecording(e,t){return this.runRecordingMutation(u.gql`
1420
+ mutation StartLiveKitRecording($input: LiveKitRecordingInput!) {
1421
+ StartLiveKitRecording(input: $input) {
1422
+ Success
1423
+ ErrorMessage
1424
+ EgressID
1425
+ Status
1426
+ }
1427
+ }
1428
+ `,{input:{RoomName:e,Layout:t}},"StartLiveKitRecording","")}async StopRecording(e){return this.runRecordingMutation(u.gql`
1429
+ mutation StopLiveKitRecording($egressID: String!) {
1430
+ StopLiveKitRecording(egressID: $egressID) {
1431
+ Success
1432
+ ErrorMessage
1433
+ EgressID
1434
+ Status
1435
+ }
1436
+ }
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`
1361
1438
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1362
1439
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1363
1440
  Success
@@ -1367,7 +1444,7 @@
1367
1444
  NodesJSON
1368
1445
  }
1369
1446
  }
1370
- `,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 Ce{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`
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`
1371
1448
  query IsTestRunning($testId: String!) {
1372
1449
  IsTestRunning(testId: $testId)
1373
1450
  }
@@ -1425,7 +1502,7 @@
1425
1502
  result
1426
1503
  }
1427
1504
  }
1428
- `}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 we{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
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`
1429
1506
  query GetRegistryComponent(
1430
1507
  $registryName: String!,
1431
1508
  $namespace: String!,
@@ -1446,7 +1523,7 @@
1446
1523
  specification
1447
1524
  }
1448
1525
  }
1449
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return c.LogError(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=u.gql`
1526
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(o){return c.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=u.gql`
1450
1527
  query GetRegistryComponent(
1451
1528
  $registryName: String!,
1452
1529
  $namespace: String!,
@@ -1467,7 +1544,7 @@
1467
1544
  specification
1468
1545
  }
1469
1546
  }
1470
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=u.gql`
1547
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=u.gql`
1471
1548
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
1472
1549
  SearchRegistryComponents(params: $params) {
1473
1550
  components
@@ -1509,7 +1586,7 @@
1509
1586
  error
1510
1587
  }
1511
1588
  }
1512
- `,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 $e{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(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
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`
1513
1590
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1514
1591
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1515
1592
  Success
@@ -1525,7 +1602,7 @@
1525
1602
  }
1526
1603
  }
1527
1604
  }
1528
- `,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 Pe{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
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`
1529
1606
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1530
1607
  ListStorageObjects(input: $input) {
1531
1608
  objects {
@@ -1542,18 +1619,18 @@
1542
1619
  prefixes
1543
1620
  }
1544
1621
  }
1545
- `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw c.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return c.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=u.gql`
1622
+ `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(s){const n=s;throw c.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return c.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=u.gql`
1546
1623
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1547
1624
  CreateDirectory(input: $input)
1548
1625
  }
1549
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return c.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){const s=r;return c.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=u.gql`
1626
+ `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return c.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(o=>o.name===s||o.fullPath===t)}catch(r){const s=r;return c.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=u.gql`
1550
1627
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1551
1628
  CreatePreAuthUploadUrl(input: $input) {
1552
1629
  UploadUrl
1553
1630
  ProviderKey
1554
1631
  }
1555
1632
  }
1556
- `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw c.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=u.gql`
1633
+ `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw c.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=u.gql`
1557
1634
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1558
1635
  CreatePreAuthDownloadUrl(input: $input)
1559
1636
  }
@@ -1581,7 +1658,7 @@
1581
1658
  destinationPath
1582
1659
  }
1583
1660
  }
1584
- `,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return c.LogError(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=u.gql`
1661
+ `,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,o);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const o=n;return c.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=u.gql`
1585
1662
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1586
1663
  SearchAcrossAccounts(input: $input) {
1587
1664
  accountResults {
@@ -1609,7 +1686,7 @@
1609
1686
  failedAccounts
1610
1687
  }
1611
1688
  }
1612
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.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 Ae{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`
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`
1613
1690
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1614
1691
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1615
1692
  Success
@@ -1715,7 +1792,7 @@
1715
1792
  IsPersonal
1716
1793
  }
1717
1794
  }
1718
- `;return((await this._dataProvider.ExecuteGQL(e,{}))?.SearchScopes??[]).map(s=>({ID:s.ID,Name:s.Name,Description:s.Description??void 0,Icon:s.Icon??void 0,IsGlobal:!!s.IsGlobal,IsDefault:!!s.IsDefault,IsPersonal:!!s.IsPersonal}))}catch(e){return c.LogError(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new A.Observable(t=>{const r=u.gql`
1795
+ `;return((await this._dataProvider.ExecuteGQL(e,{}))?.SearchScopes??[]).map(s=>({ID:s.ID,Name:s.Name,Description:s.Description??void 0,Icon:s.Icon??void 0,IsGlobal:!!s.IsGlobal,IsDefault:!!s.IsDefault,IsPersonal:!!s.IsPersonal}))}catch(e){return c.LogError(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new L.Observable(t=>{const r=u.gql`
1719
1796
  mutation StreamScopedSearch(
1720
1797
  $query: String!,
1721
1798
  $maxResults: Float,
@@ -1736,7 +1813,7 @@
1736
1813
  StreamID
1737
1814
  ErrorMessage
1738
1815
  }
1739
- }`,s=this.prepareSearchVariables(e);let n=null;return(async()=>{try{const i=(await this._dataProvider.ExecuteGQL(r,s))?.StreamScopedSearch;if(!i?.Success){t.error(new Error(i?.ErrorMessage??"StreamScopedSearch failed to start"));return}const o=u.gql`
1816
+ }`,s=this.prepareSearchVariables(e);let n=null;return(async()=>{try{const i=(await this._dataProvider.ExecuteGQL(r,s))?.StreamScopedSearch;if(!i?.Success){t.error(new Error(i?.ErrorMessage??"StreamScopedSearch failed to start"));return}const a=u.gql`
1740
1817
  subscription SearchStream($streamID: ID!) {
1741
1818
  SearchStreamEvents(streamID: $streamID) {
1742
1819
  StreamID
@@ -1748,7 +1825,7 @@
1748
1825
  ElapsedMs
1749
1826
  ErrorMessage
1750
1827
  }
1751
- }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(y=>{const l=y?.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(y=>t.error(y),"error")})}catch(a){t.error(a)}})(),()=>{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 Ne{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
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`
1752
1829
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1753
1830
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1754
1831
  Success
@@ -1805,7 +1882,7 @@
1805
1882
  Warnings
1806
1883
  }
1807
1884
  }
1808
- `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return c.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=u.gql`
1885
+ `,o=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Files:o.Files??[],Warnings:o.Warnings??[]}}catch(s){const n=s;return c.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=u.gql`
1809
1886
  query IntegrationPreviewData(
1810
1887
  $companyIntegrationID: String!,
1811
1888
  $objectName: String!,
@@ -1823,7 +1900,7 @@
1823
1900
  }
1824
1901
  }
1825
1902
  }
1826
- `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return c.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=u.gql`
1903
+ `,o=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Records:o.Records??[]}}catch(s){const n=s;return c.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=u.gql`
1827
1904
  query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
1828
1905
  IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
1829
1906
  Success
@@ -1860,13 +1937,13 @@
1860
1937
  IntegrationUpdateEntityMaps(updates: $updates) { Success Message }
1861
1938
  }`;return(await this._dataProvider.ExecuteGQL(t,{updates:e}))?.IntegrationUpdateEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async DeleteEntityMaps(e){try{const t=u.gql`mutation IntegrationDeleteEntityMaps($entityMapIDs: [String!]!) {
1862
1939
  IntegrationDeleteEntityMaps(entityMapIDs: $entityMapIDs) { Success Message }
1863
- }`;return(await this._dataProvider.ExecuteGQL(t,{entityMapIDs:e}))?.IntegrationDeleteEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async ApplySchema(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplySchema(
1940
+ }`;return(await this._dataProvider.ExecuteGQL(t,{entityMapIDs:e}))?.IntegrationDeleteEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async ApplySchema(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplySchema(
1864
1941
  $companyIntegrationID: String!, $objects: [SchemaPreviewObjectInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1865
1942
  ) {
1866
1943
  IntegrationApplySchema(companyIntegrationID: $companyIntegrationID, objects: $objects, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
1867
1944
  Success Message Steps { Name Status DurationMs Message } MigrationFilePath APIRestarted GitCommitSuccess
1868
1945
  }
1869
- }`;return(await this._dataProvider.ExecuteGQL(a,{companyIntegrationID:e,objects:t,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplySchema??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplySchemaBatch(e,t="sqlserver",r=!1,s=!1){try{const n=u.gql`mutation IntegrationApplySchemaBatch(
1946
+ }`;return(await this._dataProvider.ExecuteGQL(o,{companyIntegrationID:e,objects:t,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplySchema??{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplySchemaBatch(e,t="sqlserver",r=!1,s=!1){try{const n=u.gql`mutation IntegrationApplySchemaBatch(
1870
1947
  $items: [ApplySchemaBatchItemInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1871
1948
  ) {
1872
1949
  IntegrationApplySchemaBatch(items: $items, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -1892,14 +1969,14 @@
1892
1969
  }
1893
1970
  }
1894
1971
  }
1895
- `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListSourceObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async ApplyAllBatch(e,t=!0,r=!1,s="created",n="sqlserver",a=!1,i=!1){try{const o=u.gql`mutation($input: ApplyAllBatchInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!) {
1972
+ `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListSourceObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async ApplyAllBatch(e,t=!0,r=!1,s="created",n="sqlserver",o=!1,i=!1){try{const a=u.gql`mutation($input: ApplyAllBatchInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!) {
1896
1973
  IntegrationApplyAllBatch(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
1897
1974
  Success Message SuccessCount FailureCount
1898
1975
  ConnectorResults { CompanyIntegrationID IntegrationName Success Message EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount } SyncRunID Warnings }
1899
1976
  PipelineSteps { Name Status DurationMs Message }
1900
1977
  GitCommitSuccess APIRestarted
1901
1978
  }
1902
- }`,y={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},l=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,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(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplyAll(
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(
1903
1980
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1904
1981
  ) {
1905
1982
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -1908,7 +1985,7 @@
1908
1985
  EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount }
1909
1986
  SyncRunID GitCommitSuccess APIRestarted Warnings
1910
1987
  }
1911
- }`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(a,{input:i,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplyAll??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async StartSync(e,t,r,s){try{const n=u.gql`mutation IntegrationStartSync(
1988
+ }`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(o,{input:i,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplyAll??{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async StartSync(e,t,r,s){try{const n=u.gql`mutation IntegrationStartSync(
1912
1989
  $companyIntegrationID: String!,
1913
1990
  $webhookURL: String,
1914
1991
  $fullSync: Boolean,
@@ -1941,5 +2018,5 @@
1941
2018
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
1942
2019
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
1943
2020
  }
1944
- }`;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=ce,exports.ActionItemOutput=le,exports.BrowserIndexedDBStorageProvider=O,exports.BrowserStorageProviderBase=V,exports.FieldMapper=P,exports.FireAndForgetHelper=$,exports.GetDataOutput=ye,exports.GraphQLAIClient=U,exports.GraphQLActionClient=pe,exports.GraphQLClassifyClient=ve,exports.GraphQLClusterClient=De,exports.GraphQLComponentRegistryClient=we,exports.GraphQLDataProvider=h,exports.GraphQLEncryptionClient=Re,exports.GraphQLFileStorageClient=Pe,exports.GraphQLIntegrationClient=Ne,exports.GraphQLListsClient=he,exports.GraphQLProviderConfigData=re,exports.GraphQLSearchClient=Ae,exports.GraphQLSystemUserClient=de,exports.GraphQLTestingClient=Ce,exports.GraphQLTransactionGroup=q,exports.GraphQLVersionHistoryClient=$e,exports.PACKAGE_VERSION=L,exports.RoleInput=ae,exports.RolesAndUsersInput=ie,exports.SimpleRemoteEntity=me,exports.SimpleRemoteEntityField=Se,exports.SimpleRemoteEntityOutput=ge,exports.SyncDataAction=k,exports.SyncDataResult=ue,exports.SyncRolesAndUsersResult=ne,exports.UserInput=oe,exports.setupGraphQLClient=se;
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;
1945
2022
  //# sourceMappingURL=index.cjs.map