@memberjunction/graphql-dataprovider 6.2.0-edge.2 → 6.2.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 u=(l,e)=>Ie(l,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as J}from"graphql-request";import{gql as Ot}from"graphql-request";import{TransactionGroupBase as fe,TransactionResult as Ee,BaseEntityResult as x,LogError as y,LogStatus as P,LogErrorEx as M,ProviderBase as Re,UserInfo as W,getGraphQLTypeNameBase as L,ProviderType as De,RecordDependency as ve,KeyValuePair as Ce,CompositeKey as H,ReadableFieldsTransportKey as _,EntityFieldTSType as A,TransactionItem as z,UserRoleInfo as we,InMemoryLocalStorageProvider as $e,BaseEntity as Pe,ProviderConfigDataBase as Me,SetProvider as X,StartupManager as be,IsPlatformSQL as Ne,IsVerboseLoggingEnabled as Ae}from"@memberjunction/core";import{SafeJSONParse as v,CleanAndParseJSON as Te,UUIDsEqual as Y,GetGlobalObjectStore as Z,DeserializeValidationErrors as ee,MJGlobal as te,MJEventType as re}from"@memberjunction/global";import{ViewInfo as se}from"@memberjunction/core-entities";import{BehaviorSubject as xe,Subject as V,Observable as T,Subscription as ne}from"rxjs";import{createClient as Le}from"graphql-ws";import{v4 as Fe}from"uuid";import{openDB as Ge}from"@tempfix/idb";class N{static{u(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(N.DB_PREFIX)?N.GQL_PREFIX+e.substring(N.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(N.GQL_PREFIX)?N.DB_PREFIX+e.substring(N.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 ae extends fe{static{u(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
1
+ var Ee=Object.defineProperty;var l=(d,e)=>Ee(d,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as H}from"graphql-request";import{gql as Ht}from"graphql-request";import{TransactionGroupBase as Re,TransactionResult as De,BaseEntityResult as L,LogError as u,LogStatus as P,LogErrorEx as M,ProviderBase as ve,EntityRecordNameCache as Ce,UserInfo as z,getGraphQLTypeNameBase as F,ProviderType as we,RecordDependency as $e,KeyValuePair as Pe,CompositeKey as X,ReadableFieldsTransportKey as V,EntityFieldTSType as A,TransactionItem as Y,UserRoleInfo as Me,InMemoryLocalStorageProvider as Ne,BaseEntity as be,ProviderConfigDataBase as Ae,SetProvider as Z,StartupManager as xe,IsPlatformSQL as Te,IsVerboseLoggingEnabled as Le}from"@memberjunction/core";import{SafeJSONParse as v,CleanAndParseJSON as Fe,UUIDsEqual as ee,GetGlobalObjectStore as te,DeserializeValidationErrors as re,MJGlobal as se,MJEventType as ne}from"@memberjunction/global";import{ViewInfo as ae}from"@memberjunction/core-entities";import{BehaviorSubject as Ge,Subject as O,Observable as T,Subscription as oe,map as Qe,filter as Ue}from"rxjs";import{createClient as _e}from"graphql-ws";import{v4 as Ve}from"uuid";import{openDB as Oe}from"@tempfix/idb";class b{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(b.DB_PREFIX)?b.GQL_PREFIX+e.substring(b.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(b.GQL_PREFIX)?b.DB_PREFIX+e.substring(b.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 ie extends Re{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 u=(l,e)=>Ie(l,"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 m=n.ResultsJSON[o],d=v(m),g=this.PendingTransactions[o];a||this.recordServerFailure(g.BaseEntity,n.ErrorMessages?.[o]),i.push(new Ee(g,d,a&&d!==null))}return i}else throw new Error("Failed to execute transaction group")}recordServerFailure(e,t){const r=v(t??"");if(!r||r.Success!==!1)return;const s=r.Message?.trim();if(!s&&(r.Errors?.length??0)===0)return;const n=new x;n.Success=!1,n.Type=r.Type??(e.IsSaved?"update":"create"),n.Message=s??null,n.Errors=r.Errors??[],n.StartedAt=new Date,n.EndedAt=new Date,e.RegisterResultHistoryEntry(n)}}const Ue=180*1e3,Qe=6;class w{static{u(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??Ue,n=e.maxStallReconciles??Qe;let a,i=!1,o=0;const{promise:m,resolve:d,reject:g}=w.createCompletionPromise(),f=u(p=>{i||(i=!0,h.clear(),p())},"finish"),S=u(p=>f(()=>d(p)),"settleResolve"),E=u(p=>f(()=>g(p)),"settleReject"),D=u(async()=>{if(i)return;if(!e.onStall){E(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let p;try{P(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),p=await e.onStall()}catch(R){E(R);return}i||(p==="continue"?++o>n?E(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.`)):h.reset():"resolve"in p?(P(`[FireAndForget:${t}] Reconciliation recovered a completed run`),S(p.resolve)):E(p.reject))},"onStall"),h=w.createIdleTimer(s,()=>{D()});try{h.reset(),a=w.subscribeToPubSub(e,{onActivity:u(()=>{o=0,h.reset()},"onActivity"),onCompletion:u(R=>S(R),"onCompletion"),onStreamEnd:u(()=>{D()},"onStreamEnd")});const p=await w.executeMutation(e);if(!e.validateAck(p)){h.clear();const R=p?.errorMessage??"Server rejected the request";return y(`[FireAndForget:${t}] Server rejected: ${R}`),e.createErrorResult(R)}return P(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await m}catch(p){throw y(`[FireAndForget:${t}] Error: ${p.message}`),p}finally{h.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:u(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:u(()=>{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:u(n=>{let a;try{a=JSON.parse(n)}catch(i){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,i),t.onActivity();return}(!e.isRelevantMessage||e.isRelevantMessage(a))&&t.onActivity();try{e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(P(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(i){console.error(`[FireAndForget:${s}] Failed to route PubSub message:`,i)}},"next"),error:u(()=>t.onStreamEnd(),"error"),complete:u(()=>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 oe{static{u(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 g=n.ResultsJSON[o],y=v(g),m=this.PendingTransactions[o];a||this.recordServerFailure(m.BaseEntity,n.ErrorMessages?.[o]),i.push(new De(m,y,a&&y!==null))}return i}else throw new Error("Failed to execute transaction group")}recordServerFailure(e,t){const r=v(t??"");if(!r||r.Success!==!1)return;const s=r.Message?.trim();if(!s&&(r.Errors?.length??0)===0)return;const n=new L;n.Success=!1,n.Type=r.Type??(e.IsSaved?"update":"create"),n.Message=s??null,n.Errors=r.Errors??[],n.StartedAt=new Date,n.EndedAt=new Date,e.RegisterResultHistoryEntry(n)}}const ke=180*1e3,qe=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??ke,n=e.maxStallReconciles??qe;let a,i=!1,o=0;const{promise:g,resolve:y,reject:m}=w.createCompletionPromise(),f=l(p=>{i||(i=!0,h.clear(),p())},"finish"),S=l(p=>f(()=>y(p)),"settleResolve"),E=l(p=>f(()=>m(p)),"settleReject"),D=l(async()=>{if(i)return;if(!e.onStall){E(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let p;try{P(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),p=await e.onStall()}catch(R){E(R);return}i||(p==="continue"?++o>n?E(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.`)):h.reset():"resolve"in p?(P(`[FireAndForget:${t}] Reconciliation recovered a completed run`),S(p.resolve)):E(p.reject))},"onStall"),h=w.createIdleTimer(s,()=>{D()});try{h.reset(),a=w.subscribeToPubSub(e,{onActivity:l(()=>{o=0,h.reset()},"onActivity"),onCompletion:l(R=>S(R),"onCompletion"),onStreamEnd:l(()=>{D()},"onStreamEnd")});const p=await w.executeMutation(e);if(!e.validateAck(p)){h.clear();const R=p?.errorMessage??"Server rejected the request";return u(`[FireAndForget:${t}] Server rejected: ${R}`),e.createErrorResult(R)}return P(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await g}catch(p){throw u(`[FireAndForget:${t}] Error: ${p.message}`),p}finally{h.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=>{let a;try{a=JSON.parse(n)}catch(i){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,i),t.onActivity();return}(!e.isRelevantMessage||e.isRelevantMessage(a))&&t.onActivity();try{e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(P(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(i){console.error(`[FireAndForget:${s}] Failed to route PubSub message:`,i)}},"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.`):(u(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class ce{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 u=(l,e)=>Ie(l,"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=Te(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 RunDecision(e){try{const t=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=Fe(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return u(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunDecision(e){try{const t=c`
69
69
  mutation RunDecision(
70
70
  $state: String!,
71
71
  $questions: String!,
@@ -89,7 +89,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
89
89
  executionTimeMs
90
90
  }
91
91
  }
92
- `,r=this.prepareDecisionVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processDecisionResult(s)}catch(t){return this.handleDecisionError(t)}}prepareDecisionVariables(e){const t={state:typeof e.State=="string"?e.State:JSON.stringify(e.State),questions:JSON.stringify(e.Questions)};return e.PromptID!==void 0&&(t.promptId=e.PromptID),e.PromptName!==void 0&&(t.promptName=e.PromptName),e.TimeoutMS!==void 0&&(t.timeoutMS=e.TimeoutMS),t}processDecisionResult(e){const t=e?.RunDecision;if(!t)throw new Error("Invalid response from server");const r={PromptRunID:t.promptRunId??void 0,ModelName:t.modelName??void 0,ResolvedModel:t.resolvedModel??void 0,ExecutionTimeMs:t.executionTimeMs??void 0};if(!t.success)return{...r,Success:!1,ErrorMessage:t.errorMessage||"Decision execution failed",Answers:{}};const s=this.parseDecisionAnswers(t.answersJSON);return typeof s=="string"?{...r,Success:!1,ErrorMessage:s,Answers:{}}:{...r,Success:!0,Answers:s}}parseDecisionAnswers(e){if(!e)return"The server returned no answers";let t;try{t=JSON.parse(e)}catch(s){return`The server returned answers that are not valid JSON: ${s instanceof Error?s.message:String(s)}`}if(typeof t!="object"||t===null||Array.isArray(t))return"The server returned answers that are not an object";const r={};for(const[s,n]of Object.entries(t)){if(!this.isDecisionAnswer(n))return`The server returned an answer for '${s}' that is not a Likelihood, Choice or Score answer`;r[s]=n}return r}isDecisionAnswer(e){if(typeof e!="object"||e===null)return!1;const t=e;switch(t.Kind){case"Likelihood":return typeof t.Probability=="number";case"Choice":return typeof t.Value=="string"&&typeof t.Confidence=="number";case"Score":return typeof t.Value=="number"&&typeof t.Confidence=="number";default:return!1}}handleDecisionError(e){const t=e instanceof Error?e.message:String(e);return y(`Error running decision: ${t}`),{Success:!1,ErrorMessage:t||"Unknown error occurred",Answers:{}}}async RunAIAgent(e,t,r){let s=!1;try{const n=this.buildRunAIAgentMutation(),a=this.prepareAgentVariables(e,t,r);a.fireAndForget=!0;const i={};return await w.Execute({dataProvider:this._dataProvider,mutation:n,variables:a,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:u(o=>{const m=o?.success===!0;return m&&(s=!0),m},"validateAck"),isCompletionEvent:u(o=>this.isAgentCompletionEvent(o),"isCompletionEvent"),extractResult:u(o=>this.extractAgentResult(o),"extractResult"),extractSyncResult:u(o=>this.extractAgentResultFromAck(o),"extractSyncResult"),onMessage:u(o=>{this.captureAgentRunId(o,i),e.onProgress&&this.forwardAgentProgress(o,e.onProgress)},"onMessage"),isRelevantMessage:u(o=>this.isMessageForAgentRun(o,i),"isRelevantMessage"),onStall:u(()=>this.reconcileAgentRun(i.id?`ID='${i.id}'`:void 0),"onStall"),createErrorResult:u(o=>this.createAgentErrorResult(o,s),"createErrorResult")})}catch(n){return this.handleAgentError(n,s)}}buildRunAIAgentMutation(){return c`
92
+ `,r=this.prepareDecisionVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processDecisionResult(s)}catch(t){return this.handleDecisionError(t)}}prepareDecisionVariables(e){const t={state:typeof e.State=="string"?e.State:JSON.stringify(e.State),questions:JSON.stringify(e.Questions)};return e.PromptID!==void 0&&(t.promptId=e.PromptID),e.PromptName!==void 0&&(t.promptName=e.PromptName),e.TimeoutMS!==void 0&&(t.timeoutMS=e.TimeoutMS),t}processDecisionResult(e){const t=e?.RunDecision;if(!t)throw new Error("Invalid response from server");const r={PromptRunID:t.promptRunId??void 0,ModelName:t.modelName??void 0,ResolvedModel:t.resolvedModel??void 0,ExecutionTimeMs:t.executionTimeMs??void 0};if(!t.success)return{...r,Success:!1,ErrorMessage:t.errorMessage||"Decision execution failed",Answers:{}};const s=this.parseDecisionAnswers(t.answersJSON);return typeof s=="string"?{...r,Success:!1,ErrorMessage:s,Answers:{}}:{...r,Success:!0,Answers:s}}parseDecisionAnswers(e){if(!e)return"The server returned no answers";let t;try{t=JSON.parse(e)}catch(s){return`The server returned answers that are not valid JSON: ${s instanceof Error?s.message:String(s)}`}if(typeof t!="object"||t===null||Array.isArray(t))return"The server returned answers that are not an object";const r={};for(const[s,n]of Object.entries(t)){if(!this.isDecisionAnswer(n))return`The server returned an answer for '${s}' that is not a Likelihood, Choice or Score answer`;r[s]=n}return r}isDecisionAnswer(e){if(typeof e!="object"||e===null)return!1;const t=e;switch(t.Kind){case"Likelihood":return typeof t.Probability=="number";case"Choice":return typeof t.Value=="string"&&typeof t.Confidence=="number";case"Score":return typeof t.Value=="number"&&typeof t.Confidence=="number";default:return!1}}handleDecisionError(e){const t=e instanceof Error?e.message:String(e);return u(`Error running decision: ${t}`),{Success:!1,ErrorMessage:t||"Unknown error occurred",Answers:{}}}async RunAIAgent(e,t,r){let s=!1;try{const n=this.buildRunAIAgentMutation(),a=this.prepareAgentVariables(e,t,r);a.fireAndForget=!0;const i={};return await w.Execute({dataProvider:this._dataProvider,mutation:n,variables:a,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:l(o=>{const g=o?.success===!0;return g&&(s=!0),g},"validateAck"),isCompletionEvent:l(o=>this.isAgentCompletionEvent(o),"isCompletionEvent"),extractResult:l(o=>this.extractAgentResult(o),"extractResult"),extractSyncResult:l(o=>this.extractAgentResultFromAck(o),"extractSyncResult"),onMessage:l(o=>{this.captureAgentRunId(o,i),e.onProgress&&this.forwardAgentProgress(o,e.onProgress)},"onMessage"),isRelevantMessage:l(o=>this.isMessageForAgentRun(o,i),"isRelevantMessage"),onStall:l(()=>this.reconcileAgentRun(i.id?`ID='${i.id}'`:void 0),"onStall"),createErrorResult:l(o=>this.createAgentErrorResult(o,s),"createErrorResult")})}catch(n){return this.handleAgentError(n,s)}}buildRunAIAgentMutation(){return c`
93
93
  mutation RunAIAgent(
94
94
  $agentId: String!,
95
95
  $messages: String!,
@@ -136,7 +136,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
136
136
  result
137
137
  }
138
138
  }
139
- `}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,t=!1){const s=e?.message||String(e);y(`Error running AI agent: ${s}`);const n=s.includes("Failed to fetch")||s.includes("NetworkError"),a=s.includes("timed out")||s.includes("timeout");let i;return n&&t?i="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":n?i="Could not reach the server. The request may not have started. Please try again.":i=s,{success:!1,agentRun:void 0,errorMessage:i,requestAcknowledged:t}}async RunAIAgentFromConversationDetail(e){let t=!1;try{const r=this.buildConversationDetailMutation(e.agentHistoryFrom!=null),s=this.prepareConversationDetailVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:r,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:u(n=>{const a=n?.success===!0;return a&&(t=!0),a},"validateAck"),isCompletionEvent:u(n=>this.isConversationDetailCompletionEvent(n,e.conversationDetailId),"isCompletionEvent"),extractResult:u(n=>this.extractAgentResult(n),"extractResult"),extractSyncResult:u(n=>this.extractAgentResultFromAck(n),"extractSyncResult"),onMessage:e.onProgress?n=>this.forwardConversationDetailProgress(n,e.onProgress):void 0,isRelevantMessage:u(n=>this.isMessageForConversationDetail(n,e.conversationDetailId),"isRelevantMessage"),onStall:u(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:u(n=>this.createAgentErrorResult(n,t),"createErrorResult")})}catch(r){return this.handleAgentError(r,t)}}buildConversationDetailMutation(e){return c`
139
+ `}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,t=!1){const s=e?.message||String(e);u(`Error running AI agent: ${s}`);const n=s.includes("Failed to fetch")||s.includes("NetworkError"),a=s.includes("timed out")||s.includes("timeout");let i;return n&&t?i="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":n?i="Could not reach the server. The request may not have started. Please try again.":i=s,{success:!1,agentRun:void 0,errorMessage:i,requestAcknowledged:t}}async RunAIAgentFromConversationDetail(e){let t=!1;try{const r=this.buildConversationDetailMutation(e.agentHistoryFrom!=null),s=this.prepareConversationDetailVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:r,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:l(n=>{const a=n?.success===!0;return a&&(t=!0),a},"validateAck"),isCompletionEvent:l(n=>this.isConversationDetailCompletionEvent(n,e.conversationDetailId),"isCompletionEvent"),extractResult:l(n=>this.extractAgentResult(n),"extractResult"),extractSyncResult:l(n=>this.extractAgentResultFromAck(n),"extractSyncResult"),onMessage:e.onProgress?n=>this.forwardConversationDetailProgress(n,e.onProgress):void 0,isRelevantMessage:l(n=>this.isMessageForConversationDetail(n,e.conversationDetailId),"isRelevantMessage"),onStall:l(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:l(n=>this.createAgentErrorResult(n,t),"createErrorResult")})}catch(r){return this.handleAgentError(r,t)}}buildConversationDetailMutation(e){return c`
140
140
  mutation RunAIAgentFromConversationDetail(
141
141
  $conversationDetailId: String!,
142
142
  $agentId: String!,
@@ -181,7 +181,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
181
181
  result
182
182
  }
183
183
  }
184
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),e.agentHistoryFrom!=null&&(t.agentHistoryFrom=e.agentHistoryFrom.toISOString()),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}isMessageForConversationDetail(e,t){const r=e.data;if(!r)return!0;const s=r.conversationDetailId;return s?Y(s,t):!0}isMessageForAgentRun(e,t){if(!t.id)return!0;const r=e.data;if(!r)return!0;const s=r.agentRunId??r.runId;return!s||s==="unknown"?!0:Y(s,t.id)}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?v(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;if(r){const a=v(r);if(a)return!a.errorMessage&&typeof t.errorMessage=="string"&&(a.errorMessage=t.errorMessage),a}const s=!!t.success,n=typeof t.errorMessage=="string"&&t.errorMessage?t.errorMessage:void 0;return{success:s,agentRun:void 0,errorMessage:n??(s?void 0:"Agent execution ended without a result payload")}}extractAgentResultFromAck(e){const t=e.result;if(t){const r=v(t);if(r)return r}return{success:e.success,agentRun:void 0,errorMessage:e.errorMessage}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e,t=!1){return{success:!1,agentRun:void 0,errorMessage:e,requestAcknowledged:t}}async ExecuteSimplePrompt(e){try{const t=c`
184
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),e.agentHistoryFrom!=null&&(t.agentHistoryFrom=e.agentHistoryFrom.toISOString()),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}isMessageForConversationDetail(e,t){const r=e.data;if(!r)return!0;const s=r.conversationDetailId;return s?ee(s,t):!0}isMessageForAgentRun(e,t){if(!t.id)return!0;const r=e.data;if(!r)return!0;const s=r.agentRunId??r.runId;return!s||s==="unknown"?!0:ee(s,t.id)}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?v(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;if(r){const a=v(r);if(a)return!a.errorMessage&&typeof t.errorMessage=="string"&&(a.errorMessage=t.errorMessage),a}const s=!!t.success,n=typeof t.errorMessage=="string"&&t.errorMessage?t.errorMessage:void 0;return{success:s,agentRun:void 0,errorMessage:n??(s?void 0:"Agent execution ended without a result payload")}}extractAgentResultFromAck(e){const t=e.result;if(t){const r=v(t);if(r)return r}return{success:e.success,agentRun:void 0,errorMessage:e.errorMessage}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e,t=!1){return{success:!1,agentRun:void 0,errorMessage:e,requestAcknowledged:t}}async ExecuteSimplePrompt(e){try{const t=c`
185
185
  mutation ExecuteSimplePrompt(
186
186
  $systemPrompt: String!,
187
187
  $messages: String,
@@ -204,7 +204,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
204
204
  executionTimeMs
205
205
  }
206
206
  }
207
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return y(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=c`
207
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=c`
208
208
  mutation EmbedText(
209
209
  $textToEmbed: [String!]!,
210
210
  $modelSize: String!
@@ -219,7 +219,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
219
219
  error
220
220
  }
221
221
  }
222
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return y(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=c`
222
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return u(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=c`
223
223
  mutation RunAutotagPipeline($contentSourceIDs: [String!], $forceReprocess: Boolean) {
224
224
  RunAutotagPipeline(contentSourceIDs: $contentSourceIDs, forceReprocess: $forceReprocess) {
225
225
  Success
@@ -228,7 +228,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
228
228
  PipelineRunID
229
229
  }
230
230
  }
231
- `,r={};e?.contentSourceIDs?.length&&(r.contentSourceIDs=e.contentSourceIDs),e?.forceReprocess&&(r.forceReprocess=!0);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunAutotagPipeline)throw new Error("Invalid response from server");return s.RunAutotagPipeline}catch(t){const r=t;return y("GraphQLAIClient.RunAutotagPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PauseClassificationPipeline(e){try{const t=c`
231
+ `,r={};e?.contentSourceIDs?.length&&(r.contentSourceIDs=e.contentSourceIDs),e?.forceReprocess&&(r.forceReprocess=!0);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunAutotagPipeline)throw new Error("Invalid response from server");return s.RunAutotagPipeline}catch(t){const r=t;return u("GraphQLAIClient.RunAutotagPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PauseClassificationPipeline(e){try{const t=c`
232
232
  mutation PauseClassificationPipeline($processRunID: String!) {
233
233
  PauseClassificationPipeline(processRunID: $processRunID) {
234
234
  Success
@@ -237,7 +237,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
237
237
  PipelineRunID
238
238
  }
239
239
  }
240
- `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.PauseClassificationPipeline)throw new Error("Invalid response from server");return r.PauseClassificationPipeline}catch(t){const r=t;return y("GraphQLAIClient.PauseClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async ResumeClassificationPipeline(e){try{const t=c`
240
+ `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.PauseClassificationPipeline)throw new Error("Invalid response from server");return r.PauseClassificationPipeline}catch(t){const r=t;return u("GraphQLAIClient.PauseClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async ResumeClassificationPipeline(e){try{const t=c`
241
241
  mutation ResumeClassificationPipeline($processRunID: String!) {
242
242
  ResumeClassificationPipeline(processRunID: $processRunID) {
243
243
  Success
@@ -246,7 +246,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
246
246
  PipelineRunID
247
247
  }
248
248
  }
249
- `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.ResumeClassificationPipeline)throw new Error("Invalid response from server");return r.ResumeClassificationPipeline}catch(t){const r=t;return y("GraphQLAIClient.ResumeClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PromoteTagSuggestion(e){try{const t=c`
249
+ `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.ResumeClassificationPipeline)throw new Error("Invalid response from server");return r.ResumeClassificationPipeline}catch(t){const r=t;return u("GraphQLAIClient.ResumeClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PromoteTagSuggestion(e){try{const t=c`
250
250
  mutation PromoteTagSuggestion($suggestionID: String!, $strategy: String!, $targetTagID: String) {
251
251
  PromoteTagSuggestion(suggestionID: $suggestionID, strategy: $strategy, targetTagID: $targetTagID) {
252
252
  Success
@@ -255,14 +255,14 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
255
255
  ErrorMessage
256
256
  }
257
257
  }
258
- `,r={suggestionID:e.suggestionID,strategy:e.strategy};e.targetTagID&&(r.targetTagID=e.targetTagID);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.PromoteTagSuggestion)throw new Error("Invalid response from server");return s.PromoteTagSuggestion}catch(t){const r=t;return y("GraphQLAIClient.PromoteTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RejectTagSuggestion(e){try{const t=c`
258
+ `,r={suggestionID:e.suggestionID,strategy:e.strategy};e.targetTagID&&(r.targetTagID=e.targetTagID);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.PromoteTagSuggestion)throw new Error("Invalid response from server");return s.PromoteTagSuggestion}catch(t){const r=t;return u("GraphQLAIClient.PromoteTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RejectTagSuggestion(e){try{const t=c`
259
259
  mutation RejectTagSuggestion($suggestionID: String!, $reviewerNotes: String) {
260
260
  RejectTagSuggestion(suggestionID: $suggestionID, reviewerNotes: $reviewerNotes) {
261
261
  Success
262
262
  ErrorMessage
263
263
  }
264
264
  }
265
- `,r={suggestionID:e.suggestionID};e.reviewerNotes&&(r.reviewerNotes=e.reviewerNotes);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RejectTagSuggestion)throw new Error("Invalid response from server");return s.RejectTagSuggestion}catch(t){const r=t;return y("GraphQLAIClient.RejectTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RebuildTagEmbeddings(){try{const e=c`
265
+ `,r={suggestionID:e.suggestionID};e.reviewerNotes&&(r.reviewerNotes=e.reviewerNotes);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RejectTagSuggestion)throw new Error("Invalid response from server");return s.RejectTagSuggestion}catch(t){const r=t;return u("GraphQLAIClient.RejectTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RebuildTagEmbeddings(){try{const e=c`
266
266
  mutation RebuildTagEmbeddings {
267
267
  RebuildTagEmbeddings {
268
268
  Success
@@ -271,7 +271,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
271
271
  ErrorMessage
272
272
  }
273
273
  }
274
- `,t=await this._dataProvider.ExecuteGQL(e,{});if(!t?.RebuildTagEmbeddings)throw new Error("Invalid response from server");return t.RebuildTagEmbeddings}catch(e){const t=e;return y("GraphQLAIClient.RebuildTagEmbeddings failed",void 0,t),{Success:!1,Refreshed:0,Total:0,ErrorMessage:t.message||"Unknown error"}}}async RunTagHealth(e){try{const t=c`
274
+ `,t=await this._dataProvider.ExecuteGQL(e,{});if(!t?.RebuildTagEmbeddings)throw new Error("Invalid response from server");return t.RebuildTagEmbeddings}catch(e){const t=e;return u("GraphQLAIClient.RebuildTagEmbeddings failed",void 0,t),{Success:!1,Refreshed:0,Total:0,ErrorMessage:t.message||"Unknown error"}}}async RunTagHealth(e){try{const t=c`
275
275
  mutation RunTagHealth(
276
276
  $minCoOccurrence: Int,
277
277
  $minNameSimilarity: Float,
@@ -294,7 +294,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
294
294
  ErrorMessage
295
295
  }
296
296
  }
297
- `,r={};e?.minCoOccurrence!=null&&(r.minCoOccurrence=e.minCoOccurrence),e?.minNameSimilarity!=null&&(r.minNameSimilarity=e.minNameSimilarity),e?.minEmbeddingSimilarity!=null&&(r.minEmbeddingSimilarity=e.minEmbeddingSimilarity),e?.maxUsage!=null&&(r.maxUsage=e.maxUsage),e?.maxImplicitChildren!=null&&(r.maxImplicitChildren=e.maxImplicitChildren);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunTagHealth)throw new Error("Invalid response from server");return s.RunTagHealth}catch(t){const r=t;return y("GraphQLAIClient.RunTagHealth failed",void 0,r),{Success:!1,MergeCount:0,LowUsageCount:0,WideNodeCount:0,DurationMs:0,ErrorMessage:r.message||"Unknown error"}}}async VectorizeEntity(e){try{const t=c`
297
+ `,r={};e?.minCoOccurrence!=null&&(r.minCoOccurrence=e.minCoOccurrence),e?.minNameSimilarity!=null&&(r.minNameSimilarity=e.minNameSimilarity),e?.minEmbeddingSimilarity!=null&&(r.minEmbeddingSimilarity=e.minEmbeddingSimilarity),e?.maxUsage!=null&&(r.maxUsage=e.maxUsage),e?.maxImplicitChildren!=null&&(r.maxImplicitChildren=e.maxImplicitChildren);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunTagHealth)throw new Error("Invalid response from server");return s.RunTagHealth}catch(t){const r=t;return u("GraphQLAIClient.RunTagHealth failed",void 0,r),{Success:!1,MergeCount:0,LowUsageCount:0,WideNodeCount:0,DurationMs:0,ErrorMessage:r.message||"Unknown error"}}}async VectorizeEntity(e){try{const t=c`
298
298
  mutation VectorizeEntity(
299
299
  $entityDocumentID: String!,
300
300
  $entityID: String!,
@@ -311,7 +311,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
311
311
  PipelineRunID
312
312
  }
313
313
  }
314
- `,r={entityDocumentID:e.entityDocumentID,entityID:e.entityID};e.batchSize!==void 0&&(r.batchSize=e.batchSize);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.VectorizeEntity)throw new Error("Invalid response from server");return s.VectorizeEntity}catch(t){const r=t;return y("GraphQLAIClient.VectorizeEntity failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async FetchEntityVectors(e){try{const t=c`
314
+ `,r={entityDocumentID:e.entityDocumentID,entityID:e.entityID};e.batchSize!==void 0&&(r.batchSize=e.batchSize);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.VectorizeEntity)throw new Error("Invalid response from server");return s.VectorizeEntity}catch(t){const r=t;return u("GraphQLAIClient.VectorizeEntity failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async FetchEntityVectors(e){try{const t=c`
315
315
  query FetchEntityVectors(
316
316
  $entityDocumentID: String!,
317
317
  $maxRecords: Int,
@@ -333,7 +333,7 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
333
333
  }
334
334
  }
335
335
  }
336
- `,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"}}}async CheckDuplicateEntry(e){try{const t=c`
336
+ `,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 u("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}async CheckDuplicateEntry(e){try{const t=c`
337
337
  mutation CheckDuplicateEntry(
338
338
  $entityName: String!,
339
339
  $valuesJSON: String!
@@ -353,14 +353,14 @@ var Ie=Object.defineProperty;var u=(l,e)=>Ie(l,"name",{value:e,configurable:!0})
353
353
  }
354
354
  }
355
355
  }
356
- `,r={entityName:e.EntityName,valuesJSON:JSON.stringify(e.Values)},s=await this._dataProvider.ExecuteGQL(t,r);return this.processDuplicateEntryCheckResult(s)}catch(t){return this.handleDuplicateEntryCheckError(t)}}processDuplicateEntryCheckResult(e){const t=e?.CheckDuplicateEntry;if(!t)throw new Error("Invalid response from server");const r=t.ElapsedMs??void 0;if(!this.isDuplicateEntryCheckStatus(t.Status))return{Status:"Failed",ErrorMessage:`The server returned an unknown status '${t.Status}'`,Candidates:[],ElapsedMs:r};const s={Status:t.Status,Candidates:(t.Candidates??[]).map(n=>({RecordID:n.RecordID,DisplayName:n.DisplayName,VectorScore:n.VectorScore,Probability:n.Probability??null})),ElapsedMs:r};return t.ErrorMessage&&(s.ErrorMessage=t.ErrorMessage),s}isDuplicateEntryCheckStatus(e){return e==="Checked"||e==="NotConfigured"||e==="NotAuthorized"||e==="Failed"}handleDuplicateEntryCheckError(e){const t=e instanceof Error?e.message:String(e);return y(`Error checking for a duplicate entry: ${t}`),{Status:"Failed",ErrorMessage:t||"Unknown error occurred",Candidates:[]}}}const G="6.2.0-edge.2",$="default";class ie{static{u(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 _e="MJ_Metadata",Ve=0;function ke(){try{const l=G.split("."),e=parseInt(l[0],10),t=parseInt(l[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${G}"`);return e*1e3+t+Ve}catch(l){return M({error:l,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}u(ke,"computeIdbVersion");const Oe=ke(),ce=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class ue extends ie{static{u(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=Ge(_e,Oe,{upgrade:u((e,t,r)=>{try{P(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${G}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of ce)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){M({error:s,message:s?.message})}},"upgrade"),blocked:u((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=>{M({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return ce.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){M({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 M({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"),m=o.objectStore(n),d=i.map(f=>m.get(f)),g=await Promise.all(d);await o.done;for(let f=0;f<a.length;f++){const S=g[f];r.set(a[f],S===void 0?null:S)}return r}catch(s){M({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){M({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){M({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 M({error:t,message:t?.message}),[]}}}class k extends Error{static{u(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}
357
- ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))}u(le,"ToSafeGraphQLError");const qe=3,Ke=25;function O(l,e=0){if(l===null)return"null";if(l===void 0)return"undefined";if(Array.isArray(l))return l.length===0?"array(empty)":`array(${l.length} \xD7 ${Be(O(l[0],e+1))})`;if(typeof l=="object"){if(e>=qe)return"object(\u2026)";const t=Object.keys(l);if(t.length>Ke)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=O(l[s],e+1);return r}return typeof l=="string"?l.length===0?"string(empty)":"string":typeof l}u(O,"describeShape");function Be(l){return typeof l=="string"?l:"object"}u(Be,"typeOf");function je(l){const e=l.indexOf(`
358
- at `);return e===-1?"":l.slice(e+1)}u(je,"stripStackHeader");function Je(l,e){const t=l?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}u(Je,"deriveMessage");function We(l){if(Array.isArray(l))return l.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}})}u(We,"extractErrors");function q(l,e=!1){if(!l||typeof l!="object")return{name:typeof l,message:"Non-object value thrown; contents withheld",variables:"[REDACTED]"};const t=l,r=typeof t.response?.status=="number"?t.response.status:void 0,s=We(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:Je(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"?je(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:O(t.request.variables)}}u(q,"SanitizeGraphQLError");const de=new WeakMap;function ye(l,e,t,r){return JSON.stringify([l,e??null,t??null,r??null])}u(ye,"credentialsKey");const b=new N,He=c`subscription RemoteOperationProgress($channelId: ID!) {
356
+ `,r={entityName:e.EntityName,valuesJSON:JSON.stringify(e.Values)},s=await this._dataProvider.ExecuteGQL(t,r);return this.processDuplicateEntryCheckResult(s)}catch(t){return this.handleDuplicateEntryCheckError(t)}}processDuplicateEntryCheckResult(e){const t=e?.CheckDuplicateEntry;if(!t)throw new Error("Invalid response from server");const r=t.ElapsedMs??void 0;if(!this.isDuplicateEntryCheckStatus(t.Status))return{Status:"Failed",ErrorMessage:`The server returned an unknown status '${t.Status}'`,Candidates:[],ElapsedMs:r};const s={Status:t.Status,Candidates:(t.Candidates??[]).map(n=>({RecordID:n.RecordID,DisplayName:n.DisplayName,VectorScore:n.VectorScore,Probability:n.Probability??null})),ElapsedMs:r};return t.ErrorMessage&&(s.ErrorMessage=t.ErrorMessage),s}isDuplicateEntryCheckStatus(e){return e==="Checked"||e==="NotConfigured"||e==="NotAuthorized"||e==="Failed"}handleDuplicateEntryCheckError(e){const t=e instanceof Error?e.message:String(e);return u(`Error checking for a duplicate entry: ${t}`),{Status:"Failed",ErrorMessage:t||"Unknown error occurred",Candidates:[]}}}const Q="6.2.0-edge.3",$="default";class ue{static{l(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}get SharesReferences(){return!0}get SupportsCrossProcessPersistence(){return!1}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 Ke="MJ_Metadata",Be=0;function je(){try{const d=Q.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 "${Q}"`);return e*1e3+t+Be}catch(d){return M({error:d,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}l(je,"computeIdbVersion");const Je=je(),le=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class de extends ue{static{l(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=Oe(Ke,Je,{upgrade:l((e,t,r)=>{try{P(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${Q}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of le)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){M({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=>{M({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get SupportsCrossProcessPersistence(){return!0}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return le.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){M({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 M({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),y=i.map(f=>g.get(f)),m=await Promise.all(y);await o.done;for(let f=0;f<a.length;f++){const S=m[f];r.set(a[f],S===void 0?null:S)}return r}catch(s){M({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){M({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){M({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 M({error:t,message:t?.message}),[]}}}class k 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}
357
+ ${e.stackFrames}`:this.stack}}function ye(d){return d instanceof k?d:new k(K(d))}l(ye,"ToSafeGraphQLError");const We=3,He=25;function q(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 ${ze(q(d[0],e+1))})`;if(typeof d=="object"){if(e>=We)return"object(\u2026)";const t=Object.keys(d);if(t.length>He)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=q(d[s],e+1);return r}return typeof d=="string"?d.length===0?"string(empty)":"string":typeof d}l(q,"describeShape");function ze(d){return typeof d=="string"?d:"object"}l(ze,"typeOf");function Xe(d){const e=d.indexOf(`
358
+ at `);return e===-1?"":d.slice(e+1)}l(Xe,"stripStackHeader");function Ye(d,e){const t=d?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}l(Ye,"deriveMessage");function Ze(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(Ze,"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=Ze(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:Ye(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"?Xe(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:q(t.request.variables)}}l(K,"SanitizeGraphQLError");const ge=new WeakMap;function me(d,e,t,r){return JSON.stringify([d,e??null,t??null,r??null])}l(me,"credentialsKey");const N=new b,et=c`subscription RemoteOperationProgress($channelId: ID!) {
359
359
  RemoteOperationProgress(channelId: $channelId) {
360
360
  ChannelId
361
361
  ProgressJSON
362
362
  }
363
- }`;class ze extends Me{static{u(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,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:m,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}const Xe=1e4,Ye=1e4,Ze=1e4;class I extends Re{static{u(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
363
+ }`;class tt extends Ae{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,y){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:g,RefreshTokenFunction:s,OnAuthenticationError:y},n,a,i)}}const rt=1e4,st=1e4,nt=1e4;class I extends ve{static{l(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._recordNames=new Ce,this._innerCurrentUserQueryString=`CurrentUser {
364
364
  ${this.userInfoString()}
365
365
  Roles {
366
366
  ${this.userRoleInfoString()}
@@ -369,7 +369,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
369
369
  `,this._currentUserQuery=c`query CurrentUserAndRoles {
370
370
  ${this._innerCurrentUserQueryString}
371
371
  CurrentUserTenantContext
372
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new xe("unknown"),this._socketReconnectedSubject=new V,this._isDisposingSocketIntentionally=!1,this._disarmPongWatchdog=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._taskGraphFrameStreams=new Map,this._cacheInvalidationSubscription=null;const e=Z();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=Z();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new oe(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 Fe()}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 await this.connectClient(e,r,s),super.Config(e)}catch(n){throw y(n),n}}async Connect(e){await this.connectClient(e,!1,!1)}async connectClient(e,t,r){if(this._configData=e,t||I.Instance!==this)this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.saveStoredSessionID(this._sessionId);else{I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(r));const s=I.Instance._client;(!s||this.isBuiltWithOtherCredentials(s,e))&&(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}}isBuiltWithOtherCredentials(e,t){const r=de.get(e);return r!==void 0&&r!==ye(t.URL,t.Token,t.MJAPIKey,t.UserAPIKey)}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),{Roles:r,...s}=t,n=(r??[]).map(i=>this.ConvertBackToMJFields(i)),a=new W(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`
372
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new Ge("unknown"),this._socketReconnectedSubject=new O,this._isDisposingSocketIntentionally=!1,this._disarmPongWatchdog=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._taskGraphFrameStreams=new Map,this._cacheInvalidationSubscription=null;const e=te();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=te();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new ce(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 Ve()}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 await this.connectClient(e,r,s),super.Config(e)}catch(n){throw u(n),n}}async Connect(e){await this.connectClient(e,!1,!1)}async connectClient(e,t,r){if(this._configData=e,t||I.Instance!==this)this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.saveStoredSessionID(this._sessionId);else{I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(r));const s=I.Instance._client;(!s||this.isBuiltWithOtherCredentials(s,e))&&(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}}isBuiltWithOtherCredentials(e,t){const r=ge.get(e);return r!==void 0&&r!==me(t.URL,t.Token,t.MJAPIKey,t.UserAPIKey)}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),{Roles:r,...s}=t,n=(r??[]).map(i=>this.ConvertBackToMJFields(i)),a=new z(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,e.TimeoutSeconds,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`
373
373
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
374
374
  ExecuteAdhocQuery(input: $input) {
375
375
  ${this.QueryReturnFieldList}
@@ -381,19 +381,19 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
381
381
  ${this.QueryReturnFieldList}
382
382
  }
383
383
  }
384
- `,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 d=c`
384
+ `,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,g){const y=c`
385
385
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
386
386
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
387
387
  ${this.QueryReturnFieldList}
388
388
  }
389
389
  }
390
- `,g={QueryID:e};t!==void 0&&(g.CategoryID=t),r!==void 0&&(g.CategoryPath=r),n!==void 0&&(g.Parameters=n),a!==void 0&&(g.MaxRows=a),i!==void 0&&(g.StartRow=i),o!==void 0&&(g.Enrichment=o),m!==void 0&&(g.DataSource=m);const f=await this.ExecuteGQL(d,g);if(f&&f.GetQueryData)return this.TransformQueryPayload(f.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o,m){const d=c`
390
+ `,m={QueryID:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),n!==void 0&&(m.Parameters=n),a!==void 0&&(m.MaxRows=a),i!==void 0&&(m.StartRow=i),o!==void 0&&(m.Enrichment=o),g!==void 0&&(m.DataSource=g);const f=await this.ExecuteGQL(y,m);if(f&&f.GetQueryData)return this.TransformQueryPayload(f.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o,g){const y=c`
391
391
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
392
392
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
393
393
  ${this.QueryReturnFieldList}
394
394
  }
395
395
  }
396
- `,g={QueryName:e};t!==void 0&&(g.CategoryID=t),r!==void 0&&(g.CategoryPath=r),n!==void 0&&(g.Parameters=n),a!==void 0&&(g.MaxRows=a),i!==void 0&&(g.StartRow=i),o!==void 0&&(g.Enrichment=o),m!==void 0&&(g.DataSource=m);const f=await this.ExecuteGQL(d,g);if(f&&f.GetQueryDataByName)return this.TransformQueryPayload(f.GetQueryDataByName)}get QueryReturnFieldList(){return`
396
+ `,m={QueryName:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),n!==void 0&&(m.Parameters=n),a!==void 0&&(m.MaxRows=a),i!==void 0&&(m.StartRow=i),o!==void 0&&(m.Enrichment=o),g!==void 0&&(m.DataSource=g);const f=await this.ExecuteGQL(y,m);if(f&&f.GetQueryDataByName)return this.TransformQueryPayload(f.GetQueryDataByName)}get QueryReturnFieldList(){return`
397
397
  Success
398
398
  QueryID
399
399
  QueryName
@@ -402,7 +402,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
402
402
  TotalRowCount
403
403
  ExecutionTime
404
404
  ErrorMessage
405
- 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`
405
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u(`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`
406
406
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
407
407
  RunQueriesWithCacheCheck(input: $input) {
408
408
  success
@@ -418,7 +418,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
418
418
  }
419
419
  }
420
420
  }
421
- `,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:D,v:h}=await this.getEntityNameAndUserView(e,t);i=h,a=D}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let m=!1;const d=L(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):(m=!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),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(D=>({expression:D.expression,alias:D.alias})));const g=this.getViewRunTimeFieldList(o,i,e,m),f=e.Aggregates&&e.Aggregates.length>0?`
421
+ `,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 u(`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:D,v:h}=await this.getEntityNameAndUserView(e,t);i=h,a=D}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let g=!1;const y=F(o);e.ViewID?(r=`Run${y}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${y}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(g=!0,r=`Run${y}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),e.IncludeBinaryFields!==void 0&&(n.IncludeBinaryFields=e.IncludeBinaryFields),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(D=>({expression:D.expression,alias:D.alias})));const m=this.getViewRunTimeFieldList(o,i,e,g),f=e.Aggregates&&e.Aggregates.length>0?`
422
422
  AggregateResults {
423
423
  alias
424
424
  expression
@@ -429,7 +429,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
429
429
  query RunViewQuery ($input: ${s}!) {
430
430
  ${r}(input: $input) {
431
431
  Results {
432
- ${g.join(`
432
+ ${m.join(`
433
433
  `)}
434
434
  }
435
435
  UserViewRunID
@@ -439,7 +439,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
439
439
  Success
440
440
  ErrorMessage${f}
441
441
  }
442
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const E=await this.ExecuteGQL(S,{input:n});if(E&&E[r]){const D=E[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:D?.length||0,aggregateResults:D,aggregateExecutionTime:E[r].AggregateExecutionTime});const h=E[r].Results;if(h&&h.length>0){const R=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);h.forEach(C=>{this.ConvertBackToMJFields(C),R.forEach(F=>{C[F.Name]=C[F.CodeName]})})}return E[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 g="",f="";const S={};let E=null,D=null;if(d.ViewEntity)D=d.ViewEntity,E=D.Get("Entity");else{const{entityName:C,v:F}=await this.getEntityNameAndUserView(d,t);D=F,E=C}const h=this.EntityByName(E);if(!h)throw new Error(`Entity ${E} not found in metadata`);s.push(h);let p=!1;const R=L(h);d.ViewID?(g=`Run${R}ViewByID`,f="RunViewByIDInput",S.ViewID=d.ViewID):d.ViewName?(g=`Run${R}ViewByName`,f="RunViewByNameInput",S.ViewName=d.ViewName):(p=!0,g=`Run${R}DynamicView`,f="RunDynamicViewInput",S.EntityName=d.EntityName),S.ExtraFilter=d.ExtraFilter||"",S.OrderBy=d.OrderBy||"",S.UserSearchString=d.UserSearchString||"",S.Fields=d.Fields,S.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(S.MaxRows=d.MaxRows),d.StartRow!==void 0&&(S.StartRow=d.StartRow),d.AfterKey&&(S.AfterKey={KeyValuePairs:d.AfterKey.KeyValuePairs}),S.ForceAuditLog=d.ForceAuditLog||!1,S.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(S.AuditLogDescription=d.AuditLogDescription),d.BypassCache!==void 0&&(S.BypassCache=d.BypassCache),d.DataSource!==void 0&&(S.DataSource=d.DataSource),p||(S.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",S.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,S.OverrideExcludeFilter=d.OverrideExcludeFilter||"",S.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(S.Aggregates=d.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(S),n.push(...this.getViewRunTimeFieldList(h,D,d,p))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
442
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const E=await this.ExecuteGQL(S,{input:n});if(E&&E[r]){const D=E[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:D?.length||0,aggregateResults:D,aggregateExecutionTime:E[r].AggregateExecutionTime});const h=E[r].Results;if(h&&h.length>0){const R=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);h.forEach(C=>{this.ConvertBackToMJFields(C),R.forEach(G=>{C[G.Name]=C[G.CodeName]})})}return E[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const y of e){let m="",f="";const S={};let E=null,D=null;if(y.ViewEntity)D=y.ViewEntity,E=D.Get("Entity");else{const{entityName:C,v:G}=await this.getEntityNameAndUserView(y,t);D=G,E=C}const h=this.EntityByName(E);if(!h)throw new Error(`Entity ${E} not found in metadata`);s.push(h);let p=!1;const R=F(h);y.ViewID?(m=`Run${R}ViewByID`,f="RunViewByIDInput",S.ViewID=y.ViewID):y.ViewName?(m=`Run${R}ViewByName`,f="RunViewByNameInput",S.ViewName=y.ViewName):(p=!0,m=`Run${R}DynamicView`,f="RunDynamicViewInput",S.EntityName=y.EntityName),S.ExtraFilter=y.ExtraFilter||"",S.OrderBy=y.OrderBy||"",S.UserSearchString=y.UserSearchString||"",S.Fields=y.Fields,S.IgnoreMaxRows=y.IgnoreMaxRows||!1,y.MaxRows!==void 0&&(S.MaxRows=y.MaxRows),y.StartRow!==void 0&&(S.StartRow=y.StartRow),y.AfterKey&&(S.AfterKey={KeyValuePairs:y.AfterKey.KeyValuePairs}),S.ForceAuditLog=y.ForceAuditLog||!1,S.ResultType=y.ResultType||"simple",y.AuditLogDescription&&y.AuditLogDescription.length>0&&(S.AuditLogDescription=y.AuditLogDescription),y.BypassCache!==void 0&&(S.BypassCache=y.BypassCache),y.DataSource!==void 0&&(S.DataSource=y.DataSource),y.IncludeBinaryFields!==void 0&&(S.IncludeBinaryFields=y.IncludeBinaryFields),p||(S.ExcludeUserViewRunID=y.ExcludeUserViewRunID||"",S.ExcludeDataFromAllPriorViewRuns=y.ExcludeDataFromAllPriorViewRuns||!1,S.OverrideExcludeFilter=y.OverrideExcludeFilter||"",S.SaveViewResults=y.SaveViewResults||!1),y.Aggregates&&y.Aggregates.length>0&&(S.Aggregates=y.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(S),n.push(...this.getViewRunTimeFieldList(h,D,y,p))}const i=e.some(y=>y.Aggregates&&y.Aggregates.length>0)?`
443
443
  AggregateResults {
444
444
  alias
445
445
  expression
@@ -464,7 +464,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
464
464
  Success
465
465
  ErrorMessage${i}
466
466
  }
467
- }`,m=await this.ExecuteGQL(o,{input:r});if(m&&m.RunViews){const d=m.RunViews;for(const[g,f]of d.entries())f.Results=f.Results.map(S=>{let E=JSON.parse(S.Data);return this.ConvertBackToMJFields(E),E});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,DataSource:o.params.DataSource},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
467
+ }`,g=await this.ExecuteGQL(o,{input:r});if(g&&g.RunViews){const y=g.RunViews;for(const[m,f]of y.entries())f.Results=f.Results.map(S=>{let E=JSON.parse(S.Data);return this.ConvertBackToMJFields(E),E});return y}return null}catch(r){throw u(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,IncludeBinaryFields:o.params.IncludeBinaryFields},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
468
468
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
469
469
  RunViewsWithCacheCheck(input: $input) {
470
470
  success
@@ -503,7 +503,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
503
503
  }
504
504
  }
505
505
  }
506
- `,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 d=e[m];if(o.status==="differential"&&o.differentialData){const g=o.differentialData.updatedRows.map(f=>{const S=JSON.parse(f.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:g,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const g=o.Results.map(S=>{const E=JSON.parse(S.Data);return this.ConvertBackToMJFields(E),E}),f=o.aggregateResults?.map(S=>({expression:S.expression,alias:S.alias,value:S.value!==void 0&&S.value!==null?JSON.parse(S.value):null,error:S.error}));return{viewIndex:o.viewIndex,status:o.status,results:g,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 se.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await se.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(b.MapFieldName(a.Name));r.Fields.forEach(a=>{n.push(b.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(b.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(b.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(b.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!) {
506
+ `,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 y=e[g];if(o.status==="differential"&&o.differentialData){const m=o.differentialData.updatedRows.map(f=>{const S=JSON.parse(f.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:m,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const m=o.Results.map(S=>{const E=JSON.parse(S.Data);return this.ConvertBackToMJFields(E),E}),f=o.aggregateResults?.map(S=>({expression:S.expression,alias:S.alias,value:S.value!==void 0&&S.value!==null?JSON.parse(S.value):null,error:S.error}));return{viewIndex:o.viewIndex,status:o.status,results:m,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 u(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 ae.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await ae.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(N.MapFieldName(a.Name));r.Fields.forEach(a=>{n.push(N.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{(!a.IsBinaryFieldType||r.IncludeBinaryFields===!0)&&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(N.MapFieldName(a.Name));t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&(a.EntityField.IsBinaryFieldType&&r.IncludeBinaryFields!==!0||n.push(N.MapFieldName(a.EntityField.CodeName)))})}return n}get ProviderType(){return we.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 u(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
507
507
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
508
508
  EntityName
509
509
  RelatedEntityName
@@ -517,7 +517,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
517
517
  IsSoftLink
518
518
  EntityIDFieldName
519
519
  }
520
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}},n=await this.ExecuteGQL(r,s);return n?.GetRecordDependencies&&Array.isArray(n.GetRecordDependencies)?n.GetRecordDependencies.map(a=>{const i=new ve;i.EntityName=a.EntityName,i.RelatedEntityName=a.RelatedEntityName,i.FieldName=a.FieldName;const o=(a.PrimaryKey?.KeyValuePairs??[]).map(d=>new Ce(d.FieldName,d.Value)),m=new H(o);return m.KeyValuePairs.length===0&&o.length>0&&(m.KeyValuePairs=o),i.PrimaryKey=m,i.IsSoftLink=a.IsSoftLink??void 0,i.EntityIDFieldName=a.EntityIDFieldName??void 0,i}):[]}catch(r){throw y(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=c`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
520
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}},n=await this.ExecuteGQL(r,s);return n?.GetRecordDependencies&&Array.isArray(n.GetRecordDependencies)?n.GetRecordDependencies.map(a=>{const i=new $e;i.EntityName=a.EntityName,i.RelatedEntityName=a.RelatedEntityName,i.FieldName=a.FieldName;const o=(a.PrimaryKey?.KeyValuePairs??[]).map(y=>new Pe(y.FieldName,y.Value)),g=new X(o);return g.KeyValuePairs.length===0&&o.length>0&&(g.KeyValuePairs=o),i.PrimaryKey=g,i.IsSoftLink=a.IsSoftLink??void 0,i.EntityIDFieldName=a.EntityIDFieldName??void 0,i}):[]}catch(r){throw u(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=c`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
521
521
  GetRecordDuplicates(params: $params) {
522
522
  Status
523
523
  ErrorMessage
@@ -555,7 +555,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
555
555
  }
556
556
  }
557
557
  }
558
- }`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(o=>({entityRecordDocumentId:o.EntityRecordDocumentID,recordId:o.RecordID,score:o.Score,matchType:o.MatchType,components:{lexical:o.LexicalScore??void 0,semantic:o.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&y(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}async InternalRouteOperation(e,t,r){const s=c`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!, $progressChannelId: String) {
558
+ }`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(o=>({entityRecordDocumentId:o.EntityRecordDocumentID,recordId:o.RecordID,score:o.Score,matchType:o.MatchType,components:{lexical:o.LexicalScore??void 0,semantic:o.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&u(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}async InternalRouteOperation(e,t,r){const s=c`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!, $progressChannelId: String) {
559
559
  ExecuteRemoteOperation(input: { operationKey: $operationKey, inputJSON: $inputJSON, invokeMode: $invokeMode, progressChannelId: $progressChannelId }) {
560
560
  success
561
561
  resultCode
@@ -563,7 +563,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
563
563
  handle
564
564
  errorMessage
565
565
  }
566
- }`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.Subscribe(He,{channelId:n}).subscribe({next:u(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:u(()=>{},"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!) {
566
+ }`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.Subscribe(et,{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!) {
567
567
  MergeRecords(request: $request) {
568
568
  Success
569
569
  OverallStatus
@@ -580,34 +580,34 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
580
580
  Message
581
581
  }
582
582
  }
583
- }`,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}}}getDeniedReadFieldNamesForCurrentUser(e){return!e?.EnableFieldLevelSecurity||!this.CurrentUser?new Set:e.GetDeniedReadFields(this.CurrentUser)}fieldSecurityTransportSelection(e){return e?.EnableFieldLevelSecurity?_:""}ApplyServerFieldAccess(e,t){if(!t||typeof t!="object")return t;const r=t,s=r[_];if(delete r[_],Array.isArray(s)){const a=new Set(s.map(i=>String(i).trim().toLowerCase()));for(const i of e.Fields)a.has(i.Name.trim().toLowerCase())||(delete r[i.Name],delete r[i.CodeName]);return t}const n=this.getDeniedReadFieldNamesForCurrentUser(e);if(n.size===0)return t;for(const a of e.Fields)n.has(a.Name.trim().toLowerCase())&&(r[a.Name]===null&&delete r[a.Name],r[a.CodeName]===null&&delete r[a.CodeName]);return t}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new x;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 x;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(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const i=L(e.EntityInfo),o=`${a}${i}`,m=!e.IsSaved&&e.EntityInfo.IsChildType&&e.ISAParent?.IsSaved===!0,d=this.getDeniedReadFieldNamesForCurrentUser(e.EntityInfo),g=u(h=>d.has(h.trim().toLowerCase()),"isDeniedRead"),f=e.Fields.filter(h=>(!h.ReadOnly||h.IsPrimaryKey&&(e.IsSaved||m))&&(h.IsPrimaryKey||!h.NotLoaded&&!g(h.Name))),S=` ${o}(input: $input) {
584
- ${e.Fields.filter(h=>!g(h.Name)).map(h=>b.MapFieldName(h.CodeName)).join(`
583
+ }`,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 u(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}getDeniedReadFieldNamesForCurrentUser(e){return!e?.EnableFieldLevelSecurity||!this.CurrentUser?new Set:e.GetDeniedReadFields(this.CurrentUser)}fieldSecurityTransportSelection(e){return e?.EnableFieldLevelSecurity?V:""}ApplyServerFieldAccess(e,t){if(!t||typeof t!="object")return t;const r=t,s=r[V];if(delete r[V],Array.isArray(s)){const a=new Set(s.map(i=>String(i).trim().toLowerCase()));for(const i of e.Fields)a.has(i.Name.trim().toLowerCase())||(delete r[i.Name],delete r[i.CodeName]);return t}const n=this.getDeniedReadFieldNamesForCurrentUser(e);if(n.size===0)return t;for(const a of e.Fields)n.has(a.Name.trim().toLowerCase())&&(r[a.Name]===null&&delete r[a.Name],r[a.CodeName]===null&&delete r[a.CodeName]);return t}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new L;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 L;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(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const i=F(e.EntityInfo),o=`${a}${i}`,g=!e.IsSaved&&e.EntityInfo.IsChildType&&e.ISAParent?.IsSaved===!0,y=this.getDeniedReadFieldNamesForCurrentUser(e.EntityInfo),m=l(h=>y.has(h.trim().toLowerCase()),"isDeniedRead"),f=e.Fields.filter(h=>(!h.ReadOnly||h.IsPrimaryKey&&(e.IsSaved||g))&&(h.IsPrimaryKey||!h.NotLoaded&&!m(h.Name))),S=` ${o}(input: $input) {
584
+ ${e.Fields.filter(h=>!m(h.Name)).map(h=>N.MapFieldName(h.CodeName)).join(`
585
585
  `)}
586
586
  ${this.fieldSecurityTransportSelection(e.EntityInfo)}
587
587
  }`,E=c`mutation ${a}${i} ($input: ${o}Input!) {
588
588
  ${S}
589
589
  }
590
- `;for(let h=0;h<f.length;h++){const p=f[h];let R=e.Get(p.Name);if(R)switch(p.EntityFieldInfo.TSType){case A.Date:R=R.getTime();break;case A.Boolean:typeof R!="boolean"&&(R=parseInt(R)!==0);break;case A.Number:if(typeof R!="number"){const C=Number(R);isNaN(C)||(R=C)}break}R===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?R=p.EntityFieldInfo.DefaultValue:p.FieldType===A.Number||p.FieldType===A.Boolean?R=0:R=""),n.input[b.MapFieldName(p.CodeName)]=R}const D=e.RestoreContext;if(D&&(n.input.RestoreContext___={SourceChangeID:D.SourceChangeID,Reason:D.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const h=[];e.Fields.forEach(p=>{if(p.NotLoaded&&!p.IsPrimaryKey)return;let R=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===A.Date?R=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===A.Boolean?R=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?R=p.OldValue.toString():R=p.OldValue),h.push({Key:b.MapFieldName(p.CodeName),Value:R})}),n.input.OldValues___=h}if(e.TransactionGroup){const h=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new z(e,s.Type==="create"?"Create":"Update",S,n,{mutationName:o,mutationInputTypes:h},(p,R)=>{s.EndedAt=new Date,R&&p?(s.Success=!0,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(p))):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const h=await this.ExecuteGQL(E,n);if(h&&h[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(h[o])),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=ee(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,y(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let S=0;S<t.KeyValuePairs.length;S++){const E=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,D=t.GetValueByIndex(S),h=E.GraphQLType;i.length>0&&(i+=", "),i+=`$${E.CodeName}: ${h}!`,a.length>0&&(a+=", ");const p=E.CodeName.startsWith("__mj_")?E.CodeName.replace("__mj_","_mj__"):E.CodeName;if(a+=`${p}: $${E.CodeName}`,E.TSType===A.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${D} (${E.Name}) is not a valid number`);n[E.CodeName]=parseInt(D)}else n[E.CodeName]=D}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=L(e.EntityInfo),d=this.getDeniedReadFieldNamesForCurrentUser(e.EntityInfo),g=c`query Single${m}${o.length>0?"Full":""} (${i}) {
591
- ${m}(${a}) {
592
- ${e.Fields.filter(S=>!S.EntityFieldInfo.IsBinaryFieldType&&!d.has(S.Name.trim().toLowerCase())).map(S=>S.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?S.CodeName.replace("__mj_","_mj__"):S.CodeName).join(`
590
+ `;for(let h=0;h<f.length;h++){const p=f[h];let R=e.Get(p.Name);if(R)switch(p.EntityFieldInfo.TSType){case A.Date:R=R.getTime();break;case A.Boolean:typeof R!="boolean"&&(R=parseInt(R)!==0);break;case A.Number:if(typeof R!="number"){const C=Number(R);isNaN(C)||(R=C)}break}R===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?R=p.EntityFieldInfo.DefaultValue:p.FieldType===A.Number||p.FieldType===A.Boolean?R=0:R=""),n.input[N.MapFieldName(p.CodeName)]=R}const D=e.RestoreContext;if(D&&(n.input.RestoreContext___={SourceChangeID:D.SourceChangeID,Reason:D.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const h=[];e.Fields.forEach(p=>{if(p.NotLoaded&&!p.IsPrimaryKey)return;let R=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===A.Date?R=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===A.Boolean?R=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?R=p.OldValue.toString():R=p.OldValue),h.push({Key:N.MapFieldName(p.CodeName),Value:R})}),n.input.OldValues___=h}if(e.TransactionGroup){const h=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Y(e,s.Type==="create"?"Create":"Update",S,n,{mutationName:o,mutationInputTypes:h},(p,R)=>{s.EndedAt=new Date,R&&p?(s.Success=!0,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(p))):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const h=await this.ExecuteGQL(E,n);if(h&&h[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(h[o])),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=re(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,u(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let S=0;S<t.KeyValuePairs.length;S++){const E=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,D=t.GetValueByIndex(S),h=E.GraphQLType;i.length>0&&(i+=", "),i+=`$${E.CodeName}: ${h}!`,a.length>0&&(a+=", ");const p=E.CodeName.startsWith("__mj_")?E.CodeName.replace("__mj_","_mj__"):E.CodeName;if(a+=`${p}: $${E.CodeName}`,E.TSType===A.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${D} (${E.Name}) is not a valid number`);n[E.CodeName]=parseInt(D)}else n[E.CodeName]=D}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",g=F(e.EntityInfo),y=this.getDeniedReadFieldNamesForCurrentUser(e.EntityInfo),m=c`query Single${g}${o.length>0?"Full":""} (${i}) {
591
+ ${g}(${a}) {
592
+ ${e.Fields.filter(S=>!y.has(S.Name.trim().toLowerCase())).map(S=>S.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?S.CodeName.replace("__mj_","_mj__"):S.CodeName).join(`
593
593
  `)}
594
594
  ${this.fieldSecurityTransportSelection(e.EntityInfo)}
595
595
  ${o}
596
596
  }
597
597
  }
598
- `,f=await this.ExecuteGQL(g,n);return f&&f[m]?this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(f[m])):null}catch(n){return y(n),null}}ConvertBackToMJFields(e){return b.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+=`
598
+ `,f=await this.ExecuteGQL(m,n);return f&&f[g]?this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(f[g])):null}catch(n){return u(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+=`
599
599
  ${i} {
600
600
  ${a.Fields.map(o=>o.CodeName).join(`
601
601
  `)}
602
602
  }
603
- `}return r}async Delete(e,t,r){if(t?.IsParentEntityDelete){const n=new x;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type="delete",n.Success=!0,e.RegisterResultHistoryEntry(n),!0}const s=new x;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(E=>({FieldName:E.CodeName,Value:E.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",m="";for(let E of e.PrimaryKey.KeyValuePairs){const D=e.Fields.find(p=>p.Name.trim().toLowerCase()===E.FieldName.trim().toLowerCase());n[D.CodeName]=D.Value,a.push({varName:D.CodeName,inputType:D.EntityFieldInfo.GraphQLType+"!"});const h=D.CodeName.startsWith("__mj_")?D.CodeName.replace("__mj_","_mj__"):D.CodeName;i.length>0&&(i+=", "),i+=`${h}: $${D.CodeName}`,o.length>0&&(o+=", "),o+=`$${D.CodeName}: ${D.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
604
- `),m+=`${h}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1,SkipRecordChanges:t?.SkipRecordChanges??!1};const g="Delete"+L(e.EntityInfo),f=c`${g}(${i}, options___: $options___) {
605
- ${m}
603
+ `}return r}async Delete(e,t,r){if(t?.IsParentEntityDelete){const n=new L;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type="delete",n.Success=!0,e.RegisterResultHistoryEntry(n),!0}const s=new L;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(E=>({FieldName:E.CodeName,Value:E.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",g="";for(let E of e.PrimaryKey.KeyValuePairs){const D=e.Fields.find(p=>p.Name.trim().toLowerCase()===E.FieldName.trim().toLowerCase());n[D.CodeName]=D.Value,a.push({varName:D.CodeName,inputType:D.EntityFieldInfo.GraphQLType+"!"});const h=D.CodeName.startsWith("__mj_")?D.CodeName.replace("__mj_","_mj__"):D.CodeName;i.length>0&&(i+=", "),i+=`${h}: $${D.CodeName}`,o.length>0&&(o+=", "),o+=`$${D.CodeName}: ${D.EntityFieldInfo.GraphQLType}!`,g.length>0&&(g+=`
604
+ `),g+=`${h}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1,SkipRecordChanges:t?.SkipRecordChanges??!1};const m="Delete"+F(e.EntityInfo),f=c`${m}(${i}, options___: $options___) {
605
+ ${g}
606
606
  }
607
- `,S=c`mutation ${g} (${o}, $options___: DeleteOptionsInput!) {
607
+ `,S=c`mutation ${m} (${o}, $options___: DeleteOptionsInput!) {
608
608
  ${f}
609
609
  }
610
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new z(e,"Delete",f,n,{mutationName:g,mutationInputTypes:a},(E,D)=>{if(s.EndedAt=new Date,D&&E){let h=!0;for(const p of e.PrimaryKey.KeyValuePairs)p.Value!==E[p.FieldName]&&(h=!1);h?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const E=await this.ExecuteGQL(S,n);if(E&&E[g]){const D=E[g];for(let h of e.PrimaryKey.KeyValuePairs){let p=D[h.FieldName],R=h.Value;if(typeof R=="number"&&(R=R.toString()),typeof p=="number"&&(p=p.toString()),R!==p)throw new Error(`Primary key value mismatch in server Delete response. Field: ${h.FieldName}, Original: ${R}, Returned: ${p}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=ee(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,y(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
610
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Y(e,"Delete",f,n,{mutationName:m,mutationInputTypes:a},(E,D)=>{if(s.EndedAt=new Date,D&&E){let h=!0;for(const p of e.PrimaryKey.KeyValuePairs)p.Value!==E[p.FieldName]&&(h=!1);h?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const E=await this.ExecuteGQL(S,n);if(E&&E[m]){const D=E[m];for(let h of e.PrimaryKey.KeyValuePairs){let p=D[h.FieldName],R=h.Value;if(typeof R=="number"&&(R=R.toString()),typeof p=="number"&&(p=p.toString()),R!==p)throw new Error(`Primary key value mismatch in server Delete response. Field: ${h.FieldName}, Original: ${R}, Returned: ${p}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=re(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,u(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
611
611
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
612
612
  DatasetID
613
613
  DatasetName
@@ -625,7 +625,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
625
625
  LatestUpdateDate
626
626
  EntityUpdateDates
627
627
  }
628
- }`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(a=>({DatasetID:a.DatasetID,DatasetName:a.DatasetName,Success:a.Success,Status:a.Status,LatestUpdateDate:a.LatestUpdateDate?new Date(a.LatestUpdateDate):null,EntityUpdateDates:a.EntityUpdateDates?JSON.parse(a.EntityUpdateDates):null}));for(const a of e){const i=n.find(o=>o.DatasetName===a.datasetName);i?a.resolve(i):a.resolve({DatasetID:"",DatasetName:a.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){y(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const a=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(a)}catch(a){n.reject(a)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=c`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
628
+ }`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(a=>({DatasetID:a.DatasetID,DatasetName:a.DatasetName,Success:a.Success,Status:a.Status,LatestUpdateDate:a.LatestUpdateDate?new Date(a.LatestUpdateDate):null,EntityUpdateDates:a.EntityUpdateDates?JSON.parse(a.EntityUpdateDates):null}));for(const a of e){const i=n.find(o=>o.DatasetName===a.datasetName);i?a.resolve(i):a.resolve({DatasetID:"",DatasetName:a.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){u(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const a=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(a)}catch(a){n.reject(a)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=c`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
629
629
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
630
630
  DatasetID
631
631
  DatasetName
@@ -634,7 +634,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
634
634
  LatestUpdateDate
635
635
  EntityUpdateDates
636
636
  }
637
- }`,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 ae(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!) {
637
+ }`,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 ie(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!) {
638
638
  GetRecordFavoriteStatus(params: $params) {
639
639
  Success
640
640
  IsFavorite
@@ -643,7 +643,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
643
643
  SetRecordFavoriteStatus(params: $params){
644
644
  Success
645
645
  }
646
- }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=c`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
646
+ }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetCachedRecordName(e,t,r){const s=this._recordNames.Get(e,t);return!s&&r?this.GetEntityRecordName(e,t):s}HasCachedRecordName(e,t){return this._recordNames.Has(e,t)}GetCachedRecordNameOnlyIfCached(e,t){return this._recordNames.Get(e,t)}SetCachedRecordName(e,t,r){this._recordNames.Set(e,t,r)}async GetEntityRecordName(e,t,r,s=!1){return this._recordNames.GetOrFetch(e,t,s,()=>this.InternalGetEntityRecordName(e,t))}async GetEntityRecordNames(e,t,r=!1){return this._recordNames.GetOrFetchMany(e,r,s=>this.InternalGetEntityRecordNames(s))}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=c`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
647
647
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
648
648
  Success
649
649
  Status
@@ -662,28 +662,28 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
662
662
  EntityName
663
663
  RecordName
664
664
  }
665
- }`,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 H(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=c`query GetDataContextData ($DataContextID: String!) {
665
+ }`,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 X(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=c`query GetDataContextData ($DataContextID: String!) {
666
666
  GetDataContextData(DataContextID: $DataContextID) {
667
667
  Success
668
668
  ErrorMessages
669
669
  Results
670
670
  }
671
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw y(t),t}}async GetDataContextItemData(e){try{const t=c`query GetDataContextItemData ($DataContextItemID: String!) {
671
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u(t),t}}async GetDataContextItemData(e){try{const t=c`query GetDataContextItemData ($DataContextItemID: String!) {
672
672
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
673
673
  Success
674
674
  ErrorMessage
675
675
  Result
676
676
  }
677
- }`,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)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return I.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[d,g]of this._dynamicHeaders)m.setRequestHeader(d,g);m.upload&&r&&(m.upload.onprogress=d=>{if(d.lengthComputable&&d.total>0){const g=Math.min(100,Math.round(d.loaded/d.total*100));r({loaded:d.loaded,total:d.total,percent:g})}}),m.onload=async()=>{if(m.status>=200&&m.status<300)try{const d=JSON.parse(m.responseText);if(d.errors&&d.errors.length>0){const g=d.errors[0];if(g?.extensions?.code?.toUpperCase()?.trim()==="JWT_EXPIRED"&&s){await this.RefreshToken(),i(await this.ExecuteGQLWithProgress(e,t,r,!1));return}o(new Error(g.message||"GraphQL Error"))}else i(d.data)}catch(d){o(d)}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=q(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const a=le(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()})}static async clearClientCache(e=new Set){return this.ClearClientCache(e)}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 J(e,{headers:a});for(const[o,m]of this._dynamicHeaders)i.setHeader(o,m);return de.set(i,ye(e,t,s,n)),i}userInfoString(){return this.infoString(new W(null,null))}userRoleInfoString(){return this.infoString(new we(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
677
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return I.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 g=new XMLHttpRequest;g.open("POST",n),g.setRequestHeader("Content-Type","application/json"),this._sessionId&&g.setRequestHeader("x-session-id",this._sessionId),this._configData?.Token&&g.setRequestHeader("authorization","Bearer "+this._configData.Token),this._configData?.MJAPIKey&&g.setRequestHeader("x-mj-api-key",this._configData.MJAPIKey),this._configData?.UserAPIKey&&g.setRequestHeader("x-api-key",this._configData.UserAPIKey);for(const[y,m]of this._dynamicHeaders)g.setRequestHeader(y,m);g.upload&&r&&(g.upload.onprogress=y=>{if(y.lengthComputable&&y.total>0){const m=Math.min(100,Math.round(y.loaded/y.total*100));r({loaded:y.loaded,total:y.total,percent:m})}}),g.onload=async()=>{if(g.status>=200&&g.status<300)try{const y=JSON.parse(g.responseText);if(y.errors&&y.errors.length>0){const m=y.errors[0];if(m?.extensions?.code?.toUpperCase()?.trim()==="JWT_EXPIRED"&&s){await this.RefreshToken(),i(await this.ExecuteGQLWithProgress(e,t,r,!1));return}o(new Error(m.message||"GraphQL Error"))}else i(y.data)}catch(y){o(y)}else o(new Error(`HTTP error ${g.status}: ${g.statusText}`))},g.onerror=()=>o(new Error("Network error during request")),g.onabort=()=>o(new Error("Request aborted")),g.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=ye(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 u("JWT_EXPIRED and refreshTokenIfNeeded is false"),a}else throw a;else throw u(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()})}static async clearClientCache(e=new Set){return this.ClearClientCache(e)}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 H(e,{headers:a});for(const[o,g]of this._dynamicHeaders)i.setHeader(o,g);return ge.set(i,me(e,t,s,n)),i}userInfoString(){return this.infoString(new z(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__")+`
678
678
  `:s.startsWith("_")||(t+=s+`
679
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new ue:this._localStorageProvider=new $e),this._localStorageProvider}get Metadata(){return this}get SocketReconnected$(){return this._socketReconnectedSubject.asObservable()}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}get ActiveSubscriptionCount(){return this._activeSubscriptionCount}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();if(this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),!this._wsClient){this._isDisposingSocketIntentionally=!1;const t=Le({url:this.ConfigData.WSURL,connectionParams:u(()=>({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:Xe,connectionAckWaitTimeout:Ze,retryAttempts:3,shouldRetry:u(()=>!0,"shouldRetry")});this._wsClient=t,this._wsClientCreatedAt=e;let r=null;const s=u(()=>{r!==null&&(clearTimeout(r),r=null)},"disarmPongWatchdog");this._disarmPongWatchdog=s,t.on("ping",n=>{n||(s(),r=setTimeout(()=>{r=null;try{t.terminate()}catch{}},Ye))}),t.on("pong",n=>{n&&s()}),t.on("connected",(n,a,i)=>{this._socketStateSubject.next("connected"),i&&this._socketReconnectedSubject.next()}),t.on("closed",n=>{if(s(),this._wsClient!==t||this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),n?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))}return this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0,this._disarmPongWatchdog?.(),this._disarmPongWatchdog=null;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 T(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:u(a=>{r.next(a.data)},"next"),error:u(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:u(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}subscribe(e,t){return this.Subscribe(e,t)}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 m=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,m.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
679
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new de:this._localStorageProvider=new Ne),this._localStorageProvider}get Metadata(){return this}get SocketReconnected$(){return this._socketReconnectedSubject.asObservable()}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}get ActiveSubscriptionCount(){return this._activeSubscriptionCount}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();if(this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),!this._wsClient){this._isDisposingSocketIntentionally=!1;const t=_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:rt,connectionAckWaitTimeout:nt,retryAttempts:3,shouldRetry:l(()=>!0,"shouldRetry")});this._wsClient=t,this._wsClientCreatedAt=e;let r=null;const s=l(()=>{r!==null&&(clearTimeout(r),r=null)},"disarmPongWatchdog");this._disarmPongWatchdog=s,t.on("ping",n=>{n||(s(),r=setTimeout(()=>{r=null;try{t.terminate()}catch{}},st))}),t.on("pong",n=>{n&&s()}),t.on("connected",(n,a,i)=>{this._socketStateSubject.next("connected"),i&&this._socketReconnectedSubject.next()}),t.on("closed",n=>{if(s(),this._wsClient!==t||this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),n?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))}return this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0,this._disarmPongWatchdog?.(),this._disarmPongWatchdog=null;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 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()}})}subscribe(e,t){return this.Subscribe(e,t)}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 y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers>0&&y.activeSubscribers--,g.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
680
680
  statusUpdates(sessionId: $sessionId) {
681
681
  date
682
682
  message
683
683
  sessionId
684
684
  }
685
685
  }
686
- `,n=new V,a=this.getOrCreateWSClient(),i=new ne;return i.add(new T(o=>{const m=a.subscribe({query:s,variables:{sessionId:e}},{next:u(d=>{const g=this._pushStatusSubjects.get(e);g&&(g.lastEmissionAt=Date.now()),o.next(d.data.statusUpdates.message)},"next"),error:u(async d=>{const g=d;if(g?.extensions?.code==="JWT_EXPIRED"||g?.message?.includes("token has expired")||g?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(S){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",S),o.error(S)}}else o.error(d)},"error"),complete:u(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,m()}}).subscribe({next:u(o=>n.next(o),"next"),error:u(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:u(()=>{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 m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers++;const d=n.subscribe(o);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,d.unsubscribe()}})}TaskGraphFrames(e){const t=u(o=>new T(m=>{o.activeSubscribers++;const d=o.subject.subscribe(m);return()=>{d.unsubscribe();const g=this._taskGraphFrameStreams.get(e);g&&(g.activeSubscribers--,g.activeSubscribers<=0&&(g.subscription.unsubscribe(),g.subject.complete(),this._taskGraphFrameStreams.delete(e)))}}),"attachTo"),r=this._taskGraphFrameStreams.get(e);if(r)return t(r);const s=c`subscription TaskGraphFrames($parentTaskId: ID!) {
686
+ `,n=new O,a=this.getOrCreateWSClient(),i=new oe;return i.add(new T(o=>{const g=a.subscribe({query:s,variables:{sessionId:e}},{next:l(y=>{const m=this._pushStatusSubjects.get(e);m&&(m.lastEmissionAt=Date.now()),o.next(y.data.statusUpdates.message)},"next"),error:l(async y=>{const m=y;if(m?.extensions?.code==="JWT_EXPIRED"||m?.message?.includes("token has expired")||m?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(S){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",S),o.error(S)}}else o.error(y)},"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 y=n.subscribe(o);return()=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers>0&&m.activeSubscribers--,y.unsubscribe()}})}TaskGraphFrames(e){const t=l(o=>new T(g=>{o.activeSubscribers++;const y=o.subject.subscribe(g);return()=>{y.unsubscribe();const m=this._taskGraphFrameStreams.get(e);m&&(m.activeSubscribers--,m.activeSubscribers<=0&&(m.subscription.unsubscribe(),m.subject.complete(),this._taskGraphFrameStreams.delete(e)))}}),"attachTo"),r=this._taskGraphFrameStreams.get(e);if(r)return t(r);const s=c`subscription TaskGraphFrames($parentTaskId: ID!) {
687
687
  taskGraphFrames(parentTaskId: $parentTaskId) {
688
688
  kind
689
689
  parentTaskId
@@ -711,7 +711,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
711
711
  progressPercent
712
712
  date
713
713
  }
714
- }`,n=new V,a=new ne;a.add(this.Subscribe(s,{parentTaskId:e}).subscribe({next:u(o=>{o?.taskGraphFrames&&n.next(o.taskGraphFrames)},"next"),error:u(o=>{n.error(o),this._taskGraphFrameStreams.delete(e)},"error"),complete:u(()=>{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()}disposeWebSocketResources(){return this.DisposeWebSocketResources()}ClientToolRequests(e){return this.Subscribe(`
714
+ }`,n=new O,a=new oe;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()}disposeWebSocketResources(){return this.DisposeWebSocketResources()}ClientToolRequests(e){return this.Subscribe(`
715
715
  subscription ClientToolRequest($sessionID: String!) {
716
716
  ClientToolRequest(sessionID: $sessionID) {
717
717
  AgentRunID
@@ -733,19 +733,19 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
733
733
  OriginSessionID
734
734
  RecordData
735
735
  }
736
- }`,t=this.Subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:u(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}};te.Instance.RaiseEvent({event:re.ComponentEvent,eventCode:Pe.BaseEventCode,args:n,component:this})},"next"),error:u(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:u(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}static{this.ClientMemberRefreshWindowMinMs=15e3}static{this.ClientMemberRefreshWindowJitterMs=3e4}get MetadataMemberRefreshDelayMs(){return I.ClientMemberRefreshWindowMinMs+Math.random()*I.ClientMemberRefreshWindowJitterMs}get MetadataMemberRefreshRearmsOnNewEvents(){return!1}async RefreshAfterMetadataMemberChange(){return this.RefreshIfNeeded(void 0,!0)}UnsubscribeFromCacheInvalidation(){this.CancelPendingMetadataMemberRefresh(),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!) {
736
+ }`,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}};se.Instance.RaiseEvent({event:ne.ComponentEvent,eventCode:be.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")})}static{this.ClientMemberRefreshWindowMinMs=15e3}static{this.ClientMemberRefreshWindowJitterMs=3e4}get MetadataMemberRefreshDelayMs(){return I.ClientMemberRefreshWindowMinMs+Math.random()*I.ClientMemberRefreshWindowJitterMs}get MetadataMemberRefreshRearmsOnNewEvents(){return!1}async RefreshAfterMetadataMemberChange(){return this.RefreshIfNeeded(void 0,!0)}UnsubscribeFromCacheInvalidation(){this.CancelPendingMetadataMemberRefresh(),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!) {
737
737
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
738
738
  Success
739
739
  ChildEntityName
740
740
  ErrorMessage
741
741
  }
742
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return y(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
742
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return u(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
743
743
  FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
744
744
  Success
745
745
  ChildEntityNames
746
746
  ErrorMessage
747
747
  }
748
- }`;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 me(l){const e=new I;if(X(e),await e.Config(l),await e.preValidateAndRefresh(),e.Entities.length===0){const t=`SetupGraphQLClient: no entity metadata was loaded from ${l.URL} \u2014 the metadata download failed or returned nothing`,r=e.LastMetadataLoadError;throw r?new Error(`${t}: ${r.message}`,{cause:r}):new Error(`${t}; see the logged GetAllMetadata error`)}return te.Instance.RaiseEvent({event:re.LoggedIn,eventCode:null,component:this,args:null}),await be.Instance.Startup(),e}u(me,"SetupGraphQLClient");async function et(l){const e=new I;if(e.Entities.length>0)return e;X(e);try{await e.Connect(l)}catch(t){const r=t instanceof Error?t:new Error(String(t)),s=new Error(`ConnectGraphQLClient: connecting to ${l.URL} failed: ${r.message}`,{cause:r});throw y(s.message),s}return e}u(et,"ConnectGraphQLClient");async function tt(l){return me(l)}u(tt,"setupGraphQLClient");class rt{static{u(this,"SyncRolesAndUsersResult")}}class st{static{u(this,"RoleInput")}}class nt{static{u(this,"UserInput")}}class at{static{u(this,"RolesAndUsersInput")}}var ge=(l=>(l.Create="Create",l.Update="Update",l.CreateOrUpdate="CreateOrUpdate",l.Delete="Delete",l.DeleteWithFilter="DeleteWithFilter",l))(ge||{});class ot{static{u(this,"ActionItemInput")}}class it{static{u(this,"SyncDataResult")}constructor(){this.Results=[]}}class ct{static{u(this,"ActionItemOutput")}}const Se=`Success
748
+ }`;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 u(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Se(d){const e=new I;if(Z(e),await e.Config(d),await e.preValidateAndRefresh(),e.Entities.length===0){const t=`SetupGraphQLClient: no entity metadata was loaded from ${d.URL} \u2014 the metadata download failed or returned nothing`,r=e.LastMetadataLoadError;throw r?new Error(`${t}: ${r.message}`,{cause:r}):new Error(`${t}; see the logged GetAllMetadata error`)}return se.Instance.RaiseEvent({event:ne.LoggedIn,eventCode:null,component:this,args:null}),await xe.Instance.Startup(),e}l(Se,"SetupGraphQLClient");async function at(d){const e=new I;if(e.Entities.length>0)return e;Z(e);try{await e.Connect(d)}catch(t){const r=t instanceof Error?t:new Error(String(t)),s=new Error(`ConnectGraphQLClient: connecting to ${d.URL} failed: ${r.message}`,{cause:r});throw u(s.message),s}return e}l(at,"ConnectGraphQLClient");async function ot(d){return Se(d)}l(ot,"setupGraphQLClient");class it{static{l(this,"SyncRolesAndUsersResult")}}class ct{static{l(this,"RoleInput")}}class ut{static{l(this,"UserInput")}}class lt{static{l(this,"RolesAndUsersInput")}}var pe=(d=>(d.Create="Create",d.Update="Update",d.CreateOrUpdate="CreateOrUpdate",d.Delete="Delete",d.DeleteWithFilter="DeleteWithFilter",d))(pe||{});class dt{static{l(this,"ActionItemInput")}}class yt{static{l(this,"SyncDataResult")}constructor(){this.Results=[]}}class gt{static{l(this,"ActionItemOutput")}}const he=`Success
749
749
  ErrorMessage
750
750
  Query {
751
751
  ID
@@ -800,14 +800,14 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
800
800
  QueryID
801
801
  RoleID
802
802
  Role
803
- }`;class ut{static{u(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 J(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return Ne(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
803
+ }`;class mt{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 H(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return Te(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
804
804
  GetData(input: $input) {
805
805
  Success
806
806
  ErrorMessages
807
807
  Queries
808
808
  Results
809
809
  }
810
- }`,{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]+"."),Ae()){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 {
810
+ }`,{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]+"."),Le()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
811
811
  GetAllEntities {
812
812
  Success
813
813
  ErrorMessage
@@ -830,7 +830,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
830
830
  }
831
831
  }
832
832
  }
833
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return y(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
833
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
834
834
  SyncData(items: $items) {
835
835
  Success
836
836
  Results {
@@ -854,11 +854,11 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
854
854
  RecordJSON
855
855
  }
856
856
  }
857
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return y(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
857
+ }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return u(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
858
858
  SyncRolesAndUsers(data: $data) {
859
859
  Success
860
860
  }
861
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return y(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
861
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
862
862
  RunViewByNameSystemUser(input: $input) {
863
863
  Results {
864
864
  PrimaryKey {
@@ -875,7 +875,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
875
875
  ErrorMessage
876
876
  Success
877
877
  }
878
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return y(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
878
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
879
879
  RunViewByIDSystemUser(input: $input) {
880
880
  Results {
881
881
  PrimaryKey {
@@ -892,7 +892,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
892
892
  ErrorMessage
893
893
  Success
894
894
  }
895
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return y(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
895
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
896
896
  RunDynamicViewSystemUser(input: $input) {
897
897
  Results {
898
898
  PrimaryKey {
@@ -909,7 +909,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
909
909
  ErrorMessage
910
910
  Success
911
911
  }
912
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return y(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
912
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
913
913
  RunViewsSystemUser(input: $input) {
914
914
  Results {
915
915
  PrimaryKey {
@@ -926,7 +926,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
926
926
  ErrorMessage
927
927
  Success
928
928
  }
929
- }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return y(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
929
+ }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return u(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
930
930
  GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
931
931
  QueryID
932
932
  QueryName
@@ -938,7 +938,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
938
938
  ErrorMessage
939
939
  AppliedParameters
940
940
  }
941
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?v(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return y(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
941
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?v(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
942
942
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
943
943
  QueryID
944
944
  QueryName
@@ -950,22 +950,22 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
950
950
  ErrorMessage
951
951
  AppliedParameters
952
952
  }
953
- }`,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!) {
953
+ }`,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 u(`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!) {
954
954
  CreateQueryExtended(input: $input) {
955
- ${Se}
955
+ ${he}
956
956
  }
957
- }`,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!) {
957
+ }`,r=await this.Client.request(t,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return u(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const t=`mutation UpdateQueryExtended($input: UpdateQuerySystemUserInput!) {
958
958
  UpdateQueryExtended(input: $input) {
959
- ${Se}
959
+ ${he}
960
960
  }
961
- }`,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) {
961
+ }`,r=await this.Client.request(t,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return u(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return u("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) {
962
962
  DeleteQueryExtended(ID: $ID, options: $options) {
963
963
  Success
964
964
  ErrorMessage
965
965
  ID
966
966
  Name
967
967
  }
968
- }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1,SkipRecordChanges:t.SkipRecordChanges??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQueryExtended?n.DeleteQueryExtended:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return y(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=c`
968
+ }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1,SkipRecordChanges:t.SkipRecordChanges??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQueryExtended?n.DeleteQueryExtended:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return u(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=c`
969
969
  query RunAIPromptSystemUser(
970
970
  $promptId: String!,
971
971
  $data: String,
@@ -1024,7 +1024,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1024
1024
  chatResult
1025
1025
  }
1026
1026
  }
1027
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return y(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=c`
1027
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=c`
1028
1028
  query RunAIAgentSystemUser(
1029
1029
  $agentId: String!,
1030
1030
  $messages: String!,
@@ -1051,7 +1051,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1051
1051
  result
1052
1052
  }
1053
1053
  }
1054
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return y(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return v(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
1054
+ `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return v(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
1055
1055
  TestQuerySQL(input: $input) {
1056
1056
  Success
1057
1057
  Results
@@ -1060,7 +1060,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1060
1060
  ErrorMessage
1061
1061
  AppliedParameters
1062
1062
  }
1063
- }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?v(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?v(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return y(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=c`
1063
+ }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?v(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?v(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return u(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=c`
1064
1064
  query ExecuteSimplePromptSystemUser(
1065
1065
  $systemPrompt: String!,
1066
1066
  $messages: String,
@@ -1083,7 +1083,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1083
1083
  executionTimeMs
1084
1084
  }
1085
1085
  }
1086
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return y(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=c`
1086
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=c`
1087
1087
  query EmbedTextSystemUser(
1088
1088
  $textToEmbed: [String!]!,
1089
1089
  $modelSize: String!
@@ -1098,7 +1098,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1098
1098
  error
1099
1099
  }
1100
1100
  }
1101
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return y(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=c`
1101
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return u(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=c`
1102
1102
  mutation SearchKnowledgeAsSystemUser($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
1103
1103
  SearchKnowledgeAsSystemUser(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
1104
1104
  Success
@@ -1145,7 +1145,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1145
1145
  ErrorMessage
1146
1146
  }
1147
1147
  }
1148
- `,r={query:e.Query};if(e.MaxResults!==void 0&&(r.maxResults=e.MaxResults),e.MinScore!==void 0&&(r.minScore=e.MinScore),e.Filters!==void 0){const n={};e.Filters.EntityNames?.length&&(n.EntityNames=e.Filters.EntityNames),e.Filters.SourceTypes?.length&&(n.SourceTypes=e.Filters.SourceTypes),e.Filters.Tags?.length&&(n.Tags=e.Filters.Tags),r.filters=n}const s=await this.Client.request(t,r);return s?.SearchKnowledgeAsSystemUser?this.mapSearchResponse(s.SearchKnowledgeAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return y(`GraphQLSystemUserClient::SearchKnowledge - Error executing search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}async PreviewSearch(e){try{const t=c`
1148
+ `,r={query:e.Query};if(e.MaxResults!==void 0&&(r.maxResults=e.MaxResults),e.MinScore!==void 0&&(r.minScore=e.MinScore),e.Filters!==void 0){const n={};e.Filters.EntityNames?.length&&(n.EntityNames=e.Filters.EntityNames),e.Filters.SourceTypes?.length&&(n.SourceTypes=e.Filters.SourceTypes),e.Filters.Tags?.length&&(n.Tags=e.Filters.Tags),r.filters=n}const s=await this.Client.request(t,r);return s?.SearchKnowledgeAsSystemUser?this.mapSearchResponse(s.SearchKnowledgeAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return u(`GraphQLSystemUserClient::SearchKnowledge - Error executing search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}async PreviewSearch(e){try{const t=c`
1149
1149
  mutation PreviewSearchAsSystemUser($query: String!, $maxResults: Float) {
1150
1150
  PreviewSearchAsSystemUser(query: $query, maxResults: $maxResults) {
1151
1151
  Success
@@ -1192,7 +1192,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1192
1192
  ErrorMessage
1193
1193
  }
1194
1194
  }
1195
- `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return y(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),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}}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}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}async CheckEntityPermissionsSystemUser(e,t){try{const r=c`
1195
+ `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return u(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),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}}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}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}async CheckEntityPermissionsSystemUser(e,t){try{const r=c`
1196
1196
  query CheckEntityPermissionsSystemUser($EntityNames: [String!]!, $UserEmail: String!) {
1197
1197
  CheckEntityPermissionsSystemUser(EntityNames: $EntityNames, UserEmail: $UserEmail) {
1198
1198
  Success
@@ -1203,7 +1203,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1203
1203
  ErrorMessage
1204
1204
  }
1205
1205
  }
1206
- `,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 lt{static{u(this,"GetDataOutput")}}class dt{static{u(this,"SimpleRemoteEntityOutput")}}class yt{static{u(this,"SimpleRemoteEntity")}}class mt{static{u(this,"SimpleRemoteEntityField")}}class gt{static{u(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`
1206
+ `,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 u(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class St{static{l(this,"GetDataOutput")}}class pt{static{l(this,"SimpleRemoteEntityOutput")}}class ht{static{l(this,"SimpleRemoteEntity")}}class It{static{l(this,"SimpleRemoteEntityField")}}class ft{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`
1207
1207
  mutation RunAction($input: RunActionInput!) {
1208
1208
  RunAction(input: $input) {
1209
1209
  Success
@@ -1212,7 +1212,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1212
1212
  ResultData
1213
1213
  }
1214
1214
  }
1215
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){y(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return y(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=c`
1215
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=c`
1216
1216
  mutation RunEntityAction($input: EntityActionInput!) {
1217
1217
  RunEntityAction(input: $input) {
1218
1218
  Success
@@ -1220,63 +1220,63 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1220
1220
  ResultData
1221
1221
  }
1222
1222
  }
1223
- `;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{u(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1223
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Et{static{l(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1224
1224
  query PreviewListDelta($input: ComputeDeltaInput!) {
1225
1225
  PreviewListDelta(input: $input) {
1226
1226
  ...ListDeltaFields
1227
1227
  }
1228
1228
  }
1229
- ${pe}
1230
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:j(e.Source),Mode:e.Mode}});return he(r?.PreviewListDelta)}async ApplyListDelta(e){const t=c`
1229
+ ${Ie}
1230
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:J(e.Source),Mode:e.Mode}});return fe(r?.PreviewListDelta)}async ApplyListDelta(e){const t=c`
1231
1231
  mutation ApplyListDelta($input: ApplyDeltaInput!) {
1232
1232
  ApplyListDelta(input: $input) {
1233
1233
  ...ApplyResultFields
1234
1234
  }
1235
1235
  }
1236
1236
  ${U}
1237
- `,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`
1237
+ `,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 _(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=c`
1238
1238
  mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
1239
1239
  MaterializeListFromView(viewId: $viewId, options: $options) {
1240
1240
  ...ApplyResultFields
1241
1241
  }
1242
1242
  }
1243
1243
  ${U}
1244
- `,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`
1244
+ `,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 _(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=c`
1245
1245
  mutation AddViewResultsToList($viewId: String!, $listId: String!) {
1246
1246
  AddViewResultsToList(viewId: $viewId, listId: $listId) {
1247
1247
  ...ApplyResultFields
1248
1248
  }
1249
1249
  }
1250
1250
  ${U}
1251
- `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return Q(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1251
+ `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return _(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1252
1252
  mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
1253
1253
  RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
1254
1254
  ...ApplyResultFields
1255
1255
  }
1256
1256
  }
1257
1257
  ${U}
1258
- `,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`
1258
+ `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return _(r?.RefreshListFromSource)}async ComposeLists(e){const t=c`
1259
1259
  mutation ComposeLists($input: ComposeListsInput!) {
1260
1260
  ComposeLists(input: $input) {
1261
1261
  ...ListDeltaFields
1262
1262
  }
1263
1263
  }
1264
- ${pe}
1265
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(j),Target:e.Target?j(e.Target):null}});return he(r?.ComposeLists)}async Share(e){const t=c`
1264
+ ${Ie}
1265
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(J),Target:e.Target?J(e.Target):null}});return fe(r?.ComposeLists)}async Share(e){const t=c`
1266
1266
  mutation ShareList($input: ShareListInput!) {
1267
1267
  ShareList(input: $input) {
1268
1268
  ...ShareResultFields
1269
1269
  }
1270
1270
  }
1271
- ${K}
1272
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:pt(e.Target),PermissionLevel:e.PermissionLevel}});return B(r?.ShareList)}async Unshare(e){const t=c`
1271
+ ${B}
1272
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Rt(e.Target),PermissionLevel:e.PermissionLevel}});return j(r?.ShareList)}async Unshare(e){const t=c`
1273
1273
  mutation UnshareList($permissionId: String!) {
1274
1274
  UnshareList(permissionId: $permissionId) {
1275
1275
  ...ShareResultFields
1276
1276
  }
1277
1277
  }
1278
- ${K}
1279
- `,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return B(r?.UnshareList)}async Invite(e){const t=c`
1278
+ ${B}
1279
+ `,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return j(r?.UnshareList)}async Invite(e){const t=c`
1280
1280
  mutation InviteToList($input: InviteToListInput!) {
1281
1281
  InviteToList(input: $input) {
1282
1282
  Success
@@ -1303,8 +1303,8 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1303
1303
  ...ShareResultFields
1304
1304
  }
1305
1305
  }
1306
- ${K}
1307
- `,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return B(r?.RevokeListInvitation)}async GetSharesForList(e){const t=c`
1306
+ ${B}
1307
+ `,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return j(r?.RevokeListInvitation)}async GetSharesForList(e){const t=c`
1308
1308
  query ListSharesForList($listId: String!) {
1309
1309
  ListSharesForList(listId: $listId) {
1310
1310
  PermissionID
@@ -1320,7 +1320,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1320
1320
  CreatedAt
1321
1321
  }
1322
1322
  }
1323
- `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(ht)}async ListsSharedWithMe(){const e=c`
1323
+ `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Dt)}async ListsSharedWithMe(){const e=c`
1324
1324
  query ListsSharedWithMe {
1325
1325
  ListsSharedWithMe {
1326
1326
  ListID
@@ -1330,7 +1330,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1330
1330
  SharedAt
1331
1331
  }
1332
1332
  }
1333
- `;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 pe=c`
1333
+ `;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 Ie=c`
1334
1334
  fragment ListDeltaFields on ListDeltaType {
1335
1335
  TargetListId
1336
1336
  EntityName
@@ -1363,14 +1363,14 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1363
1363
  FailedCount
1364
1364
  Errors
1365
1365
  }
1366
- `,K=c`
1366
+ `,B=c`
1367
1367
  fragment ShareResultFields on ShareResultType {
1368
1368
  Success
1369
1369
  ResultCode
1370
1370
  Message
1371
1371
  PermissionID
1372
1372
  }
1373
- `;function pt(l){return l.kind==="user"?{Kind:"user",UserID:l.userId}:{Kind:"role",RoleID:l.roleId}}u(pt,"serializeShareTarget");function B(l){if(!l||typeof l!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=l;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}u(B,"parseShareResult");function ht(l){const e=l,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)}}u(ht,"parseShareSummary");function j(l){switch(l.kind){case"list":return{Kind:"list",ListID:l.listId};case"view":return{Kind:"view",ViewID:l.viewId};case"adhoc":return{Kind:"adhoc",EntityName:l.entityName,ExtraFilter:l.extraFilter}}}u(j,"serializeListSource");function he(l){if(!l||typeof l!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=l;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(It),DeltaToken:e.DeltaToken}}u(he,"parseListDelta");function It(l){let e;if(l.DetailsJSON)try{e=JSON.parse(l.DetailsJSON)}catch(t){y(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:l.Code,Message:l.Message,Details:e}}u(It,"parseWarning");function Q(l){if(!l||typeof l!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=l;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}}u(Q,"parseApplyResult");class ft{static{u(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`
1373
+ `;function Rt(d){return d.kind==="user"?{Kind:"user",UserID:d.userId}:{Kind:"role",RoleID:d.roleId}}l(Rt,"serializeShareTarget");function j(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(j,"parseShareResult");function Dt(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(Dt,"parseShareSummary");function J(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(J,"serializeListSource");function fe(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(vt),DeltaToken:e.DeltaToken}}l(fe,"parseListDelta");function vt(d){let e;if(d.DetailsJSON)try{e=JSON.parse(d.DetailsJSON)}catch(t){u(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:d.Code,Message:d.Message,Details:e}}l(vt,"parseWarning");function _(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(_,"parseApplyResult");class Ct{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`
1374
1374
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1375
1375
  CreateAPIKey(input: $input) {
1376
1376
  Success
@@ -1379,14 +1379,14 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1379
1379
  Error
1380
1380
  }
1381
1381
  }
1382
- `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return y(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=c`
1382
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return u(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=c`
1383
1383
  mutation RevokeAPIKey($apiKeyId: String!) {
1384
1384
  RevokeAPIKey(apiKeyId: $apiKeyId) {
1385
1385
  Success
1386
1386
  Error
1387
1387
  }
1388
1388
  }
1389
- `,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 Et{static{u(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1389
+ `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class wt{static{l(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1390
1390
  mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1391
1391
  RunClusterAnalysis(input: $input) {
1392
1392
  Success
@@ -1402,7 +1402,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1402
1402
  AnalysisID
1403
1403
  }
1404
1404
  }
1405
- `,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 Rt{static{u(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
1405
+ `,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 u("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 $t{static{l(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
1406
1406
  mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1407
1407
  MintLiveKitClientToken(input: $input) {
1408
1408
  Success
@@ -1413,7 +1413,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1413
1413
  RoomName
1414
1414
  }
1415
1415
  }
1416
- `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.MintLiveKitClientToken;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return y("GraphQLLiveKitClient.MintClientToken failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",ServerUrl:"",Token:"",Identity:"",RoomName:e.RoomName}}}async StartAgentRoomSession(e){try{const t=c`
1416
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.MintLiveKitClientToken;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return u("GraphQLLiveKitClient.MintClientToken failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",ServerUrl:"",Token:"",Identity:"",RoomName:e.RoomName}}}async StartAgentRoomSession(e){try{const t=c`
1417
1417
  mutation StartLiveKitAgentRoomSession($input: StartLiveKitAgentRoomSessionInput!) {
1418
1418
  StartLiveKitAgentRoomSession(input: $input) {
1419
1419
  Success
@@ -1425,19 +1425,27 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1425
1425
  Identity
1426
1426
  }
1427
1427
  }
1428
- `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.StartLiveKitAgentRoomSession;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return y("GraphQLLiveKitClient.StartAgentRoomSession failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",SessionBridgeID:"",RoomName:"",ServerUrl:"",ClientToken:"",Identity:""}}}async StopAgentRoomSession(e){try{const t=c`
1428
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.StartLiveKitAgentRoomSession;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return u("GraphQLLiveKitClient.StartAgentRoomSession failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",SessionBridgeID:"",RoomName:"",ServerUrl:"",ClientToken:"",Identity:""}}}async StopAgentRoomSession(e){try{const t=c`
1429
1429
  mutation StopLiveKitAgentRoomSession($sessionBridgeID: String!) {
1430
1430
  StopLiveKitAgentRoomSession(sessionBridgeID: $sessionBridgeID)
1431
1431
  }
1432
- `;return(await this._dataProvider.ExecuteGQL(t,{sessionBridgeID:e}))?.StopLiveKitAgentRoomSession===!0}catch(t){return y("GraphQLLiveKitClient.StopAgentRoomSession failed",void 0,t),!1}}async EndRoom(e){try{const t=c`
1432
+ `;return(await this._dataProvider.ExecuteGQL(t,{sessionBridgeID:e}))?.StopLiveKitAgentRoomSession===!0}catch(t){return u("GraphQLLiveKitClient.StopAgentRoomSession failed",void 0,t),!1}}async EndRoom(e){try{const t=c`
1433
1433
  mutation EndLiveKitRoom($roomName: String!) {
1434
1434
  EndLiveKitRoom(roomName: $roomName)
1435
1435
  }
1436
- `;return(await this._dataProvider.ExecuteGQL(t,{roomName:e}))?.EndLiveKitRoom===!0}catch(t){return y("GraphQLLiveKitClient.EndRoom failed",void 0,t),!1}}async InviteUsers(e,t){try{const r=c`
1436
+ `;return(await this._dataProvider.ExecuteGQL(t,{roomName:e}))?.EndLiveKitRoom===!0}catch(t){return u("GraphQLLiveKitClient.EndRoom failed",void 0,t),!1}}async InviteUsers(e,t){try{const r=c`
1437
1437
  mutation InviteUsersToLiveKitRoom($roomName: String!, $userIDs: [String!]!) {
1438
1438
  InviteUsersToLiveKitRoom(roomName: $roomName, userIDs: $userIDs)
1439
1439
  }
1440
- `;return(await this._dataProvider.ExecuteGQL(r,{roomName:e,userIDs:t}))?.InviteUsersToLiveKitRoom===!0}catch(r){return y("GraphQLLiveKitClient.InviteUsers failed",void 0,r),!1}}async GetRealtimeModelVoices(){try{const e=c`
1440
+ `;return(await this._dataProvider.ExecuteGQL(r,{roomName:e,userIDs:t}))?.InviteUsersToLiveKitRoom===!0}catch(r){return u("GraphQLLiveKitClient.InviteUsers failed",void 0,r),!1}}async GetRoomTurnState(e){try{const t=c`
1441
+ query GetLiveKitRoomTurnState($roomName: String!) {
1442
+ GetLiveKitRoomTurnState(roomName: $roomName) {
1443
+ Success
1444
+ ErrorMessage
1445
+ StateJSON
1446
+ }
1447
+ }
1448
+ `,s=(await this._dataProvider.ExecuteGQL(t,{roomName:e}))?.GetLiveKitRoomTurnState;if(!s)throw new Error("Invalid response from server");const n=s.StateJSON?JSON.parse(s.StateJSON):null;return{Success:s.Success,ErrorMessage:s.ErrorMessage,State:s.Success?n:null}}catch(t){const r=t;return u("GraphQLLiveKitClient.GetRoomTurnState failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",State:null}}}async GetRealtimeModelVoices(){try{const e=c`
1441
1449
  query GetRealtimeModelVoices {
1442
1450
  GetRealtimeModelVoices {
1443
1451
  ModelID
@@ -1448,7 +1456,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1448
1456
  }
1449
1457
  }
1450
1458
  }
1451
- `;return(await this._dataProvider.ExecuteGQL(e,{}))?.GetRealtimeModelVoices??[]}catch(e){return y("GraphQLLiveKitClient.GetRealtimeModelVoices failed",void 0,e),[]}}async StartRecording(e,t){return this.runRecordingMutation(c`
1459
+ `;return(await this._dataProvider.ExecuteGQL(e,{}))?.GetRealtimeModelVoices??[]}catch(e){return u("GraphQLLiveKitClient.GetRealtimeModelVoices failed",void 0,e),[]}}async StartRecording(e,t){return this.runRecordingMutation(c`
1452
1460
  mutation StartLiveKitRecording($input: LiveKitRecordingInput!) {
1453
1461
  StartLiveKitRecording(input: $input) {
1454
1462
  Success
@@ -1467,7 +1475,51 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1467
1475
  RecordingFileID
1468
1476
  }
1469
1477
  }
1470
- `,{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 Dt{static{u(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1478
+ `,{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 u(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}const W=`
1479
+ OfferID
1480
+ RoomName
1481
+ Mode
1482
+ Summary
1483
+ CallerLabel
1484
+ AgentName
1485
+ Status
1486
+ CreatedAt
1487
+ ExpiresAt
1488
+ InteractionID
1489
+ `;class Pt{static{l(this,"GraphQLHandoffClient")}constructor(e){this._dataProvider=e}async GetMyOffers(){try{const e=c`
1490
+ query MyHandoffOffers {
1491
+ MyHandoffOffers {
1492
+ ${W}
1493
+ }
1494
+ }
1495
+ `;return(await this._dataProvider.ExecuteGQL(e,{}))?.MyHandoffOffers??[]}catch(e){return u("GraphQLHandoffClient.GetMyOffers failed",void 0,e),[]}}async AcceptOffer(e){try{const t=c`
1496
+ mutation AcceptHandoffOffer($offerID: String!) {
1497
+ AcceptHandoffOffer(offerID: $offerID) {
1498
+ Success
1499
+ ErrorMessage
1500
+ RoomName
1501
+ Offer {
1502
+ ${W}
1503
+ }
1504
+ }
1505
+ }
1506
+ `,s=(await this._dataProvider.ExecuteGQL(t,{offerID:e}))?.AcceptHandoffOffer;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return u("GraphQLHandoffClient.AcceptOffer failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",RoomName:""}}}async DeclineOffer(e){try{const t=c`
1507
+ mutation DeclineHandoffOffer($offerID: String!) {
1508
+ DeclineHandoffOffer(offerID: $offerID) {
1509
+ Success
1510
+ ErrorMessage
1511
+ }
1512
+ }
1513
+ `,s=(await this._dataProvider.ExecuteGQL(t,{offerID:e}))?.DeclineHandoffOffer;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return u("GraphQLHandoffClient.DeclineOffer failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}ObserveOfferChanges(){const e=c`
1514
+ subscription HandoffOfferChanges {
1515
+ HandoffOfferChanges {
1516
+ Kind
1517
+ Offer {
1518
+ ${W}
1519
+ }
1520
+ }
1521
+ }
1522
+ `;return this._dataProvider.Subscribe(e).pipe(Qe(t=>t?.HandoffOfferChanges),Ue(t=>t!=null))}}class Mt{static{l(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1471
1523
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1472
1524
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1473
1525
  Success
@@ -1477,11 +1529,11 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1477
1529
  NodesJSON
1478
1530
  }
1479
1531
  }
1480
- `,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 vt{static{u(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:u(n=>n?.success===!0,"validateAck"),isCompletionEvent:u(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:u(n=>this.extractTestResult(n),"extractResult"),onMessage:u(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:u(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:u(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:u(s=>s?.success===!0,"validateAck"),isCompletionEvent:u(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:u(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:u(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1532
+ `,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 u("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 Nt{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`
1481
1533
  query IsTestRunning($testId: String!) {
1482
1534
  IsTestRunning(testId: $testId)
1483
1535
  }
1484
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return y(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return c`
1536
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return c`
1485
1537
  mutation RunTest(
1486
1538
  $testId: String!,
1487
1539
  $verbose: Boolean,
@@ -1535,7 +1587,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1535
1587
  result
1536
1588
  }
1537
1589
  }
1538
- `}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 Ct{static{u(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1590
+ `}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 u(`${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 bt{static{l(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1539
1591
  query GetRegistryComponent(
1540
1592
  $registryName: String!,
1541
1593
  $namespace: String!,
@@ -1556,7 +1608,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1556
1608
  specification
1557
1609
  }
1558
1610
  }
1559
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return y(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw y(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=c`
1611
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return u(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw u(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=c`
1560
1612
  query GetRegistryComponent(
1561
1613
  $registryName: String!,
1562
1614
  $namespace: String!,
@@ -1577,7 +1629,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1577
1629
  specification
1578
1630
  }
1579
1631
  }
1580
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){y(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw y(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=c`
1632
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){u(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=c`
1581
1633
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
1582
1634
  SearchRegistryComponents(params: $params) {
1583
1635
  components
@@ -1586,7 +1638,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1586
1638
  limit
1587
1639
  }
1588
1640
  }
1589
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw y(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=c`
1641
+ `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=c`
1590
1642
  query ResolveComponentDependencies(
1591
1643
  $registryId: String!,
1592
1644
  $componentId: String!
@@ -1611,7 +1663,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1611
1663
  }
1612
1664
  }
1613
1665
  }
1614
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw y(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return y(s),null}}async SendComponentFeedback(e){try{const t=c`
1666
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u(s),null}}async SendComponentFeedback(e){try{const t=c`
1615
1667
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
1616
1668
  SendComponentFeedback(feedback: $feedback) {
1617
1669
  success
@@ -1619,7 +1671,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1619
1671
  error
1620
1672
  }
1621
1673
  }
1622
- `,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 wt{static{u(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`
1674
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class At{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`
1623
1675
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1624
1676
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1625
1677
  Success
@@ -1635,7 +1687,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1635
1687
  }
1636
1688
  }
1637
1689
  }
1638
- `,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 $t{static{u(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1690
+ `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u(`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 xt{static{l(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1639
1691
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1640
1692
  ListStorageObjects(input: $input) {
1641
1693
  objects {
@@ -1652,18 +1704,18 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1652
1704
  prefixes
1653
1705
  }
1654
1706
  }
1655
- `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw y(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){return y(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=c`
1707
+ `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw u(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){return u(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=c`
1656
1708
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1657
1709
  CreateDirectory(input: $input)
1658
1710
  }
1659
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return y(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){return y(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=c`
1711
+ `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return u(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){return u(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=c`
1660
1712
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1661
1713
  CreatePreAuthUploadUrl(input: $input) {
1662
1714
  UploadUrl
1663
1715
  ProviderKey
1664
1716
  }
1665
1717
  }
1666
- `,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`
1718
+ `,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 u(`Error creating pre-auth upload URL: ${n}`),n}}async UploadFile(e){try{const t=c`
1667
1719
  mutation UploadStorageFile($input: UploadStorageFileInput!) {
1668
1720
  UploadStorageFile(input: $input) {
1669
1721
  Success
@@ -1680,23 +1732,23 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1680
1732
  }
1681
1733
  }
1682
1734
  }
1683
- `,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`
1735
+ `,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 u(`Error uploading file via MJ Storage: ${r}`),r}}async CreatePreAuthDownloadUrl(e,t){try{const r=c`
1684
1736
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1685
1737
  CreatePreAuthDownloadUrl(input: $input)
1686
1738
  }
1687
- `,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw y(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=c`
1739
+ `,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw u(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=c`
1688
1740
  mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
1689
1741
  DeleteStorageObject(input: $input)
1690
1742
  }
1691
- `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){return y(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,r){try{const s=c`
1743
+ `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){return u(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,r){try{const s=c`
1692
1744
  mutation MoveStorageObject($input: MoveStorageObjectInput!) {
1693
1745
  MoveStorageObject(input: $input)
1694
1746
  }
1695
- `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){return y(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=c`
1747
+ `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){return u(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=c`
1696
1748
  mutation CopyStorageObject($input: CopyStorageObjectInput!) {
1697
1749
  CopyStorageObject(input: $input)
1698
1750
  }
1699
- `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){return y(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=c`
1751
+ `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){return u(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=c`
1700
1752
  mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
1701
1753
  CopyObjectBetweenAccounts(input: $input) {
1702
1754
  success
@@ -1708,7 +1760,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1708
1760
  destinationPath
1709
1761
  }
1710
1762
  }
1711
- `,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return y(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=c`
1763
+ `,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return u(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=c`
1712
1764
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1713
1765
  SearchAcrossAccounts(input: $input) {
1714
1766
  accountResults {
@@ -1736,7 +1788,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1736
1788
  failedAccounts
1737
1789
  }
1738
1790
  }
1739
- `,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 Pt{static{u(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`
1791
+ `,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 u(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Tt{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`
1740
1792
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1741
1793
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1742
1794
  Success
@@ -1844,7 +1896,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1844
1896
  IsPersonal
1845
1897
  }
1846
1898
  }
1847
- `;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`
1899
+ `;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 u(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new T(t=>{const r=c`
1848
1900
  mutation StreamScopedSearch(
1849
1901
  $query: String!,
1850
1902
  $maxResults: Float,
@@ -1877,7 +1929,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1877
1929
  ElapsedMs
1878
1930
  ErrorMessage
1879
1931
  }
1880
- }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:u(m=>{const d=m?.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:u(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,EntityDisplayName:e.EntityDisplayName,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 Mt{static{u(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1932
+ }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:l(g=>{const y=g?.SearchStreamEvents;y&&(t.next(y),y.Phase==="final"?(t.complete(),n?.unsubscribe()):y.Phase==="error"&&(t.error(new Error(y.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,EntityDisplayName:e.EntityDisplayName,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 u(`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 Lt{static{l(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1881
1933
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1882
1934
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1883
1935
  Success
@@ -1913,7 +1965,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1913
1965
  ServerVersion
1914
1966
  }
1915
1967
  }
1916
- `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return y(`Error testing integration connection: ${r}`),{Success:!1,Message:`Error: ${r.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const s=c`
1968
+ `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return u(`Error testing integration connection: ${r}`),{Success:!1,Message:`Error: ${r.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const s=c`
1917
1969
  query IntegrationSchemaPreview(
1918
1970
  $companyIntegrationID: String!,
1919
1971
  $objects: [SchemaPreviewObjectInput!]!,
@@ -1934,7 +1986,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1934
1986
  Warnings
1935
1987
  }
1936
1988
  }
1937
- `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return y(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=c`
1989
+ `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return u(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=c`
1938
1990
  query IntegrationPreviewData(
1939
1991
  $companyIntegrationID: String!,
1940
1992
  $objectName: String!,
@@ -1952,7 +2004,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1952
2004
  }
1953
2005
  }
1954
2006
  }
1955
- `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return y(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=c`
2007
+ `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return u(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=c`
1956
2008
  query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
1957
2009
  IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
1958
2010
  Success
@@ -1971,7 +2023,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
1971
2023
  }
1972
2024
  }
1973
2025
  }
1974
- `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return y(`Error getting default config: ${r}`),{Success:!1,Message:`Error: ${r.message}`}}}async CreateConnection(e){try{const t=c`mutation IntegrationCreateConnection($input: CreateConnectionInput!) {
2026
+ `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return u(`Error getting default config: ${r}`),{Success:!1,Message:`Error: ${r.message}`}}}async CreateConnection(e){try{const t=c`mutation IntegrationCreateConnection($input: CreateConnectionInput!) {
1975
2027
  IntegrationCreateConnection(input: $input) { Success Message CompanyIntegrationID CredentialID }
1976
2028
  }`;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.IntegrationCreateConnection??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async UpdateConnection(e,t,r,s){try{const n=c`mutation IntegrationUpdateConnection(
1977
2029
  $companyIntegrationID: String!, $credentialValues: String, $configuration: String, $externalSystemID: String
@@ -2028,7 +2080,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
2028
2080
  PipelineSteps { Name Status DurationMs Message }
2029
2081
  GitCommitSuccess APIRestarted
2030
2082
  }
2031
- }`,m={Connectors:e.map(g=>({CompanyIntegrationID:g.CompanyIntegrationID,SourceObjects:g.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:m,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(g=>g.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(
2083
+ }`,g={Connectors:e.map(m=>({CompanyIntegrationID:m.CompanyIntegrationID,SourceObjects:m.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},y=(await this._dataProvider.ExecuteGQL(o,{input:g,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return y?{Success:y.Success,Message:y.Message,Steps:y.PipelineSteps,GitCommitSuccess:y.GitCommitSuccess,APIRestarted:y.APIRestarted,EntityMapsCreated:y.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:y.ConnectorResults?.[0]?.SyncRunID,Warnings:y.ConnectorResults?.flatMap(m=>m.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(
2032
2084
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
2033
2085
  ) {
2034
2086
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -2070,7 +2122,7 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
2070
2122
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
2071
2123
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
2072
2124
  }
2073
- }`;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}}}const bt=c`
2125
+ }`;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 u(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}const Ft=c`
2074
2126
  query TailConversationEvents($conversationDetailID: String!, $sinceSeq: Int) {
2075
2127
  TailConversationEvents(conversationDetailID: $conversationDetailID, sinceSeq: $sinceSeq) {
2076
2128
  Success
@@ -2093,5 +2145,142 @@ ${e.stackFrames}`:this.stack}}function le(l){return l instanceof k?l:new k(q(l))
2093
2145
  DetailStatus
2094
2146
  }
2095
2147
  }
2096
- `;class Nt{static{u(this,"GraphQLConversationClient")}constructor(e){this._dataProvider=e}async TailConversationEvents(e,t=0){const r=Math.max(0,Math.floor(t));try{const n=(await this._dataProvider.ExecuteGQL(bt,{conversationDetailID:e,sinceSeq:r}))?.TailConversationEvents;return n?{...n,Events:n.Events??[],LatestSeq:typeof n.LatestSeq=="number"?n.LatestSeq:r}:this.failure(r,"Invalid response from server")}catch(s){const n=s instanceof Error?s.message:String(s);return this.failure(r,`TailConversationEvents failed: ${n}`)}}failure(e,t){return{Success:!1,Message:t,Events:[],LatestSeq:e,IsInFlight:!0}}}export{ot as ActionItemInput,ct as ActionItemOutput,ue as BrowserIndexedDBStorageProvider,ie as BrowserStorageProviderBase,et as ConnectGraphQLClient,N as FieldMapper,w as FireAndForgetHelper,lt as GetDataOutput,oe as GraphQLAIClient,gt as GraphQLActionClient,Dt as GraphQLClassifyClient,Et as GraphQLClusterClient,Ct as GraphQLComponentRegistryClient,Nt as GraphQLConversationClient,I as GraphQLDataProvider,ft as GraphQLEncryptionClient,$t as GraphQLFileStorageClient,Mt as GraphQLIntegrationClient,St as GraphQLListsClient,Rt as GraphQLLiveKitClient,ze as GraphQLProviderConfigData,Pt as GraphQLSearchClient,ut as GraphQLSystemUserClient,vt as GraphQLTestingClient,ae as GraphQLTransactionGroup,wt as GraphQLVersionHistoryClient,G as PACKAGE_VERSION,st as RoleInput,at as RolesAndUsersInput,k as SafeGraphQLError,q as SanitizeGraphQLError,me as SetupGraphQLClient,yt as SimpleRemoteEntity,mt as SimpleRemoteEntityField,dt as SimpleRemoteEntityOutput,ge as SyncDataAction,it as SyncDataResult,rt as SyncRolesAndUsersResult,le as ToSafeGraphQLError,nt as UserInput,Ot as gql,tt as setupGraphQLClient};
2148
+ `;class Gt{static{l(this,"GraphQLConversationClient")}constructor(e){this._dataProvider=e}async TailConversationEvents(e,t=0){const r=Math.max(0,Math.floor(t));try{const n=(await this._dataProvider.ExecuteGQL(Ft,{conversationDetailID:e,sinceSeq:r}))?.TailConversationEvents;return n?{...n,Events:n.Events??[],LatestSeq:typeof n.LatestSeq=="number"?n.LatestSeq:r}:this.failure(r,"Invalid response from server")}catch(s){const n=s instanceof Error?s.message:String(s);return this.failure(r,`TailConversationEvents failed: ${n}`)}}failure(e,t){return{Success:!1,Message:t,Events:[],LatestSeq:e,IsInFlight:!0}}}const x=`
2149
+ ID
2150
+ Title
2151
+ Description
2152
+ HostUserID
2153
+ HostUserName
2154
+ RoomName
2155
+ Status
2156
+ ScheduledStartAt
2157
+ ScheduledEndAt
2158
+ StartedAt
2159
+ EndedAt
2160
+ AllowPhoneDialIn
2161
+ DialInPhoneNumberID
2162
+ DialInPhoneNumber
2163
+ DialInCode
2164
+ RecordingPolicy
2165
+ ConversationID
2166
+ CreatedAt
2167
+ UpdatedAt
2168
+ Participants {
2169
+ ID
2170
+ MeetingID
2171
+ UserID
2172
+ UserName
2173
+ UserEmail
2174
+ AgentID
2175
+ AgentName
2176
+ ExternalName
2177
+ ExternalEmail
2178
+ ExternalPhone
2179
+ Role
2180
+ InviteStatus
2181
+ JoinedAt
2182
+ LeftAt
2183
+ }
2184
+ `;class Qt{static{l(this,"GraphQLMeetingClient")}constructor(e){e&&"ExecuteGQL"in e?this._dataProvider=e:this._dataProvider=I.Instance}async GetMeeting(e){return this.Meeting(e)}async MyMeetings(e){try{const t=c`
2185
+ query MyMeetings($status: String) {
2186
+ MyMeetings(status: $status) {
2187
+ ${x}
2188
+ }
2189
+ }
2190
+ `;return(await this._dataProvider.ExecuteGQL(t,{status:e}))?.MyMeetings??[]}catch(t){return u(`GraphQLMeetingClient.MyMeetings error: ${t instanceof Error?t.message:String(t)}`),[]}}async Meeting(e){try{const t=c`
2191
+ query Meeting($id: String!) {
2192
+ Meeting(id: $id) {
2193
+ ${x}
2194
+ }
2195
+ }
2196
+ `;return(await this._dataProvider.ExecuteGQL(t,{id:e}))?.Meeting??null}catch(t){return u(`GraphQLMeetingClient.Meeting error: ${t instanceof Error?t.message:String(t)}`),null}}async MeetingParticipants(e){try{const t=c`
2197
+ query MeetingParticipants($meetingID: String!) {
2198
+ MeetingParticipants(meetingID: $meetingID) {
2199
+ ID
2200
+ MeetingID
2201
+ UserID
2202
+ UserName
2203
+ UserEmail
2204
+ AgentID
2205
+ AgentName
2206
+ ExternalName
2207
+ ExternalEmail
2208
+ ExternalPhone
2209
+ Role
2210
+ InviteStatus
2211
+ JoinedAt
2212
+ LeftAt
2213
+ }
2214
+ }
2215
+ `;return(await this._dataProvider.ExecuteGQL(t,{meetingID:e}))?.MeetingParticipants??[]}catch(t){return u(`GraphQLMeetingClient.MeetingParticipants error: ${t instanceof Error?t.message:String(t)}`),[]}}async AvailableDialInPhoneNumbers(){try{const e=c`
2216
+ query AvailableDialInPhoneNumbers {
2217
+ AvailableDialInPhoneNumbers {
2218
+ ID
2219
+ Number
2220
+ Label
2221
+ }
2222
+ }
2223
+ `;return(await this._dataProvider.ExecuteGQL(e,{}))?.AvailableDialInPhoneNumbers??[]}catch(e){return u(`GraphQLMeetingClient.AvailableDialInPhoneNumbers error: ${e instanceof Error?e.message:String(e)}`),[]}}async CreateMeeting(e){try{const t=c`
2224
+ mutation CreateMeeting($input: CreateMeetingInput!) {
2225
+ CreateMeeting(input: $input) {
2226
+ Success
2227
+ ErrorMessage
2228
+ Meeting {
2229
+ ${x}
2230
+ }
2231
+ }
2232
+ }
2233
+ `;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.CreateMeeting??{Success:!1,ErrorMessage:"No response"}}catch(t){const r=t instanceof Error?t.message:String(t);return u(`GraphQLMeetingClient.CreateMeeting error: ${r}`),{Success:!1,ErrorMessage:r}}}async UpdateMeeting(e){try{const t=c`
2234
+ mutation UpdateMeeting($input: UpdateMeetingInput!) {
2235
+ UpdateMeeting(input: $input) {
2236
+ Success
2237
+ ErrorMessage
2238
+ Meeting {
2239
+ ${x}
2240
+ }
2241
+ }
2242
+ }
2243
+ `;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.UpdateMeeting??{Success:!1,ErrorMessage:"No response"}}catch(t){const r=t instanceof Error?t.message:String(t);return u(`GraphQLMeetingClient.UpdateMeeting error: ${r}`),{Success:!1,ErrorMessage:r}}}async StartMeeting(e){try{const t=c`
2244
+ mutation StartMeeting($meetingID: String!) {
2245
+ StartMeeting(meetingID: $meetingID) {
2246
+ Success
2247
+ ErrorMessage
2248
+ RoomName
2249
+ ClientToken
2250
+ Meeting {
2251
+ ${x}
2252
+ }
2253
+ }
2254
+ }
2255
+ `;return(await this._dataProvider.ExecuteGQL(t,{meetingID:e}))?.StartMeeting??{Success:!1,ErrorMessage:"No response"}}catch(t){const r=t instanceof Error?t.message:String(t);return u(`GraphQLMeetingClient.StartMeeting error: ${r}`),{Success:!1,ErrorMessage:r}}}async EndMeeting(e){try{const t=c`
2256
+ mutation EndMeeting($meetingID: String!) {
2257
+ EndMeeting(meetingID: $meetingID) {
2258
+ Success
2259
+ ErrorMessage
2260
+ Meeting {
2261
+ ${x}
2262
+ }
2263
+ }
2264
+ }
2265
+ `;return(await this._dataProvider.ExecuteGQL(t,{meetingID:e}))?.EndMeeting??{Success:!1,ErrorMessage:"No response"}}catch(t){const r=t instanceof Error?t.message:String(t);return u(`GraphQLMeetingClient.EndMeeting error: ${r}`),{Success:!1,ErrorMessage:r}}}async CancelMeeting(e){try{const t=c`
2266
+ mutation CancelMeeting($meetingID: String!) {
2267
+ CancelMeeting(meetingID: $meetingID) {
2268
+ Success
2269
+ ErrorMessage
2270
+ Meeting {
2271
+ ${x}
2272
+ }
2273
+ }
2274
+ }
2275
+ `;return(await this._dataProvider.ExecuteGQL(t,{meetingID:e}))?.CancelMeeting??{Success:!1,ErrorMessage:"No response"}}catch(t){const r=t instanceof Error?t.message:String(t);return u(`GraphQLMeetingClient.CancelMeeting error: ${r}`),{Success:!1,ErrorMessage:r}}}async RSVPMeeting(e){try{const t=c`
2276
+ mutation RSVPMeeting($input: RSVPMeetingInput!) {
2277
+ RSVPMeeting(input: $input) {
2278
+ Success
2279
+ ErrorMessage
2280
+ Meeting {
2281
+ ${x}
2282
+ }
2283
+ }
2284
+ }
2285
+ `;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RSVPMeeting??{Success:!1,ErrorMessage:"No response"}}catch(t){const r=t instanceof Error?t.message:String(t);return u(`GraphQLMeetingClient.RSVPMeeting error: ${r}`),{Success:!1,ErrorMessage:r}}}}export{dt as ActionItemInput,gt as ActionItemOutput,de as BrowserIndexedDBStorageProvider,ue as BrowserStorageProviderBase,at as ConnectGraphQLClient,b as FieldMapper,w as FireAndForgetHelper,St as GetDataOutput,ce as GraphQLAIClient,ft as GraphQLActionClient,Mt as GraphQLClassifyClient,wt as GraphQLClusterClient,bt as GraphQLComponentRegistryClient,Gt as GraphQLConversationClient,I as GraphQLDataProvider,Ct as GraphQLEncryptionClient,xt as GraphQLFileStorageClient,Pt as GraphQLHandoffClient,Lt as GraphQLIntegrationClient,Et as GraphQLListsClient,$t as GraphQLLiveKitClient,Qt as GraphQLMeetingClient,tt as GraphQLProviderConfigData,Tt as GraphQLSearchClient,mt as GraphQLSystemUserClient,Nt as GraphQLTestingClient,ie as GraphQLTransactionGroup,At as GraphQLVersionHistoryClient,Q as PACKAGE_VERSION,ct as RoleInput,lt as RolesAndUsersInput,k as SafeGraphQLError,K as SanitizeGraphQLError,Se as SetupGraphQLClient,ht as SimpleRemoteEntity,It as SimpleRemoteEntityField,pt as SimpleRemoteEntityOutput,pe as SyncDataAction,yt as SyncDataResult,it as SyncRolesAndUsersResult,ye as ToSafeGraphQLError,ut as UserInput,Ht as gql,ot as setupGraphQLClient};
2097
2286
  //# sourceMappingURL=index.mjs.map