@memberjunction/graphql-dataprovider 6.1.0-edge.2 → 6.1.0-edge.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as B}from"graphql-request";import{gql as Pt}from"graphql-request";import{TransactionGroupBase as ce,TransactionResult as ue,LogError as y,LogStatus as P,LogErrorEx as A,ProviderBase as le,UserInfo as j,getGraphQLTypeNameBase as x,ProviderType as de,BaseEntityResult as G,EntityFieldTSType as b,TransactionItem as J,CompositeKey as ye,UserRoleInfo as me,InMemoryLocalStorageProvider as ge,BaseEntity as Se,ProviderConfigDataBase as pe,SetProvider as he,StartupManager as Ie,IsPlatformSQL as fe,IsVerboseLoggingEnabled as Re}from"@memberjunction/core";import{SafeJSONParse as v,CleanAndParseJSON as Ee,GetGlobalObjectStore as W,MJGlobal as z,MJEventType as H}from"@memberjunction/global";import{ViewInfo as X}from"@memberjunction/core-entities";import{BehaviorSubject as De,Observable as T,Subject as ve,Subscription as Ce}from"rxjs";import{createClient as we}from"graphql-ws";import{v4 as $e}from"uuid";import{openDB as Pe}from"@tempfix/idb";class M{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(M.DB_PREFIX)?M.GQL_PREFIX+e.substring(M.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(M.GQL_PREFIX)?M.DB_PREFIX+e.substring(M.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 Y extends ce{static{l(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
1
+ var le=Object.defineProperty;var l=(d,e)=>le(d,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as B}from"graphql-request";import{gql as bt}from"graphql-request";import{TransactionGroupBase as de,TransactionResult as ye,LogError as y,LogStatus as P,LogErrorEx as b,ProviderBase as me,UserInfo as j,getGraphQLTypeNameBase as T,ProviderType as ge,BaseEntityResult as U,EntityFieldTSType as N,TransactionItem as J,CompositeKey as Se,UserRoleInfo as pe,InMemoryLocalStorageProvider as he,BaseEntity as Ie,ProviderConfigDataBase as fe,SetProvider as Ee,StartupManager as Re,IsPlatformSQL as De,IsVerboseLoggingEnabled as ve}from"@memberjunction/core";import{SafeJSONParse as v,CleanAndParseJSON as Ce,GetGlobalObjectStore as W,MJGlobal as H,MJEventType as z}from"@memberjunction/global";import{ViewInfo as X}from"@memberjunction/core-entities";import{BehaviorSubject as we,Observable as x,Subject as Y,Subscription as Z}from"rxjs";import{createClient as $e}from"graphql-ws";import{v4 as Pe}from"uuid";import{openDB as be}from"@tempfix/idb";class M{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(M.DB_PREFIX)?M.GQL_PREFIX+e.substring(M.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(M.GQL_PREFIX)?M.DB_PREFIX+e.substring(M.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 ee extends de{static{l(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@ var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0})
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=n.Success===!0,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const g=n.ResultsJSON[o],d=v(g),h=this.PendingTransactions[o];i.push(new ue(h,d,a&&d!==null))}return i}else throw new Error("Failed to execute transaction group")}}const Ae=720*1e3,Me=6;class w{static{l(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;if(!(typeof e.dataProvider.PushStatusUpdates=="function"))return w.executeSynchronously(e);const s=e.timeoutMs??Ae,n=e.maxStallReconciles??Me;let a,i=!1,o=0;const{promise:g,resolve:d,reject:h}=w.createCompletionPromise(),f=l(E=>{i||(i=!0,R.clear(),E())},"finish"),m=l(E=>f(()=>d(E)),"settleResolve"),S=l(E=>f(()=>h(E)),"settleReject"),p=l(async()=>{if(i)return;if(!e.onStall){S(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let E;try{P(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){S(D);return}i||(E==="continue"?++o>n?S(new Error(`The operation is still reported as running but no signal has arrived after ${o} checks. Please refresh the page to check the latest status.`)):R.reset():"resolve"in E?(P(`[FireAndForget:${t}] Reconciliation recovered a completed run`),m(E.resolve)):S(E.reject))},"onStall"),R=w.createIdleTimer(s,()=>{p()});try{R.reset(),a=w.subscribeToPubSub(e,{onActivity:l(()=>{o=0,R.reset()},"onActivity"),onCompletion:l(D=>m(D),"onCompletion"),onStreamEnd:l(()=>{p()},"onStreamEnd")});const E=await w.executeMutation(e);if(!e.validateAck(E)){R.clear();const D=E?.errorMessage??"Server rejected the request";return y(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return P(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await g}catch(E){throw y(`[FireAndForget:${t}] Error: ${E.message}`),E}finally{R.clear(),a&&a.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 a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(P(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"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]}static async executeSynchronously(e){const t=e.operationLabel??e.mutationFieldName;P(`[FireAndForget:${t}] Provider has no PushStatusUpdates channel \u2014 running synchronously (fireAndForget disabled)`);const r={...e.variables,fireAndForget:!1},n=(await e.dataProvider.ExecuteGQL(e.mutation,r))?.[e.mutationFieldName];return n?e.extractSyncResult?(P(`[FireAndForget:${t}] Synchronous execution completed`),e.extractSyncResult(n)):e.createErrorResult(`${t} cannot run on this data provider: it has no PushStatusUpdates channel and no synchronous result extractor is configured for this operation.`):(y(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class Z{static{l(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
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=n.Success===!0,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const m=n.ResultsJSON[o],u=v(m),S=this.PendingTransactions[o];i.push(new ye(S,u,a&&u!==null))}return i}else throw new Error("Failed to execute transaction group")}}const Ae=720*1e3,Me=6;class w{static{l(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;if(!(typeof e.dataProvider.PushStatusUpdates=="function"))return w.executeSynchronously(e);const s=e.timeoutMs??Ae,n=e.maxStallReconciles??Me;let a,i=!1,o=0;const{promise:m,resolve:u,reject:S}=w.createCompletionPromise(),h=l(E=>{i||(i=!0,R.clear(),E())},"finish"),g=l(E=>h(()=>u(E)),"settleResolve"),p=l(E=>h(()=>S(E)),"settleReject"),I=l(async()=>{if(i)return;if(!e.onStall){p(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let E;try{P(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){p(D);return}i||(E==="continue"?++o>n?p(new Error(`The operation is still reported as running but no signal has arrived after ${o} checks. Please refresh the page to check the latest status.`)):R.reset():"resolve"in E?(P(`[FireAndForget:${t}] Reconciliation recovered a completed run`),g(E.resolve)):p(E.reject))},"onStall"),R=w.createIdleTimer(s,()=>{I()});try{R.reset(),a=w.subscribeToPubSub(e,{onActivity:l(()=>{o=0,R.reset()},"onActivity"),onCompletion:l(D=>g(D),"onCompletion"),onStreamEnd:l(()=>{I()},"onStreamEnd")});const E=await w.executeMutation(e);if(!e.validateAck(E)){R.clear();const D=E?.errorMessage??"Server rejected the request";return y(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return P(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await m}catch(E){throw y(`[FireAndForget:${t}] Error: ${E.message}`),E}finally{R.clear(),a&&a.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 a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(P(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"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]}static async executeSynchronously(e){const t=e.operationLabel??e.mutationFieldName;P(`[FireAndForget:${t}] Provider has no PushStatusUpdates channel \u2014 running synchronously (fireAndForget disabled)`);const r={...e.variables,fireAndForget:!1},n=(await e.dataProvider.ExecuteGQL(e.mutation,r))?.[e.mutationFieldName];return n?e.extractSyncResult?(P(`[FireAndForget:${t}] Synchronous execution completed`),e.extractSyncResult(n)):e.createErrorResult(`${t} cannot run on this data provider: it has no PushStatusUpdates channel and no synchronous result extractor is configured for this operation.`):(y(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class te{static{l(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@ var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0})
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=Ee(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 y(`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 w.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"),extractSyncResult:l(i=>this.extractAgentResultFromAck(i),"extractSyncResult"),onMessage:l(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:l(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
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=Ce(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 y(`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 w.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"),extractSyncResult:l(i=>this.extractAgentResultFromAck(i),"extractSyncResult"),onMessage:l(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:l(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -83,7 +83,8 @@ var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0})
83
83
  $sourceArtifactVersionId: String,
84
84
  $fireAndForget: Boolean,
85
85
  $planMode: Boolean,
86
- $requestedSkillIDs: [String!]
86
+ $requestedSkillIDs: [String!],
87
+ $taskGraphDebug: String
87
88
  ) {
88
89
  RunAIAgent(
89
90
  agentId: $agentId,
@@ -102,7 +103,8 @@ var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0})
102
103
  sourceArtifactVersionId: $sourceArtifactVersionId,
103
104
  fireAndForget: $fireAndForget,
104
105
  planMode: $planMode,
105
- requestedSkillIDs: $requestedSkillIDs
106
+ requestedSkillIDs: $requestedSkillIDs,
107
+ taskGraphDebug: $taskGraphDebug
106
108
  ) {
107
109
  success
108
110
  errorMessage
@@ -110,7 +112,7 @@ var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0})
110
112
  result
111
113
  }
112
114
  }
113
- `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),s}processAgentResult(e){return v(e)}handleAgentError(e){const r=e?.message||String(e);y(`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 w.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"),extractSyncResult:l(s=>this.extractAgentResultFromAck(s),"extractSyncResult"),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 c`
115
+ `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),e.taskGraphDebug!==void 0&&(s.taskGraphDebug=JSON.stringify(e.taskGraphDebug)),s}processAgentResult(e){return v(e)}handleAgentError(e){const r=e?.message||String(e);y(`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 w.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"),extractSyncResult:l(s=>this.extractAgentResultFromAck(s),"extractSyncResult"),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 c`
114
116
  mutation RunAIAgentFromConversationDetail(
115
117
  $conversationDetailId: String!,
116
118
  $agentId: String!,
@@ -305,23 +307,23 @@ var ie=Object.defineProperty;var l=(u,e)=>ie(u,"name",{value:e,configurable:!0})
305
307
  }
306
308
  }
307
309
  }
308
- `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return y("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="6.1.0-edge.2",$="default";class ee{static{l(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}get SharesReferences(){return!0}getCategoryMap(e){const t=e||$;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||$).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||$);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||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const be="MJ_Metadata",Ne=0;function xe(){try{const u=F.split("."),e=parseInt(u[0],10),t=parseInt(u[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${F}"`);return e*1e3+t+Ne}catch(u){return A({error:u,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}l(xe,"computeIdbVersion");const Te=xe(),te=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class re extends ee{static{l(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=Pe(be,Te,{upgrade:l((e,t,r)=>{try{P(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${F}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of te)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){A({error:s,message:s?.message})}},"upgrade"),blocked:l((e,t)=>{P(`[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=()=>{P("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return te.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;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){A({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 A({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(f=>this.getStoreKey(f,t)),o=s.transaction(n,"readonly"),g=o.objectStore(n),d=i.map(f=>g.get(f)),h=await Promise.all(d);await o.done;for(let f=0;f<a.length;f++){const m=h[f];r.set(a[f],m===void 0?null:m)}return r}catch(s){A({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){A({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,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 g of o)typeof g=="string"&&g.startsWith(n)&&await i.delete(g);await a.done}}catch(t){A({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(g=>String(g));const o=`[${r}]:`;return i.map(g=>String(g)).filter(g=>g.startsWith(o)).map(g=>g.slice(o.length))}catch(t){return A({error:t,message:t?.message}),[]}}}class V extends Error{static{l(this,"SafeGraphQLError")}constructor(e){super(e.message),this.name=e.name,this.response={status:e.status,errors:e.errors},this.request={query:e.query},this.Code=e.code,this.VariableShape=e.variableShape,this.stack=e.stackFrames?`${e.name}: ${e.message}
309
- ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))}l(se,"ToSafeGraphQLError");const Le=3,Fe=25;function _(u,e=0){if(u===null)return"null";if(u===void 0)return"undefined";if(Array.isArray(u))return u.length===0?"array(empty)":`array(${u.length} \xD7 ${Qe(_(u[0],e+1))})`;if(typeof u=="object"){if(e>=Le)return"object(\u2026)";const t=Object.keys(u);if(t.length>Fe)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=_(u[s],e+1);return r}return typeof u=="string"?u.length===0?"string(empty)":"string":typeof u}l(_,"describeShape");function Qe(u){return typeof u=="string"?u:"object"}l(Qe,"typeOf");function Ue(u){const e=u.indexOf(`
310
- at `);return e===-1?"":u.slice(e+1)}l(Ue,"stripStackHeader");function Ge(u,e){const t=u?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}l(Ge,"deriveMessage");function Ve(u){if(Array.isArray(u))return u.map(e=>{const t=e??{};return{message:typeof t.message=="string"?t.message:void 0,path:Array.isArray(t.path)?t.path:void 0,extensions:t.extensions&&typeof t.extensions=="object"?t.extensions:void 0}})}l(Ve,"extractErrors");function O(u,e=!1){if(!u||typeof u!="object")return{name:typeof u,message:"Non-object value thrown; contents withheld",variables:"[REDACTED]"};const t=u,r=typeof t.response?.status=="number"?t.response.status:void 0,s=Ve(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:Ge(s,r),status:r,errors:s,code:typeof n=="string"?n:void 0,query:typeof t.request?.query=="string"?t.request.query:void 0,stackFrames:typeof t.stack=="string"?Ue(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:_(t.request.variables)}}l(O,"SanitizeGraphQLError");const N=new M,_e=c`subscription RemoteOperationProgress($channelId: ID!) {
310
+ `,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 y("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="6.1.0-edge.3",$="default";class re{static{l(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}get SharesReferences(){return!0}getCategoryMap(e){const t=e||$;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||$).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||$);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||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const Ne="MJ_Metadata",xe=0;function Te(){try{const d=F.split("."),e=parseInt(d[0],10),t=parseInt(d[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${F}"`);return e*1e3+t+xe}catch(d){return b({error:d,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}l(Te,"computeIdbVersion");const Le=Te(),se=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class ne extends re{static{l(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=be(Ne,Le,{upgrade:l((e,t,r)=>{try{P(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${F}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of se)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){b({error:s,message:s?.message})}},"upgrade"),blocked:l((e,t)=>{P(`[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=()=>{P("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{b({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return se.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;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){b({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 b({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(h=>this.getStoreKey(h,t)),o=s.transaction(n,"readonly"),m=o.objectStore(n),u=i.map(h=>m.get(h)),S=await Promise.all(u);await o.done;for(let h=0;h<a.length;h++){const g=S[h];r.set(a[h],g===void 0?null:g)}return r}catch(s){b({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){b({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,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 m of o)typeof m=="string"&&m.startsWith(n)&&await i.delete(m);await a.done}}catch(t){b({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(m=>String(m));const o=`[${r}]:`;return i.map(m=>String(m)).filter(m=>m.startsWith(o)).map(m=>m.slice(o.length))}catch(t){return b({error:t,message:t?.message}),[]}}}class _ extends Error{static{l(this,"SafeGraphQLError")}constructor(e){super(e.message),this.name=e.name,this.response={status:e.status,errors:e.errors},this.request={query:e.query},this.Code=e.code,this.VariableShape=e.variableShape,this.stack=e.stackFrames?`${e.name}: ${e.message}
311
+ ${e.stackFrames}`:this.stack}}function ae(d){return d instanceof _?d:new _(k(d))}l(ae,"ToSafeGraphQLError");const Fe=3,Ge=25;function V(d,e=0){if(d===null)return"null";if(d===void 0)return"undefined";if(Array.isArray(d))return d.length===0?"array(empty)":`array(${d.length} \xD7 ${Qe(V(d[0],e+1))})`;if(typeof d=="object"){if(e>=Fe)return"object(\u2026)";const t=Object.keys(d);if(t.length>Ge)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=V(d[s],e+1);return r}return typeof d=="string"?d.length===0?"string(empty)":"string":typeof d}l(V,"describeShape");function Qe(d){return typeof d=="string"?d:"object"}l(Qe,"typeOf");function Ue(d){const e=d.indexOf(`
312
+ at `);return e===-1?"":d.slice(e+1)}l(Ue,"stripStackHeader");function _e(d,e){const t=d?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}l(_e,"deriveMessage");function Ve(d){if(Array.isArray(d))return d.map(e=>{const t=e??{};return{message:typeof t.message=="string"?t.message:void 0,path:Array.isArray(t.path)?t.path:void 0,extensions:t.extensions&&typeof t.extensions=="object"?t.extensions:void 0}})}l(Ve,"extractErrors");function k(d,e=!1){if(!d||typeof d!="object")return{name:typeof d,message:"Non-object value thrown; contents withheld",variables:"[REDACTED]"};const t=d,r=typeof t.response?.status=="number"?t.response.status:void 0,s=Ve(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:_e(s,r),status:r,errors:s,code:typeof n=="string"?n:void 0,query:typeof t.request?.query=="string"?t.request.query:void 0,stackFrames:typeof t.stack=="string"?Ue(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:V(t.request.variables)}}l(k,"SanitizeGraphQLError");const A=new M,ke=c`subscription RemoteOperationProgress($channelId: ID!) {
311
313
  RemoteOperationProgress(channelId: $channelId) {
312
314
  ChannelId
313
315
  ProgressJSON
314
316
  }
315
- }`;class Oe extends pe{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 LogVariableValues(){return this.Data.LogVariableValues===!0}set LogVariableValues(e){this.Data.LogVariableValues=e}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,g,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:g,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}class I extends le{static{l(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
317
+ }`;class Oe extends fe{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 LogVariableValues(){return this.Data.LogVariableValues===!0}set LogVariableValues(e){this.Data.LogVariableValues=e}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,m,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:m,RefreshTokenFunction:s,OnAuthenticationError:u},n,a,i)}}class f extends me{static{l(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
316
318
  ${this.userInfoString()}
317
- MJUserRoles_UserIDArray {
319
+ Roles {
318
320
  ${this.userRoleInfoString()}
319
321
  }
320
322
  }
321
323
  `,this._currentUserQuery=c`query CurrentUserAndRoles {
322
324
  ${this._innerCurrentUserQueryString}
323
325
  CurrentUserTenantContext
324
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new De("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=W();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=W();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new Z(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 $e()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw y(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new j(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=c`
326
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new we("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._taskGraphFrameStreams=new Map,this._cacheInvalidationSubscription=null;const e=W();if(e&&e[f._globalStoreKey])return e[f._globalStoreKey];e&&(e[f._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=W();return e?e[f._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new te(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 Pe()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(f.Instance._configData=e,f.Instance._sessionId===void 0&&(f.Instance._sessionId=await this.GetPreferredUUID(s)),f.Instance._client||(f.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,f.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.Instance._client),super.Config(e)}catch(n){throw y(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),f.Instance&&f.Instance!==this&&f.Instance._configData===this._configData&&(f.Instance._dynamicHeaders.set(e,t),f.Instance._client&&f.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),f.Instance&&f.Instance!==this&&f.Instance._configData===this._configData&&(f.Instance._dynamicHeaders.delete(e),f.Instance._client&&f.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),{Roles:r,...s}=t,n=(r??[]).map(i=>this.ConvertBackToMJFields(i)),a=new j(this,{...s,UserRoles:n});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(a.TenantContext=e.CurrentUserTenantContext),a}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment,e.DataSource);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment,e.DataSource);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=c`
325
327
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
326
328
  ExecuteAdhocQuery(input: $input) {
327
329
  ${this.QueryReturnFieldList}
@@ -333,19 +335,19 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
333
335
  ${this.QueryReturnFieldList}
334
336
  }
335
337
  }
336
- `,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,Enrichment:a.Enrichment})),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,o){const g=c`
337
- query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
338
- GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
338
+ `,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,Enrichment:a.Enrichment,DataSource:a.DataSource})),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,o,m){const u=c`
339
+ query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
340
+ GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
339
341
  ${this.QueryReturnFieldList}
340
342
  }
341
343
  }
342
- `,d={QueryID:e};t!==void 0&&(d.CategoryID=t),r!==void 0&&(d.CategoryPath=r),n!==void 0&&(d.Parameters=n),a!==void 0&&(d.MaxRows=a),i!==void 0&&(d.StartRow=i),o!==void 0&&(d.Enrichment=o);const h=await this.ExecuteGQL(g,d);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o){const g=c`
343
- query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
344
- GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
344
+ `,S={QueryID:e};t!==void 0&&(S.CategoryID=t),r!==void 0&&(S.CategoryPath=r),n!==void 0&&(S.Parameters=n),a!==void 0&&(S.MaxRows=a),i!==void 0&&(S.StartRow=i),o!==void 0&&(S.Enrichment=o),m!==void 0&&(S.DataSource=m);const h=await this.ExecuteGQL(u,S);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o,m){const u=c`
345
+ query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
346
+ GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
345
347
  ${this.QueryReturnFieldList}
346
348
  }
347
349
  }
348
- `,d={QueryName:e};t!==void 0&&(d.CategoryID=t),r!==void 0&&(d.CategoryPath=r),n!==void 0&&(d.Parameters=n),a!==void 0&&(d.MaxRows=a),i!==void 0&&(d.StartRow=i),o!==void 0&&(d.Enrichment=o);const h=await this.ExecuteGQL(g,d);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
350
+ `,S={QueryName:e};t!==void 0&&(S.CategoryID=t),r!==void 0&&(S.CategoryPath=r),n!==void 0&&(S.Parameters=n),a!==void 0&&(S.MaxRows=a),i!==void 0&&(S.StartRow=i),o!==void 0&&(S.Enrichment=o),m!==void 0&&(S.DataSource=m);const h=await this.ExecuteGQL(u,S);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
349
351
  Success
350
352
  QueryID
351
353
  QueryName
@@ -354,7 +356,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
354
356
  TotalRowCount
355
357
  ExecutionTime
356
358
  ErrorMessage
357
- 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 y(`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,Enrichment:o.params.Enrichment||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
359
+ 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 y(`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,Enrichment:o.params.Enrichment||null,DataSource:o.params.DataSource||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
358
360
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
359
361
  RunQueriesWithCacheCheck(input: $input) {
360
362
  success
@@ -370,18 +372,18 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
370
372
  }
371
373
  }
372
374
  }
373
- `,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 g=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:g,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 y(`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:p,v:R}=await this.getEntityNameAndUserView(e,t);i=R,a=p}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let g=!1;const d=x(o);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(p=>({expression:p.expression,alias:p.alias})));const h=this.getViewRunTimeFieldList(o,i,e,g),f=e.Aggregates&&e.Aggregates.length>0?`
375
+ `,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 m=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:m,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 y(`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:I,v:R}=await this.getEntityNameAndUserView(e,t);i=R,a=I}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let m=!1;const u=T(o);e.ViewID?(r=`Run${u}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${u}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(m=!0,r=`Run${u}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),e.DataSource!==void 0&&(n.DataSource=e.DataSource),m||(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(I=>({expression:I.expression,alias:I.alias})));const S=this.getViewRunTimeFieldList(o,i,e,m),h=e.Aggregates&&e.Aggregates.length>0?`
374
376
  AggregateResults {
375
377
  alias
376
378
  expression
377
379
  value
378
380
  error
379
381
  }
380
- AggregateExecutionTime`:"",m=c`
382
+ AggregateExecutionTime`:"",g=c`
381
383
  query RunViewQuery ($input: ${s}!) {
382
384
  ${r}(input: $input) {
383
385
  Results {
384
- ${h.join(`
386
+ ${S.join(`
385
387
  `)}
386
388
  }
387
389
  UserViewRunID
@@ -389,9 +391,9 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
389
391
  TotalRowCount
390
392
  ExecutionTime
391
393
  Success
392
- ErrorMessage${f}
394
+ ErrorMessage${h}
393
395
  }
394
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const S=await this.ExecuteGQL(m,{input:n});if(S&&S[r]){const p=S[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:S[r].AggregateExecutionTime});const R=S[r].Results;if(R&&R.length>0){const D=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);R.forEach(C=>{this.ConvertBackToMJFields(C),D.forEach(L=>{C[L.Name]=C[L.CodeName]})})}return S[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw y(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let h="",f="";const m={};let S=null,p=null;if(d.ViewEntity)p=d.ViewEntity,S=p.Get("Entity");else{const{entityName:C,v:L}=await this.getEntityNameAndUserView(d,t);p=L,S=C}const R=this.EntityByName(S);if(!R)throw new Error(`Entity ${S} not found in metadata`);s.push(R);let E=!1;const D=x(R);d.ViewID?(h=`Run${D}ViewByID`,f="RunViewByIDInput",m.ViewID=d.ViewID):d.ViewName?(h=`Run${D}ViewByName`,f="RunViewByNameInput",m.ViewName=d.ViewName):(E=!0,h=`Run${D}DynamicView`,f="RunDynamicViewInput",m.EntityName=d.EntityName),m.ExtraFilter=d.ExtraFilter||"",m.OrderBy=d.OrderBy||"",m.UserSearchString=d.UserSearchString||"",m.Fields=d.Fields,m.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(m.MaxRows=d.MaxRows),d.StartRow!==void 0&&(m.StartRow=d.StartRow),d.AfterKey&&(m.AfterKey={KeyValuePairs:d.AfterKey.KeyValuePairs}),m.ForceAuditLog=d.ForceAuditLog||!1,m.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(m.AuditLogDescription=d.AuditLogDescription),d.BypassCache!==void 0&&(m.BypassCache=d.BypassCache),E||(m.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=d.OverrideExcludeFilter||"",m.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(m.Aggregates=d.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(m),n.push(...this.getViewRunTimeFieldList(R,p,d,E))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
396
+ }`;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 I=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:I?.length||0,aggregateResults:I,aggregateExecutionTime:p[r].AggregateExecutionTime});const R=p[r].Results;if(R&&R.length>0){const D=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);R.forEach(C=>{this.ConvertBackToMJFields(C),D.forEach(L=>{C[L.Name]=C[L.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw y(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const u of e){let S="",h="";const g={};let p=null,I=null;if(u.ViewEntity)I=u.ViewEntity,p=I.Get("Entity");else{const{entityName:C,v:L}=await this.getEntityNameAndUserView(u,t);I=L,p=C}const R=this.EntityByName(p);if(!R)throw new Error(`Entity ${p} not found in metadata`);s.push(R);let E=!1;const D=T(R);u.ViewID?(S=`Run${D}ViewByID`,h="RunViewByIDInput",g.ViewID=u.ViewID):u.ViewName?(S=`Run${D}ViewByName`,h="RunViewByNameInput",g.ViewName=u.ViewName):(E=!0,S=`Run${D}DynamicView`,h="RunDynamicViewInput",g.EntityName=u.EntityName),g.ExtraFilter=u.ExtraFilter||"",g.OrderBy=u.OrderBy||"",g.UserSearchString=u.UserSearchString||"",g.Fields=u.Fields,g.IgnoreMaxRows=u.IgnoreMaxRows||!1,u.MaxRows!==void 0&&(g.MaxRows=u.MaxRows),u.StartRow!==void 0&&(g.StartRow=u.StartRow),u.AfterKey&&(g.AfterKey={KeyValuePairs:u.AfterKey.KeyValuePairs}),g.ForceAuditLog=u.ForceAuditLog||!1,g.ResultType=u.ResultType||"simple",u.AuditLogDescription&&u.AuditLogDescription.length>0&&(g.AuditLogDescription=u.AuditLogDescription),u.BypassCache!==void 0&&(g.BypassCache=u.BypassCache),u.DataSource!==void 0&&(g.DataSource=u.DataSource),E||(g.ExcludeUserViewRunID=u.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=u.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=u.OverrideExcludeFilter||"",g.SaveViewResults=u.SaveViewResults||!1),u.Aggregates&&u.Aggregates.length>0&&(g.Aggregates=u.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(g),n.push(...this.getViewRunTimeFieldList(R,I,u,E))}const i=e.some(u=>u.Aggregates&&u.Aggregates.length>0)?`
395
397
  AggregateResults {
396
398
  alias
397
399
  expression
@@ -416,7 +418,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
416
418
  Success
417
419
  ErrorMessage${i}
418
420
  }
419
- }`,g=await this.ExecuteGQL(o,{input:r});if(g&&g.RunViews){const d=g.RunViews;for(const[h,f]of d.entries())f.Results=f.Results.map(m=>{let S=JSON.parse(m.Data);return this.ConvertBackToMJFields(S),S});return d}return null}catch(r){throw y(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",Aggregates:o.params.Aggregates??null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
421
+ }`,m=await this.ExecuteGQL(o,{input:r});if(m&&m.RunViews){const u=m.RunViews;for(const[S,h]of u.entries())h.Results=h.Results.map(g=>{let p=JSON.parse(g.Data);return this.ConvertBackToMJFields(p),p});return u}return null}catch(r){throw y(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",Aggregates:o.params.Aggregates??null,DataSource:o.params.DataSource},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
420
422
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
421
423
  RunViewsWithCacheCheck(input: $input) {
422
424
  success
@@ -455,7 +457,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
455
457
  }
456
458
  }
457
459
  }
458
- `,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,g)=>{const d=e[g];if(o.status==="differential"&&o.differentialData){const h=o.differentialData.updatedRows.map(f=>{const m=JSON.parse(f.Data);return this.ConvertBackToMJFields(m),m});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:h,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const h=o.Results.map(m=>{const S=JSON.parse(m.Data);return this.ConvertBackToMJFields(S),S}),f=o.aggregateResults?.map(m=>({expression:m.expression,alias:m.alias,value:m.value!==void 0&&m.value!==null?JSON.parse(m.value):null,error:m.error}));return{viewIndex:o.viewIndex,status:o.status,results:h,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage,aggregateResults:f}}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 y(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 X.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await X.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 de.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 y(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
460
+ `,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,m)=>{const u=e[m];if(o.status==="differential"&&o.differentialData){const S=o.differentialData.updatedRows.map(h=>{const g=JSON.parse(h.Data);return this.ConvertBackToMJFields(g),g});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:S,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const S=o.Results.map(g=>{const p=JSON.parse(g.Data);return this.ConvertBackToMJFields(p),p}),h=o.aggregateResults?.map(g=>({expression:g.expression,alias:g.alias,value:g.value!==void 0&&g.value!==null?JSON.parse(g.value):null,error:g.error}));return{viewIndex:o.viewIndex,status:o.status,results:S,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage,aggregateResults:h}}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 y(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 X.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await X.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.MapFieldName(a.Name));r.Fields.forEach(a=>{n.push(A.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(A.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(A.MapFieldName(a.Name));t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&n.push(A.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return ge.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 y(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
459
461
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
460
462
  EntityName
461
463
  RelatedEntityName
@@ -513,7 +515,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
513
515
  handle
514
516
  errorMessage
515
517
  }
516
- }`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.subscribe(_e,{channelId:n}).subscribe({next:l(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:l(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return o?{Success:!!o.success,ResultCode:o.resultCode??void 0,Output:o.outputJSON!=null?JSON.parse(o.outputJSON):void 0,Handle:o.handle??void 0,ErrorMessage:o.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{a?.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=c`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
518
+ }`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.subscribe(ke,{channelId:n}).subscribe({next:l(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:l(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return o?{Success:!!o.success,ResultCode:o.resultCode??void 0,Output:o.outputJSON!=null?JSON.parse(o.outputJSON):void 0,Handle:o.handle??void 0,ErrorMessage:o.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{a?.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=c`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
517
519
  MergeRecords(request: $request) {
518
520
  Success
519
521
  OverallStatus
@@ -530,32 +532,32 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
530
532
  Message
531
533
  }
532
534
  }
533
- }`,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 y(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 G;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 G;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(m=>({FieldName:m.CodeName,Value:m.Value})),e.RegisterResultHistoryEntry(s);const i=x(e.EntityInfo),o=`${a}${i}`,g=e.Fields.filter(m=>!m.ReadOnly||m.IsPrimaryKey&&e.IsSaved),d=` ${o}(input: $input) {
534
- ${e.Fields.map(m=>N.MapFieldName(m.CodeName)).join(`
535
+ }`,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 y(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;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 U;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=T(e.EntityInfo),o=`${a}${i}`,m=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),u=` ${o}(input: $input) {
536
+ ${e.Fields.map(g=>A.MapFieldName(g.CodeName)).join(`
535
537
  `)}
536
- }`,h=c`mutation ${a}${i} ($input: ${o}Input!) {
537
- ${d}
538
+ }`,S=c`mutation ${a}${i} ($input: ${o}Input!) {
539
+ ${u}
538
540
  }
539
- `;for(let m=0;m<g.length;m++){const S=g[m];let p=e.Get(S.Name);if(p)switch(S.EntityFieldInfo.TSType){case b.Date:p=p.getTime();break;case b.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case b.Number:if(typeof p!="number"){const R=Number(p);isNaN(R)||(p=R)}break}p===null&&S.EntityFieldInfo.AllowsNull===!1&&(S.EntityFieldInfo.DefaultValue!==null?p=S.EntityFieldInfo.DefaultValue:S.FieldType===b.Number||S.FieldType===b.Boolean?p=0:p=""),n.input[N.MapFieldName(S.CodeName)]=p}const f=e.RestoreContext;if(f&&(n.input.RestoreContext___={SourceChangeID:f.SourceChangeID,Reason:f.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const m=[];e.Fields.forEach(S=>{let p=null;S.OldValue!==null&&S.OldValue!==void 0&&(S.EntityFieldInfo.TSType===b.Date?p=S.OldValue.getTime().toString():S.EntityFieldInfo.TSType===b.Boolean?p=S.OldValue===!0?"1":"0":typeof S.OldValue!="string"?p=S.OldValue.toString():p=S.OldValue),m.push({Key:N.MapFieldName(S.CodeName),Value:p})}),n.input.OldValues___=m}if(e.TransactionGroup){const m=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new J(e,s.Type==="create"?"Create":"Update",d,n,{mutationName:o,mutationInputTypes:m},(S,p)=>{s.EndedAt=new Date,p&&S?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(S)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const m=await this.ExecuteGQL(h,n);if(m&&m[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(m[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,y(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let f=0;f<t.KeyValuePairs.length;f++){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[f].FieldName.trim().toLowerCase()).EntityFieldInfo,S=t.GetValueByIndex(f),p=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${p}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===b.Number){if(isNaN(t.GetValueByIndex(f)))throw new Error(`Primary Key value ${S} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(S)}else n[m.CodeName]=S}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",g=x(e.EntityInfo),d=c`query Single${g}${o.length>0?"Full":""} (${i}) {
540
- ${g}(${a}) {
541
- ${e.Fields.filter(f=>!f.EntityFieldInfo.IsBinaryFieldType).map(f=>f.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?f.CodeName.replace("__mj_","_mj__"):f.CodeName).join(`
541
+ `;for(let g=0;g<m.length;g++){const p=m[g];let I=e.Get(p.Name);if(I)switch(p.EntityFieldInfo.TSType){case N.Date:I=I.getTime();break;case N.Boolean:typeof I!="boolean"&&(I=parseInt(I)!==0);break;case N.Number:if(typeof I!="number"){const R=Number(I);isNaN(R)||(I=R)}break}I===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?I=p.EntityFieldInfo.DefaultValue:p.FieldType===N.Number||p.FieldType===N.Boolean?I=0:I=""),n.input[A.MapFieldName(p.CodeName)]=I}const h=e.RestoreContext;if(h&&(n.input.RestoreContext___={SourceChangeID:h.SourceChangeID,Reason:h.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(p=>{let I=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===N.Date?I=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===N.Boolean?I=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?I=p.OldValue.toString():I=p.OldValue),g.push({Key:A.MapFieldName(p.CodeName),Value:I})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new J(e,s.Type==="create"?"Create":"Update",u,n,{mutationName:o,mutationInputTypes:g},(p,I)=>{s.EndedAt=new Date,I&&p?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(p)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(S,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,y(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let h=0;h<t.KeyValuePairs.length;h++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[h].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(h),I=g.GraphQLType;i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${I}!`,a.length>0&&(a+=", ");const R=g.CodeName.startsWith("__mj_")?g.CodeName.replace("__mj_","_mj__"):g.CodeName;if(a+=`${R}: $${g.CodeName}`,g.TSType===N.Number){if(isNaN(t.GetValueByIndex(h)))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):"",m=T(e.EntityInfo),u=c`query Single${m}${o.length>0?"Full":""} (${i}) {
542
+ ${m}(${a}) {
543
+ ${e.Fields.filter(h=>!h.EntityFieldInfo.IsBinaryFieldType).map(h=>h.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?h.CodeName.replace("__mj_","_mj__"):h.CodeName).join(`
542
544
  `)}
543
545
  ${o}
544
546
  }
545
547
  }
546
- `,h=await this.ExecuteGQL(d,n);return h&&h[g]?this.ConvertBackToMJFields(h[g]):null}catch(n){return y(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+=`
548
+ `,S=await this.ExecuteGQL(u,n);return S&&S[m]?this.ConvertBackToMJFields(S[m]):null}catch(n){return y(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],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+=`
547
549
  ${i} {
548
550
  ${a.Fields.map(o=>o.CodeName).join(`
549
551
  `)}
550
552
  }
551
- `}return r}async Delete(e,t,r){const s=new G;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(S=>({FieldName:S.CodeName,Value:S.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",g="";for(let S of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(R=>R.Name.trim().toLowerCase()===S.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,a.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,o.length>0&&(o+=", "),o+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,g.length>0&&(g+=`
552
- `),g+=`${p.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 h="Delete"+x(e.EntityInfo),f=c`${h}(${i}, options___: $options___) {
553
- ${g}
553
+ `}return r}async Delete(e,t,r){const s=new U;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="",m="";for(let p of e.PrimaryKey.KeyValuePairs){const I=e.Fields.find(E=>E.Name.trim().toLowerCase()===p.FieldName.trim().toLowerCase());n[I.CodeName]=I.Value,a.push({varName:I.CodeName,inputType:I.EntityFieldInfo.GraphQLType+"!"});const R=I.CodeName.startsWith("__mj_")?I.CodeName.replace("__mj_","_mj__"):I.CodeName;i.length>0&&(i+=", "),i+=`${R}: $${I.CodeName}`,o.length>0&&(o+=", "),o+=`$${I.CodeName}: ${I.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
554
+ `),m+=`${R}`}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 S="Delete"+T(e.EntityInfo),h=c`${S}(${i}, options___: $options___) {
555
+ ${m}
554
556
  }
555
- `,m=c`mutation ${h} (${o}, $options___: DeleteOptionsInput!) {
556
- ${f}
557
+ `,g=c`mutation ${S} (${o}, $options___: DeleteOptionsInput!) {
558
+ ${h}
557
559
  }
558
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new J(e,"Delete",f,n,{mutationName:h,mutationInputTypes:a},(S,p)=>{if(s.EndedAt=new Date,p&&S){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==S[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const S=await this.ExecuteGQL(m,n);if(S&&S[h]){const p=S[h];for(let R of e.PrimaryKey.KeyValuePairs){let E=p[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof E=="number"&&(E=E.toString()),D!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,y(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
560
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new J(e,"Delete",h,n,{mutationName:S,mutationInputTypes:a},(p,I)=>{if(s.EndedAt=new Date,I&&p){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==p[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(g,n);if(p&&p[S]){const I=p[S];for(let R of e.PrimaryKey.KeyValuePairs){let E=I[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof E=="number"&&(E=E.toString()),D!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,y(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
559
561
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
560
562
  DatasetID
561
563
  DatasetName
@@ -564,7 +566,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
564
566
  LatestUpdateDate
565
567
  Results
566
568
  }
567
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);P(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
569
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return f._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{f._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),f._datasetStatusTimer||(f._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),f._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){f._datasetStatusTimer=null;const e=f._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);P(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
568
570
  GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
569
571
  DatasetID
570
572
  DatasetName
@@ -582,7 +584,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
582
584
  LatestUpdateDate
583
585
  EntityUpdateDates
584
586
  }
585
- }`,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 Y(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=c`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
587
+ }`,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 ee(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=c`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
586
588
  GetRecordFavoriteStatus(params: $params) {
587
589
  Success
588
590
  IsFavorite
@@ -610,7 +612,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
610
612
  EntityName
611
613
  RecordName
612
614
  }
613
- }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new ye(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=c`query GetDataContextData ($DataContextID: String!) {
615
+ }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new Se(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=c`query GetDataContextData ($DataContextID: String!) {
614
616
  GetDataContextData(DataContextID: $DataContextID) {
615
617
  Success
616
618
  ErrorMessages
@@ -622,16 +624,44 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
622
624
  ErrorMessage
623
625
  Result
624
626
  }
625
- }`,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 y(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){const n=O(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const a=se(s);if(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 y("JWT_EXPIRED and refreshTokenIfNeeded is false"),a}else throw a;else throw y(JSON.stringify(n)),a}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const 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 B(e,{headers:a});for(const[o,g]of this._dynamicHeaders)i.setHeader(o,g);return i}userInfoString(){return this.infoString(new j(null,null))}userRoleInfoString(){return this.infoString(new me(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
627
+ }`,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 y(t),t}}static async ExecuteGQL(e,t,r=!0){return f.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return f.Instance.ExecuteGQLWithProgress(e,t,r,s)}async ExecuteGQLWithProgress(e,t,r,s=!0){if(!this._configData?.URL)throw new Error("GraphQLDataProvider is not configured with a URL.");const n=this._configData.URL,a=JSON.stringify({query:e,variables:t});return new Promise((i,o)=>{const m=new XMLHttpRequest;m.open("POST",n),m.setRequestHeader("Content-Type","application/json"),this._sessionId&&m.setRequestHeader("x-session-id",this._sessionId),this._configData?.Token&&m.setRequestHeader("authorization","Bearer "+this._configData.Token),this._configData?.MJAPIKey&&m.setRequestHeader("x-mj-api-key",this._configData.MJAPIKey),this._configData?.UserAPIKey&&m.setRequestHeader("x-api-key",this._configData.UserAPIKey);for(const[u,S]of this._dynamicHeaders)m.setRequestHeader(u,S);m.upload&&r&&(m.upload.onprogress=u=>{if(u.lengthComputable&&u.total>0){const S=Math.min(100,Math.round(u.loaded/u.total*100));r({loaded:u.loaded,total:u.total,percent:S})}}),m.onload=async()=>{if(m.status>=200&&m.status<300)try{const u=JSON.parse(m.responseText);if(u.errors&&u.errors.length>0){const S=u.errors[0];if(S?.extensions?.code?.toUpperCase()?.trim()==="JWT_EXPIRED"&&s){await this.RefreshToken(),i(await this.ExecuteGQLWithProgress(e,t,r,!1));return}o(new Error(S.message||"GraphQL Error"))}else i(u.data)}catch(u){o(u)}else o(new Error(`HTTP error ${m.status}: ${m.statusText}`))},m.onerror=()=>o(new Error("Network error during request")),m.onabort=()=>o(new Error("Request aborted")),m.send(a)})}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){const n=k(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const a=ae(s);if(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 y("JWT_EXPIRED and refreshTokenIfNeeded is false"),a}else throw a;else throw y(JSON.stringify(n)),a}}async RefreshToken(){const e=f.Instance&&f.Instance._configData===this._configData;if(e&&f.Instance._refreshPromise)return f.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(f.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&f.Instance&&(f.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)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,f.Instance&&f.Instance._configData===this._configData&&(f.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 f.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 B(e,{headers:a});for(const[o,m]of this._dynamicHeaders)i.setHeader(o,m);return i}userInfoString(){return this.infoString(new j(null,null))}userRoleInfoString(){return this.infoString(new pe(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
626
628
  `:s.startsWith("_")||(t+=s+`
627
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new re:this._localStorageProvider=new ge),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=we({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,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 T(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:l(a=>{r.next(a.data)},"next"),error:l(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(g){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",g),r.error(g)}}else r.error(a)},"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 T(o=>{r.activeSubscribers++;const g=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,g.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
629
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new ne:this._localStorageProvider=new he),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=$e({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(),this._taskGraphFrameStreams.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up frame stream for ${t}:`,r)}}),this._taskGraphFrameStreams.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 x(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:l(a=>{r.next(a.data)},"next"),error:l(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(m){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",m),r.error(m)}}else r.error(a)},"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 x(o=>{r.activeSubscribers++;const m=r.subject.subscribe(o);return()=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers>0&&u.activeSubscribers--,m.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
628
630
  statusUpdates(sessionId: $sessionId) {
629
631
  date
630
632
  message
631
633
  sessionId
632
634
  }
633
635
  }
634
- `,n=new ve,a=this.getOrCreateWSClient(),i=new Ce;return i.add(new T(o=>{const g=a.subscribe({query:s,variables:{sessionId:e}},{next:l(d=>{const h=this._pushStatusSubjects.get(e);h&&(h.lastEmissionAt=Date.now()),o.next(d.data.statusUpdates.message)},"next"),error:l(async d=>{const h=d;if(h?.extensions?.code==="JWT_EXPIRED"||h?.message?.includes("token has expired")||h?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(m){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",m),o.error(m)}}else o.error(d)},"error"),complete:l(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,g()}}).subscribe({next:l(o=>n.next(o),"next"),error:l(o=>{n.error(o),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 T(o=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers++;const d=n.subscribe(o);return()=>{const h=this._pushStatusSubjects.get(e);h&&h.activeSubscribers>0&&h.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(`
636
+ `,n=new Y,a=this.getOrCreateWSClient(),i=new Z;return i.add(new x(o=>{const m=a.subscribe({query:s,variables:{sessionId:e}},{next:l(u=>{const S=this._pushStatusSubjects.get(e);S&&(S.lastEmissionAt=Date.now()),o.next(u.data.statusUpdates.message)},"next"),error:l(async u=>{const S=u;if(S?.extensions?.code==="JWT_EXPIRED"||S?.message?.includes("token has expired")||S?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(g){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",g),o.error(g)}}else o.error(u)},"error"),complete:l(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,m()}}).subscribe({next:l(o=>n.next(o),"next"),error:l(o=>{n.error(o),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 x(o=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers++;const u=n.subscribe(o);return()=>{const S=this._pushStatusSubjects.get(e);S&&S.activeSubscribers>0&&S.activeSubscribers--,u.unsubscribe()}})}TaskGraphFrames(e){const t=l(o=>new x(m=>{o.activeSubscribers++;const u=o.subject.subscribe(m);return()=>{u.unsubscribe();const S=this._taskGraphFrameStreams.get(e);S&&(S.activeSubscribers--,S.activeSubscribers<=0&&(S.subscription.unsubscribe(),S.subject.complete(),this._taskGraphFrameStreams.delete(e)))}}),"attachTo"),r=this._taskGraphFrameStreams.get(e);if(r)return t(r);const s=c`subscription TaskGraphFrames($parentTaskId: ID!) {
637
+ taskGraphFrames(parentTaskId: $parentTaskId) {
638
+ kind
639
+ parentTaskId
640
+ taskId
641
+ taskName
642
+ status
643
+ errorMessage
644
+ assignedUserId
645
+ completedCount
646
+ totalCount
647
+ edgeId
648
+ dependsOnTaskId
649
+ verdict
650
+ conditionText
651
+ reason
652
+ claimEvent
653
+ claimedBy
654
+ claimExpiresAt
655
+ passNumber
656
+ eligibleCount
657
+ heldCount
658
+ claimedCount
659
+ instanceInFlightCount
660
+ progressMessage
661
+ progressPercent
662
+ date
663
+ }
664
+ }`,n=new Y,a=new Z;a.add(this.subscribe(s,{parentTaskId:e}).subscribe({next:l(o=>{o?.taskGraphFrames&&n.next(o.taskGraphFrames)},"next"),error:l(o=>{n.error(o),this._taskGraphFrameStreams.delete(e)},"error"),complete:l(()=>{n.complete(),this._taskGraphFrameStreams.delete(e)},"complete")}));const i={subject:n,subscription:a,activeSubscribers:0};return this._taskGraphFrameStreams.set(e,i),t(i)}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
635
665
  subscription ClientToolRequest($sessionID: String!) {
636
666
  ClientToolRequest(sessionID: $sessionID) {
637
667
  AgentRunID
@@ -653,7 +683,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
653
683
  OriginSessionID
654
684
  RecordData
655
685
  }
656
- }`,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){I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};z.Instance.RaiseEvent({event:H.ComponentEvent,eventCode:Se.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!) {
686
+ }`,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){f.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}f.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}};H.Instance.RaiseEvent({event:z.ComponentEvent,eventCode:Ie.BaseEventCode,args:n,component:this})},"next"),error:l(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:l(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
657
687
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
658
688
  Success
659
689
  ChildEntityName
@@ -665,14 +695,69 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
665
695
  ChildEntityNames
666
696
  ErrorMessage
667
697
  }
668
- }`;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 y(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function ke(u){const e=new I;return he(e),await e.Config(u),await e.preValidateAndRefresh(),z.Instance.RaiseEvent({event:H.LoggedIn,eventCode:null,component:this,args:null}),await Ie.Instance.Startup(),e}l(ke,"setupGraphQLClient");class qe{static{l(this,"SyncRolesAndUsersResult")}}class Ke{static{l(this,"RoleInput")}}class Be{static{l(this,"UserInput")}}class je{static{l(this,"RolesAndUsersInput")}}var ne=(u=>(u.Create="Create",u.Update="Update",u.CreateOrUpdate="CreateOrUpdate",u.Delete="Delete",u.DeleteWithFilter="DeleteWithFilter",u))(ne||{});class Je{static{l(this,"ActionItemInput")}}class We{static{l(this,"SyncDataResult")}constructor(){this.Results=[]}}class ze{static{l(this,"ActionItemOutput")}}class He{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 B(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return fe(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
698
+ }`;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 y(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function qe(d){const e=new f;return Ee(e),await e.Config(d),await e.preValidateAndRefresh(),H.Instance.RaiseEvent({event:z.LoggedIn,eventCode:null,component:this,args:null}),await Re.Instance.Startup(),e}l(qe,"setupGraphQLClient");class Ke{static{l(this,"SyncRolesAndUsersResult")}}class Be{static{l(this,"RoleInput")}}class je{static{l(this,"UserInput")}}class Je{static{l(this,"RolesAndUsersInput")}}var oe=(d=>(d.Create="Create",d.Update="Update",d.CreateOrUpdate="CreateOrUpdate",d.Delete="Delete",d.DeleteWithFilter="DeleteWithFilter",d))(oe||{});class We{static{l(this,"ActionItemInput")}}class He{static{l(this,"SyncDataResult")}constructor(){this.Results=[]}}class ze{static{l(this,"ActionItemOutput")}}const ie=`Success
699
+ ErrorMessage
700
+ Query {
701
+ ID
702
+ Name
703
+ Description
704
+ CategoryID
705
+ Category
706
+ SQL
707
+ Status
708
+ QualityRank
709
+ EmbeddingVector
710
+ EmbeddingModelID
711
+ EmbeddingModel
712
+ TechnicalDescription
713
+ Reusable
714
+ }
715
+ Fields {
716
+ ID
717
+ QueryID
718
+ Name
719
+ Description
720
+ Sequence
721
+ SQLBaseType
722
+ SQLFullType
723
+ SourceEntityID
724
+ SourceEntity
725
+ SourceFieldName
726
+ IsComputed
727
+ ComputationDescription
728
+ IsSummary
729
+ SummaryDescription
730
+ }
731
+ Parameters {
732
+ ID
733
+ QueryID
734
+ Name
735
+ Description
736
+ Type
737
+ IsRequired
738
+ DefaultValue
739
+ SampleValue
740
+ ValidationFilters
741
+ }
742
+ Entities {
743
+ ID
744
+ QueryID
745
+ EntityID
746
+ Entity
747
+ }
748
+ Permissions {
749
+ ID
750
+ QueryID
751
+ RoleID
752
+ Role
753
+ }`;class Xe{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 B(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return De(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
669
754
  GetData(input: $input) {
670
755
  Success
671
756
  ErrorMessages
672
757
  Queries
673
758
  Results
674
759
  }
675
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?v(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]+"."),Re()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;y(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
760
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?v(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]+"."),ve()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;y(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
676
761
  GetAllEntities {
677
762
  Success
678
763
  ErrorMessage
@@ -815,125 +900,15 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
815
900
  ErrorMessage
816
901
  AppliedParameters
817
902
  }
818
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?v(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return y(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQueryExtended($input: CreateQuerySystemUserInput!) {
903
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?v(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return y(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const t=`mutation CreateQueryExtended($input: CreateQuerySystemUserInput!) {
819
904
  CreateQueryExtended(input: $input) {
820
- Success
821
- ErrorMessage
822
- Query {
823
- ID
824
- Name
825
- Description
826
- CategoryID
827
- Category
828
- SQL
829
- Status
830
- QualityRank
831
- EmbeddingVector
832
- EmbeddingModelID
833
- EmbeddingModel
834
- TechnicalDescription
835
- Reusable
836
- MJQueryFields_QueryIDArray {
837
- ID
838
- QueryID
839
- Name
840
- Description
841
- Sequence
842
- SQLBaseType
843
- SQLFullType
844
- SourceEntityID
845
- SourceEntity
846
- SourceFieldName
847
- IsComputed
848
- ComputationDescription
849
- IsSummary
850
- SummaryDescription
851
- }
852
- MJQueryParameters_QueryIDArray {
853
- ID
854
- QueryID
855
- Name
856
- Description
857
- Type
858
- IsRequired
859
- DefaultValue
860
- SampleValue
861
- ValidationFilters
862
- }
863
- MJQueryEntities_QueryIDArray {
864
- ID
865
- QueryID
866
- EntityID
867
- Entity
868
- }
869
- MJQueryPermissions_QueryIDArray {
870
- ID
871
- QueryID
872
- RoleID
873
- Role
874
- }
875
- }
905
+ ${ie}
876
906
  }
877
- }`,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return y(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQueryExtended($input: UpdateQuerySystemUserInput!) {
907
+ }`,r=await this.Client.request(t,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return y(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const t=`mutation UpdateQueryExtended($input: UpdateQuerySystemUserInput!) {
878
908
  UpdateQueryExtended(input: $input) {
879
- Success
880
- ErrorMessage
881
- Query {
882
- ID
883
- Name
884
- Description
885
- CategoryID
886
- Category
887
- SQL
888
- Status
889
- QualityRank
890
- EmbeddingVector
891
- EmbeddingModelID
892
- EmbeddingModel
893
- TechnicalDescription
894
- Reusable
895
- MJQueryFields_QueryIDArray {
896
- ID
897
- QueryID
898
- Name
899
- Description
900
- Sequence
901
- SQLBaseType
902
- SQLFullType
903
- SourceEntityID
904
- SourceEntity
905
- SourceFieldName
906
- IsComputed
907
- ComputationDescription
908
- IsSummary
909
- SummaryDescription
910
- }
911
- MJQueryParameters_QueryIDArray {
912
- ID
913
- QueryID
914
- Name
915
- Description
916
- Type
917
- IsRequired
918
- DefaultValue
919
- SampleValue
920
- ValidationFilters
921
- }
922
- MJQueryEntities_QueryIDArray {
923
- ID
924
- QueryID
925
- EntityID
926
- Entity
927
- }
928
- MJQueryPermissions_QueryIDArray {
929
- ID
930
- QueryID
931
- RoleID
932
- Role
933
- }
934
- }
909
+ ${ie}
935
910
  }
936
- }`,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return y(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return y("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQueryExtended($ID: String!, $options: DeleteOptionsInput) {
911
+ }`,r=await this.Client.request(t,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return y(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return y("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQueryExtended($ID: String!, $options: DeleteOptionsInput) {
937
912
  DeleteQueryExtended(ID: $ID, options: $options) {
938
913
  Success
939
914
  ErrorMessage
@@ -1178,7 +1153,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1178
1153
  ErrorMessage
1179
1154
  }
1180
1155
  }
1181
- `,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 y(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class Xe{static{l(this,"GetDataOutput")}}class Ye{static{l(this,"SimpleRemoteEntityOutput")}}class Ze{static{l(this,"SimpleRemoteEntity")}}class et{static{l(this,"SimpleRemoteEntityField")}}class tt{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),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=c`
1156
+ `,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 y(`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 Ze{static{l(this,"SimpleRemoteEntityOutput")}}class et{static{l(this,"SimpleRemoteEntity")}}class tt{static{l(this,"SimpleRemoteEntityField")}}class rt{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),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=c`
1182
1157
  mutation RunAction($input: RunActionInput!) {
1183
1158
  RunAction(input: $input) {
1184
1159
  Success
@@ -1195,62 +1170,62 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1195
1170
  ResultData
1196
1171
  }
1197
1172
  }
1198
- `;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){y(`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 y(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class rt{static{l(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1173
+ `;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){y(`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 y(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class st{static{l(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1199
1174
  query PreviewListDelta($input: ComputeDeltaInput!) {
1200
1175
  PreviewListDelta(input: $input) {
1201
1176
  ...ListDeltaFields
1202
1177
  }
1203
1178
  }
1204
- ${ae}
1205
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:K(e.Source),Mode:e.Mode}});return oe(r?.PreviewListDelta)}async ApplyListDelta(e){const t=c`
1179
+ ${ce}
1180
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:K(e.Source),Mode:e.Mode}});return ue(r?.PreviewListDelta)}async ApplyListDelta(e){const t=c`
1206
1181
  mutation ApplyListDelta($input: ApplyDeltaInput!) {
1207
1182
  ApplyListDelta(input: $input) {
1208
1183
  ...ApplyResultFields
1209
1184
  }
1210
1185
  }
1211
- ${Q}
1212
- `,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 U(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=c`
1186
+ ${G}
1187
+ `,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 Q(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=c`
1213
1188
  mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
1214
1189
  MaterializeListFromView(viewId: $viewId, options: $options) {
1215
1190
  ...ApplyResultFields
1216
1191
  }
1217
1192
  }
1218
- ${Q}
1219
- `,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 U(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=c`
1193
+ ${G}
1194
+ `,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 Q(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=c`
1220
1195
  mutation AddViewResultsToList($viewId: String!, $listId: String!) {
1221
1196
  AddViewResultsToList(viewId: $viewId, listId: $listId) {
1222
1197
  ...ApplyResultFields
1223
1198
  }
1224
1199
  }
1225
- ${Q}
1226
- `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return U(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1200
+ ${G}
1201
+ `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return Q(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1227
1202
  mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
1228
1203
  RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
1229
1204
  ...ApplyResultFields
1230
1205
  }
1231
1206
  }
1232
- ${Q}
1233
- `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return U(r?.RefreshListFromSource)}async ComposeLists(e){const t=c`
1207
+ ${G}
1208
+ `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return Q(r?.RefreshListFromSource)}async ComposeLists(e){const t=c`
1234
1209
  mutation ComposeLists($input: ComposeListsInput!) {
1235
1210
  ComposeLists(input: $input) {
1236
1211
  ...ListDeltaFields
1237
1212
  }
1238
1213
  }
1239
- ${ae}
1240
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(K),Target:e.Target?K(e.Target):null}});return oe(r?.ComposeLists)}async Share(e){const t=c`
1214
+ ${ce}
1215
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(K),Target:e.Target?K(e.Target):null}});return ue(r?.ComposeLists)}async Share(e){const t=c`
1241
1216
  mutation ShareList($input: ShareListInput!) {
1242
1217
  ShareList(input: $input) {
1243
1218
  ...ShareResultFields
1244
1219
  }
1245
1220
  }
1246
- ${k}
1247
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:st(e.Target),PermissionLevel:e.PermissionLevel}});return q(r?.ShareList)}async Unshare(e){const t=c`
1221
+ ${O}
1222
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:nt(e.Target),PermissionLevel:e.PermissionLevel}});return q(r?.ShareList)}async Unshare(e){const t=c`
1248
1223
  mutation UnshareList($permissionId: String!) {
1249
1224
  UnshareList(permissionId: $permissionId) {
1250
1225
  ...ShareResultFields
1251
1226
  }
1252
1227
  }
1253
- ${k}
1228
+ ${O}
1254
1229
  `,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return q(r?.UnshareList)}async Invite(e){const t=c`
1255
1230
  mutation InviteToList($input: InviteToListInput!) {
1256
1231
  InviteToList(input: $input) {
@@ -1278,7 +1253,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1278
1253
  ...ShareResultFields
1279
1254
  }
1280
1255
  }
1281
- ${k}
1256
+ ${O}
1282
1257
  `,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return q(r?.RevokeListInvitation)}async GetSharesForList(e){const t=c`
1283
1258
  query ListSharesForList($listId: String!) {
1284
1259
  ListSharesForList(listId: $listId) {
@@ -1295,7 +1270,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1295
1270
  CreatedAt
1296
1271
  }
1297
1272
  }
1298
- `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(nt)}async ListsSharedWithMe(){const e=c`
1273
+ `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(at)}async ListsSharedWithMe(){const e=c`
1299
1274
  query ListsSharedWithMe {
1300
1275
  ListsSharedWithMe {
1301
1276
  ListID
@@ -1305,7 +1280,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1305
1280
  SharedAt
1306
1281
  }
1307
1282
  }
1308
- `;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 ae=c`
1283
+ `;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 ce=c`
1309
1284
  fragment ListDeltaFields on ListDeltaType {
1310
1285
  TargetListId
1311
1286
  EntityName
@@ -1326,7 +1301,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1326
1301
  }
1327
1302
  DeltaToken
1328
1303
  }
1329
- `,Q=c`
1304
+ `,G=c`
1330
1305
  fragment ApplyResultFields on ApplyListResultType {
1331
1306
  Success
1332
1307
  ResultCode
@@ -1338,14 +1313,14 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1338
1313
  FailedCount
1339
1314
  Errors
1340
1315
  }
1341
- `,k=c`
1316
+ `,O=c`
1342
1317
  fragment ShareResultFields on ShareResultType {
1343
1318
  Success
1344
1319
  ResultCode
1345
1320
  Message
1346
1321
  PermissionID
1347
1322
  }
1348
- `;function st(u){return u.kind==="user"?{Kind:"user",UserID:u.userId}:{Kind:"role",RoleID:u.roleId}}l(st,"serializeShareTarget");function q(u){if(!u||typeof u!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=u;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}l(q,"parseShareResult");function nt(u){const e=u,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(nt,"parseShareSummary");function K(u){switch(u.kind){case"list":return{Kind:"list",ListID:u.listId};case"view":return{Kind:"view",ViewID:u.viewId};case"adhoc":return{Kind:"adhoc",EntityName:u.entityName,ExtraFilter:u.extraFilter}}}l(K,"serializeListSource");function oe(u){if(!u||typeof u!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=u;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(at),DeltaToken:e.DeltaToken}}l(oe,"parseListDelta");function at(u){let e;if(u.DetailsJSON)try{e=JSON.parse(u.DetailsJSON)}catch(t){y(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:u.Code,Message:u.Message,Details:e}}l(at,"parseWarning");function U(u){if(!u||typeof u!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=u;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(U,"parseApplyResult");class ot{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=c`
1323
+ `;function nt(d){return d.kind==="user"?{Kind:"user",UserID:d.userId}:{Kind:"role",RoleID:d.roleId}}l(nt,"serializeShareTarget");function q(d){if(!d||typeof d!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=d;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}l(q,"parseShareResult");function at(d){const e=d,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(at,"parseShareSummary");function K(d){switch(d.kind){case"list":return{Kind:"list",ListID:d.listId};case"view":return{Kind:"view",ViewID:d.viewId};case"adhoc":return{Kind:"adhoc",EntityName:d.entityName,ExtraFilter:d.extraFilter}}}l(K,"serializeListSource");function ue(d){if(!d||typeof d!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=d;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(ot),DeltaToken:e.DeltaToken}}l(ue,"parseListDelta");function ot(d){let e;if(d.DetailsJSON)try{e=JSON.parse(d.DetailsJSON)}catch(t){y(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:d.Code,Message:d.Message,Details:e}}l(ot,"parseWarning");function Q(d){if(!d||typeof d!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=d;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(Q,"parseApplyResult");class it{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=c`
1349
1324
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1350
1325
  CreateAPIKey(input: $input) {
1351
1326
  Success
@@ -1361,7 +1336,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1361
1336
  Error
1362
1337
  }
1363
1338
  }
1364
- `,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 y(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class it{static{l(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1339
+ `,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 y(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ct{static{l(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1365
1340
  mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1366
1341
  RunClusterAnalysis(input: $input) {
1367
1342
  Success
@@ -1377,7 +1352,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1377
1352
  AnalysisID
1378
1353
  }
1379
1354
  }
1380
- `,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 y("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=v(e.ClustersJSON)??[],s=v(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=v(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 ct{static{l(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
1355
+ `,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 y("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=v(e.ClustersJSON)??[],s=v(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=v(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 ut{static{l(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
1381
1356
  mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1382
1357
  MintLiveKitClientToken(input: $input) {
1383
1358
  Success
@@ -1442,7 +1417,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1442
1417
  RecordingFileID
1443
1418
  }
1444
1419
  }
1445
- `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return y(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class ut{static{l(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1420
+ `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return y(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class lt{static{l(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1446
1421
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1447
1422
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1448
1423
  Success
@@ -1452,7 +1427,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1452
1427
  NodesJSON
1453
1428
  }
1454
1429
  }
1455
- `,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 y("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=v(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 lt{static{l(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await w.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 w.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=c`
1430
+ `,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 y("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=v(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 dt{static{l(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await w.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 w.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=c`
1456
1431
  query IsTestRunning($testId: String!) {
1457
1432
  IsTestRunning(testId: $testId)
1458
1433
  }
@@ -1510,7 +1485,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1510
1485
  result
1511
1486
  }
1512
1487
  }
1513
- `}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?v(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v(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 y(`${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 dt{static{l(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1488
+ `}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?v(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v(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 y(`${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 yt{static{l(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1514
1489
  query GetRegistryComponent(
1515
1490
  $registryName: String!,
1516
1491
  $namespace: String!,
@@ -1594,7 +1569,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1594
1569
  error
1595
1570
  }
1596
1571
  }
1597
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return y(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class yt{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(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=c`
1572
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return y(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class mt{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(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=c`
1598
1573
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1599
1574
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1600
1575
  Success
@@ -1610,7 +1585,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1610
1585
  }
1611
1586
  }
1612
1587
  }
1613
- `,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 y(`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 mt{static{l(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1588
+ `,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 y(`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 gt{static{l(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1614
1589
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1615
1590
  ListStorageObjects(input: $input) {
1616
1591
  objects {
@@ -1638,7 +1613,24 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1638
1613
  ProviderKey
1639
1614
  }
1640
1615
  }
1641
- `,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 y(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=c`
1616
+ `,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");const i=a.CreatePreAuthUploadUrl;return{success:!!i.UploadUrl,uploadUrl:i.UploadUrl||"",providerKey:i.ProviderKey}}catch(s){const n=s;throw y(`Error creating pre-auth upload URL: ${n}`),n}}async UploadFile(e){try{const t=c`
1617
+ mutation UploadStorageFile($input: UploadStorageFileInput!) {
1618
+ UploadStorageFile(input: $input) {
1619
+ Success
1620
+ FileID
1621
+ ErrorMessage
1622
+ File {
1623
+ ID
1624
+ Name
1625
+ Description
1626
+ ContentType
1627
+ Status
1628
+ ProviderID
1629
+ CategoryID
1630
+ }
1631
+ }
1632
+ }
1633
+ `,r=await this._dataProvider.ExecuteGQL(t,{input:e});if(!r?.UploadStorageFile)throw new Error("Invalid response from UploadStorageFile mutation");return r.UploadStorageFile}catch(t){const r=t;throw y(`Error uploading file via MJ Storage: ${r}`),r}}async CreatePreAuthDownloadUrl(e,t){try{const r=c`
1642
1634
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1643
1635
  CreatePreAuthDownloadUrl(input: $input)
1644
1636
  }
@@ -1694,7 +1686,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1694
1686
  failedAccounts
1695
1687
  }
1696
1688
  }
1697
- `,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(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:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return y(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class gt{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 c`
1689
+ `,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(m=>({path:m.path,name:m.name,size:m.size,contentType:m.contentType,lastModified:new Date(m.lastModified),relevance:m.relevance,excerpt:m.excerpt,matchInFilename:m.matchInFilename,objectId:m.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return y(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class St{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 c`
1698
1690
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1699
1691
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1700
1692
  Success
@@ -1800,7 +1792,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1800
1792
  IsPersonal
1801
1793
  }
1802
1794
  }
1803
- `;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 y(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new T(t=>{const r=c`
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 y(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new x(t=>{const r=c`
1804
1796
  mutation StreamScopedSearch(
1805
1797
  $query: String!,
1806
1798
  $maxResults: Float,
@@ -1833,7 +1825,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1833
1825
  ElapsedMs
1834
1826
  ErrorMessage
1835
1827
  }
1836
- }`;n=this._dataProvider.subscribe(o,{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(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 y(`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 St{static{l(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1828
+ }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:l(m=>{const u=m?.SearchStreamEvents;u&&(t.next(u),u.Phase==="final"?(t.complete(),n?.unsubscribe()):u.Phase==="error"&&(t.error(new Error(u.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:l(m=>t.error(m),"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 y(`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 pt{static{l(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1837
1829
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1838
1830
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1839
1831
  Success
@@ -1984,7 +1976,7 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
1984
1976
  PipelineSteps { Name Status DurationMs Message }
1985
1977
  GitCommitSuccess APIRestarted
1986
1978
  }
1987
- }`,g={Connectors:e.map(h=>({CompanyIntegrationID:h.CompanyIntegrationID,SourceObjects:h.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},d=(await this._dataProvider.ExecuteGQL(o,{input:g,platform:n,skipGitCommit:a,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(h=>h.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=c`mutation IntegrationApplyAll(
1979
+ }`,m={Connectors:e.map(S=>({CompanyIntegrationID:S.CompanyIntegrationID,SourceObjects:S.SourceObjects.map(h=>({SourceObjectID:h.SourceObjectID??null,SourceObjectName:h.SourceObjectName??null,Fields:h.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},u=(await this._dataProvider.ExecuteGQL(o,{input:m,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return u?{Success:u.Success,Message:u.Message,Steps:u.PipelineSteps,GitCommitSuccess:u.GitCommitSuccess,APIRestarted:u.APIRestarted,EntityMapsCreated:u.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:u.ConnectorResults?.[0]?.SyncRunID,Warnings:u.ConnectorResults?.flatMap(S=>S.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=c`mutation IntegrationApplyAll(
1988
1980
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1989
1981
  ) {
1990
1982
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -2026,5 +2018,5 @@ ${e.stackFrames}`:this.stack}}function se(u){return u instanceof V?u:new V(O(u))
2026
2018
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
2027
2019
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
2028
2020
  }
2029
- }`;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 y(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Je as ActionItemInput,ze as ActionItemOutput,re as BrowserIndexedDBStorageProvider,ee as BrowserStorageProviderBase,M as FieldMapper,w as FireAndForgetHelper,Xe as GetDataOutput,Z as GraphQLAIClient,tt as GraphQLActionClient,ut as GraphQLClassifyClient,it as GraphQLClusterClient,dt as GraphQLComponentRegistryClient,I as GraphQLDataProvider,ot as GraphQLEncryptionClient,mt as GraphQLFileStorageClient,St as GraphQLIntegrationClient,rt as GraphQLListsClient,ct as GraphQLLiveKitClient,Oe as GraphQLProviderConfigData,gt as GraphQLSearchClient,He as GraphQLSystemUserClient,lt as GraphQLTestingClient,Y as GraphQLTransactionGroup,yt as GraphQLVersionHistoryClient,F as PACKAGE_VERSION,Ke as RoleInput,je as RolesAndUsersInput,V as SafeGraphQLError,O as SanitizeGraphQLError,Ze as SimpleRemoteEntity,et as SimpleRemoteEntityField,Ye as SimpleRemoteEntityOutput,ne as SyncDataAction,We as SyncDataResult,qe as SyncRolesAndUsersResult,se as ToSafeGraphQLError,Be as UserInput,Pt as gql,ke as setupGraphQLClient};
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 y(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{We as ActionItemInput,ze as ActionItemOutput,ne as BrowserIndexedDBStorageProvider,re as BrowserStorageProviderBase,M as FieldMapper,w as FireAndForgetHelper,Ye as GetDataOutput,te as GraphQLAIClient,rt as GraphQLActionClient,lt as GraphQLClassifyClient,ct as GraphQLClusterClient,yt as GraphQLComponentRegistryClient,f as GraphQLDataProvider,it as GraphQLEncryptionClient,gt as GraphQLFileStorageClient,pt as GraphQLIntegrationClient,st as GraphQLListsClient,ut as GraphQLLiveKitClient,Oe as GraphQLProviderConfigData,St as GraphQLSearchClient,Xe as GraphQLSystemUserClient,dt as GraphQLTestingClient,ee as GraphQLTransactionGroup,mt as GraphQLVersionHistoryClient,F as PACKAGE_VERSION,Be as RoleInput,Je as RolesAndUsersInput,_ as SafeGraphQLError,k as SanitizeGraphQLError,et as SimpleRemoteEntity,tt as SimpleRemoteEntityField,Ze as SimpleRemoteEntityOutput,oe as SyncDataAction,He as SyncDataResult,Ke as SyncRolesAndUsersResult,ae as ToSafeGraphQLError,je as UserInput,bt as gql,qe as setupGraphQLClient};
2030
2022
  //# sourceMappingURL=index.mjs.map