@memberjunction/graphql-dataprovider 5.47.0 → 5.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +50 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +38 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +49 -43
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -8
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as k}from"graphql-request";import{gql as ht}from"graphql-request";import{TransactionGroupBase as ne,TransactionResult as ae,LogError as l,LogStatus as
|
|
1
|
+
var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as k}from"graphql-request";import{gql as ht}from"graphql-request";import{TransactionGroupBase as ne,TransactionResult as ae,LogError as l,LogStatus as P,LogErrorEx as M,ProviderBase as oe,UserInfo as q,getGraphQLTypeNameBase as x,ProviderType as ie,BaseEntityResult as U,EntityFieldTSType as N,TransactionItem as K,CompositeKey as ce,UserRoleInfo as ue,InMemoryLocalStorageProvider as le,BaseEntity as de,ProviderConfigDataBase as ye,SetProvider as me,StartupManager as ge,IsPlatformSQL as Se,IsVerboseLoggingEnabled as pe}from"@memberjunction/core";import{SafeJSONParse as v,CleanAndParseJSON as he,GetGlobalObjectStore as B,MJGlobal as j,MJEventType as J}from"@memberjunction/global";import{ViewInfo as W}from"@memberjunction/core-entities";import{BehaviorSubject as Ie,Observable as T,Subject as fe,Subscription as Re}from"rxjs";import{createClient as Ee}from"graphql-ws";import{v4 as De}from"uuid";import{openDB as ve}from"@tempfix/idb";class A{static{d(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(A.DB_PREFIX)?A.GQL_PREFIX+e.substring(A.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(A.GQL_PREFIX)?A.DB_PREFIX+e.substring(A.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 z extends ne{static{d(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 se=Object.defineProperty;var d=(g,e)=>se(g,"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=[];for(let
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=n.Success===!0,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const m=n.ResultsJSON[o],u=v(m),h=this.PendingTransactions[o];i.push(new ae(h,u,a&&u!==null))}return i}else throw new Error("Failed to execute transaction group")}}const Ce=720*1e3,we=6;class w{static{d(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??Ce,n=e.maxStallReconciles??we;let a,i=!1,o=0;const{promise:m,resolve:u,reject:h}=w.createCompletionPromise(),f=d(E=>{i||(i=!0,R.clear(),E())},"finish"),y=d(E=>f(()=>u(E)),"settleResolve"),S=d(E=>f(()=>h(E)),"settleReject"),p=d(async()=>{if(i)return;if(!e.onStall){S(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let E;try{P(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){S(D);return}i||(E==="continue"?++o>n?S(new Error(`The operation is still reported as running but no signal has arrived after ${o} checks. Please refresh the page to check the latest status.`)):R.reset():"resolve"in E?(P(`[FireAndForget:${t}] Reconciliation recovered a completed run`),y(E.resolve)):S(E.reject))},"onStall"),R=w.createIdleTimer(s,()=>{p()});try{R.reset(),a=w.subscribeToPubSub(e,{onActivity:d(()=>{o=0,R.reset()},"onActivity"),onCompletion:d(D=>y(D),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const E=await w.executeMutation(e);if(!e.validateAck(E)){R.clear();const D=E?.errorMessage??"Server rejected the request";return l(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return P(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await m}catch(E){throw l(`[FireAndForget:${t}] Error: ${E.message}`),E}finally{R.clear(),a&&a.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:d(n=>{t.onActivity();try{const a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(P(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"next"),error:d(()=>t.onStreamEnd(),"error"),complete:d(()=>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.`):(l(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class H{static{d(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 se=Object.defineProperty;var d=(g,e)=>se(g,"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=he(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 l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await
|
|
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=he(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 l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await w.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:d(i=>i?.success===!0,"validateAck"),isCompletionEvent:d(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:d(i=>this.extractAgentResult(i),"extractResult"),extractSyncResult:d(i=>this.extractAgentResultFromAck(i),"extractSyncResult"),onMessage:d(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:d(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -110,7 +110,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
110
110
|
result
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
|
-
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),s}processAgentResult(e){return
|
|
113
|
+
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),s}processAgentResult(e){return v(e)}handleAgentError(e){const r=e?.message||String(e);l(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:d(s=>this.extractAgentResult(s),"extractResult"),extractSyncResult:d(s=>this.extractAgentResultFromAck(s),"extractSyncResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:d(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:d(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return c`
|
|
114
114
|
mutation RunAIAgentFromConversationDetail(
|
|
115
115
|
$conversationDetailId: String!,
|
|
116
116
|
$agentId: String!,
|
|
@@ -153,7 +153,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
153
153
|
result
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
|
-
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?
|
|
156
|
+
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?v(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?v(r):{success:t.success,agentRun:void 0}}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){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=c`
|
|
157
157
|
mutation ExecuteSimplePrompt(
|
|
158
158
|
$systemPrompt: String!,
|
|
159
159
|
$messages: String,
|
|
@@ -305,12 +305,12 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
305
305
|
}
|
|
306
306
|
}
|
|
307
307
|
}
|
|
308
|
-
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return l("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="5.
|
|
308
|
+
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return l("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="5.49.0",$="default";class X{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}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",Pe=0;function Me(){try{const g=F.split("."),e=parseInt(g[0],10),t=parseInt(g[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${F}"`);return e*1e3+t+Pe}catch(g){return M({error:g,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(Me,"computeIdbVersion");const Ae=Me(),Y=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Z extends X{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ve($e,Ae,{upgrade:d((e,t,r)=>{try{P(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${F}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of Y)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){M({error:s,message:s?.message})}},"upgrade"),blocked:d((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 IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return Y.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),u=i.map(f=>m.get(f)),h=await Promise.all(u);await o.done;for(let f=0;f<a.length;f++){const y=h[f];r.set(a[f],y===void 0?null:y)}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}),[]}}}const b=new A,Ne=c`subscription RemoteOperationProgress($channelId: ID!) {
|
|
309
309
|
RemoteOperationProgress(channelId: $channelId) {
|
|
310
310
|
ChannelId
|
|
311
311
|
ProgressJSON
|
|
312
312
|
}
|
|
313
|
-
}`;class be extends ye{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,
|
|
313
|
+
}`;class be extends ye{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,m,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:m,RefreshTokenFunction:s,OnAuthenticationError:u},n,a,i)}}class I extends oe{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
|
|
314
314
|
${this.userInfoString()}
|
|
315
315
|
MJUserRoles_UserIDArray {
|
|
316
316
|
${this.userRoleInfoString()}
|
|
@@ -340,19 +340,19 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
340
340
|
${this.QueryReturnFieldList}
|
|
341
341
|
}
|
|
342
342
|
}
|
|
343
|
-
`,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription,Enrichment:a.Enrichment})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i,o){const
|
|
343
|
+
`,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription,Enrichment:a.Enrichment})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i,o){const m=c`
|
|
344
344
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
|
|
345
345
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
|
|
346
346
|
${this.QueryReturnFieldList}
|
|
347
347
|
}
|
|
348
348
|
}
|
|
349
|
-
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i),o!==void 0&&(u.Enrichment=o);const h=await this.ExecuteGQL(
|
|
349
|
+
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i),o!==void 0&&(u.Enrichment=o);const h=await this.ExecuteGQL(m,u);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o){const m=c`
|
|
350
350
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
|
|
351
351
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
|
|
352
352
|
${this.QueryReturnFieldList}
|
|
353
353
|
}
|
|
354
354
|
}
|
|
355
|
-
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i),o!==void 0&&(u.Enrichment=o);const h=await this.ExecuteGQL(
|
|
355
|
+
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i),o!==void 0&&(u.Enrichment=o);const h=await this.ExecuteGQL(m,u);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
356
356
|
Success
|
|
357
357
|
QueryID
|
|
358
358
|
QueryName
|
|
@@ -377,14 +377,14 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
377
377
|
}
|
|
378
378
|
}
|
|
379
379
|
}
|
|
380
|
-
`,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
|
|
380
|
+
`,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 l(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:p,v:R}=await this.getEntityNameAndUserView(e,t);i=R,a=p}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let m=!1;const u=x(o);e.ViewID?(r=`Run${u}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${u}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(m=!0,r=`Run${u}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),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(p=>({expression:p.expression,alias:p.alias})));const h=this.getViewRunTimeFieldList(o,i,e,m),f=e.Aggregates&&e.Aggregates.length>0?`
|
|
381
381
|
AggregateResults {
|
|
382
382
|
alias
|
|
383
383
|
expression
|
|
384
384
|
value
|
|
385
385
|
error
|
|
386
386
|
}
|
|
387
|
-
AggregateExecutionTime`:"",
|
|
387
|
+
AggregateExecutionTime`:"",y=c`
|
|
388
388
|
query RunViewQuery ($input: ${s}!) {
|
|
389
389
|
${r}(input: $input) {
|
|
390
390
|
Results {
|
|
@@ -398,7 +398,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
398
398
|
Success
|
|
399
399
|
ErrorMessage${f}
|
|
400
400
|
}
|
|
401
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const
|
|
401
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const S=await this.ExecuteGQL(y,{input:n});if(S&&S[r]){const p=S[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:S[r].AggregateExecutionTime});const R=S[r].Results;if(R&&R.length>0){const D=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);R.forEach(C=>{this.ConvertBackToMJFields(C),D.forEach(L=>{C[L.Name]=C[L.CodeName]})})}return S[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw l(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const u of e){let h="",f="";const y={};let S=null,p=null;if(u.ViewEntity)p=u.ViewEntity,S=p.Get("Entity");else{const{entityName:C,v:L}=await this.getEntityNameAndUserView(u,t);p=L,S=C}const R=this.EntityByName(S);if(!R)throw new Error(`Entity ${S} not found in metadata`);s.push(R);let E=!1;const D=x(R);u.ViewID?(h=`Run${D}ViewByID`,f="RunViewByIDInput",y.ViewID=u.ViewID):u.ViewName?(h=`Run${D}ViewByName`,f="RunViewByNameInput",y.ViewName=u.ViewName):(E=!0,h=`Run${D}DynamicView`,f="RunDynamicViewInput",y.EntityName=u.EntityName),y.ExtraFilter=u.ExtraFilter||"",y.OrderBy=u.OrderBy||"",y.UserSearchString=u.UserSearchString||"",y.Fields=u.Fields,y.IgnoreMaxRows=u.IgnoreMaxRows||!1,u.MaxRows!==void 0&&(y.MaxRows=u.MaxRows),u.StartRow!==void 0&&(y.StartRow=u.StartRow),u.AfterKey&&(y.AfterKey={KeyValuePairs:u.AfterKey.KeyValuePairs}),y.ForceAuditLog=u.ForceAuditLog||!1,y.ResultType=u.ResultType||"simple",u.AuditLogDescription&&u.AuditLogDescription.length>0&&(y.AuditLogDescription=u.AuditLogDescription),u.BypassCache!==void 0&&(y.BypassCache=u.BypassCache),E||(y.ExcludeUserViewRunID=u.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=u.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=u.OverrideExcludeFilter||"",y.SaveViewResults=u.SaveViewResults||!1),u.Aggregates&&u.Aggregates.length>0&&(y.Aggregates=u.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(R,p,u,E))}const i=e.some(u=>u.Aggregates&&u.Aggregates.length>0)?`
|
|
402
402
|
AggregateResults {
|
|
403
403
|
alias
|
|
404
404
|
expression
|
|
@@ -423,7 +423,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
423
423
|
Success
|
|
424
424
|
ErrorMessage${i}
|
|
425
425
|
}
|
|
426
|
-
}`,
|
|
426
|
+
}`,m=await this.ExecuteGQL(o,{input:r});if(m&&m.RunViews){const u=m.RunViews;for(const[h,f]of u.entries())f.Results=f.Results.map(y=>{let S=JSON.parse(y.Data);return this.ConvertBackToMJFields(S),S});return u}return null}catch(r){throw l(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple",Aggregates:o.params.Aggregates??null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
|
|
427
427
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
428
428
|
RunViewsWithCacheCheck(input: $input) {
|
|
429
429
|
success
|
|
@@ -433,6 +433,12 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
433
433
|
status
|
|
434
434
|
maxUpdatedAt
|
|
435
435
|
rowCount
|
|
436
|
+
aggregateResults {
|
|
437
|
+
expression
|
|
438
|
+
alias
|
|
439
|
+
value
|
|
440
|
+
error
|
|
441
|
+
}
|
|
436
442
|
errorMessage
|
|
437
443
|
Results {
|
|
438
444
|
PrimaryKey {
|
|
@@ -456,7 +462,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
456
462
|
}
|
|
457
463
|
}
|
|
458
464
|
}
|
|
459
|
-
`,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,
|
|
465
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,m)=>{const u=e[m];if(o.status==="differential"&&o.differentialData){const h=o.differentialData.updatedRows.map(f=>{const y=JSON.parse(f.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:h,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const h=o.Results.map(y=>{const S=JSON.parse(y.Data);return this.ConvertBackToMJFields(S),S}),f=o.aggregateResults?.map(y=>({expression:y.expression,alias:y.alias,value:y.value!==void 0&&y.value!==null?JSON.parse(y.value):null,error:y.error}));return{viewIndex:o.viewIndex,status:o.status,results:h,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage,aggregateResults:f}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(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 W.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await W.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const a of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);r.Fields.forEach(a=>{n.push(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(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 ie.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 l(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
460
466
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
461
467
|
EntityName
|
|
462
468
|
RelatedEntityName
|
|
@@ -531,32 +537,32 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
531
537
|
Message
|
|
532
538
|
}
|
|
533
539
|
}
|
|
534
|
-
}`,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 l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new U;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(
|
|
535
|
-
${e.Fields.map(
|
|
540
|
+
}`,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 l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new U;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.RegisterResultHistoryEntry(s);const i=x(e.EntityInfo),o=`${a}${i}`,m=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),u=` ${o}(input: $input) {
|
|
541
|
+
${e.Fields.map(y=>b.MapFieldName(y.CodeName)).join(`
|
|
536
542
|
`)}
|
|
537
543
|
}`,h=c`mutation ${a}${i} ($input: ${o}Input!) {
|
|
538
544
|
${u}
|
|
539
545
|
}
|
|
540
|
-
`;for(let
|
|
541
|
-
${
|
|
546
|
+
`;for(let y=0;y<m.length;y++){const S=m[y];let p=e.Get(S.Name);if(p)switch(S.EntityFieldInfo.TSType){case N.Date:p=p.getTime();break;case N.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case N.Number:if(typeof p!="number"){const R=Number(p);isNaN(R)||(p=R)}break}p===null&&S.EntityFieldInfo.AllowsNull===!1&&(S.EntityFieldInfo.DefaultValue!==null?p=S.EntityFieldInfo.DefaultValue:S.FieldType===N.Number||S.FieldType===N.Boolean?p=0:p=""),n.input[b.MapFieldName(S.CodeName)]=p}const f=e.RestoreContext;if(f&&(n.input.RestoreContext___={SourceChangeID:f.SourceChangeID,Reason:f.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(S=>{let p=null;S.OldValue!==null&&S.OldValue!==void 0&&(S.EntityFieldInfo.TSType===N.Date?p=S.OldValue.getTime().toString():S.EntityFieldInfo.TSType===N.Boolean?p=S.OldValue===!0?"1":"0":typeof S.OldValue!="string"?p=S.OldValue.toString():p=S.OldValue),y.push({Key:b.MapFieldName(S.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,s.Type==="create"?"Create":"Update",u,n,{mutationName:o,mutationInputTypes:y},(S,p)=>{s.EndedAt=new Date,p&&S?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(S)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(h,n);if(y&&y[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let f=0;f<t.KeyValuePairs.length;f++){const y=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[f].FieldName.trim().toLowerCase()).EntityFieldInfo,S=t.GetValueByIndex(f),p=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${p}!`,a.length>0&&(a+=", "),a+=`${y.CodeName}: $${y.CodeName}`,y.TSType===N.Number){if(isNaN(t.GetValueByIndex(f)))throw new Error(`Primary Key value ${S} (${y.Name}) is not a valid number`);n[y.CodeName]=parseInt(S)}else n[y.CodeName]=S}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=x(e.EntityInfo),u=c`query Single${m}${o.length>0?"Full":""} (${i}) {
|
|
547
|
+
${m}(${a}) {
|
|
542
548
|
${e.Fields.filter(f=>!f.EntityFieldInfo.IsBinaryFieldType).map(f=>f.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?f.CodeName.replace("__mj_","_mj__"):f.CodeName).join(`
|
|
543
549
|
`)}
|
|
544
550
|
${o}
|
|
545
551
|
}
|
|
546
552
|
}
|
|
547
|
-
`,h=await this.ExecuteGQL(u,n);return h&&h[
|
|
553
|
+
`,h=await this.ExecuteGQL(u,n);return h&&h[m]?this.ConvertBackToMJFields(h[m]):null}catch(n){return l(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+=`
|
|
548
554
|
${i} {
|
|
549
555
|
${a.Fields.map(o=>o.CodeName).join(`
|
|
550
556
|
`)}
|
|
551
557
|
}
|
|
552
|
-
`}return r}async Delete(e,t,r){const s=new U;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(
|
|
553
|
-
`),
|
|
554
|
-
${
|
|
558
|
+
`}return r}async Delete(e,t,r){const s=new U;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(S=>({FieldName:S.CodeName,Value:S.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",m="";for(let S of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(R=>R.Name.trim().toLowerCase()===S.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,a.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,o.length>0&&(o+=", "),o+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
|
|
559
|
+
`),m+=`${p.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const h="Delete"+x(e.EntityInfo),f=c`${h}(${i}, options___: $options___) {
|
|
560
|
+
${m}
|
|
555
561
|
}
|
|
556
|
-
`,
|
|
562
|
+
`,y=c`mutation ${h} (${o}, $options___: DeleteOptionsInput!) {
|
|
557
563
|
${f}
|
|
558
564
|
}
|
|
559
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,"Delete",f,n,{mutationName:h,mutationInputTypes:a},(p
|
|
565
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,"Delete",f,n,{mutationName:h,mutationInputTypes:a},(S,p)=>{if(s.EndedAt=new Date,p&&S){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==S[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const S=await this.ExecuteGQL(y,n);if(S&&S[h]){const p=S[h];for(let R of e.PrimaryKey.KeyValuePairs){let E=p[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof E=="number"&&(E=E.toString()),D!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
560
566
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
561
567
|
DatasetID
|
|
562
568
|
DatasetName
|
|
@@ -565,7 +571,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
565
571
|
LatestUpdateDate
|
|
566
572
|
Results
|
|
567
573
|
}
|
|
568
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);
|
|
574
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);P(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
|
|
569
575
|
GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
|
|
570
576
|
DatasetID
|
|
571
577
|
DatasetName
|
|
@@ -623,16 +629,16 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
623
629
|
ErrorMessage
|
|
624
630
|
Result
|
|
625
631
|
}
|
|
626
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const 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 k(e,{headers:a});for(const[o,
|
|
632
|
+
}`,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 l(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const 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 k(e,{headers:a});for(const[o,m]of this._dynamicHeaders)i.setHeader(o,m);return i}userInfoString(){return this.infoString(new q(null,null))}userRoleInfoString(){return this.infoString(new ue(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
627
633
|
`:s.startsWith("_")||(t+=s+`
|
|
628
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Z:this._localStorageProvider=new le),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=Ee({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,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
|
|
634
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Z:this._localStorageProvider=new le),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=Ee({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,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:d(a=>{r.next(a.data)},"next"),error:d(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(m){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",m),r.error(m)}}else r.error(a)},"error"),complete:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new T(o=>{r.activeSubscribers++;const m=r.subject.subscribe(o);return()=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers>0&&u.activeSubscribers--,m.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
|
|
629
635
|
statusUpdates(sessionId: $sessionId) {
|
|
630
636
|
date
|
|
631
637
|
message
|
|
632
638
|
sessionId
|
|
633
639
|
}
|
|
634
640
|
}
|
|
635
|
-
`,n=new fe,a=this.getOrCreateWSClient(),i=new Re;return i.add(new
|
|
641
|
+
`,n=new fe,a=this.getOrCreateWSClient(),i=new Re;return i.add(new T(o=>{const m=a.subscribe({query:s,variables:{sessionId:e}},{next:d(u=>{const h=this._pushStatusSubjects.get(e);h&&(h.lastEmissionAt=Date.now()),o.next(u.data.statusUpdates.message)},"next"),error:d(async u=>{const h=u;if(h?.extensions?.code==="JWT_EXPIRED"||h?.message?.includes("token has expired")||h?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),o.error(y)}}else o.error(u)},"error"),complete:d(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,m()}}).subscribe({next:d(o=>n.next(o),"next"),error:d(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new T(o=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers++;const u=n.subscribe(o);return()=>{const h=this._pushStatusSubjects.get(e);h&&h.activeSubscribers>0&&h.activeSubscribers--,u.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
|
|
636
642
|
subscription ClientToolRequest($sessionID: String!) {
|
|
637
643
|
ClientToolRequest(sessionID: $sessionID) {
|
|
638
644
|
AgentRunID
|
|
@@ -666,14 +672,14 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
666
672
|
ChildEntityNames
|
|
667
673
|
ErrorMessage
|
|
668
674
|
}
|
|
669
|
-
}`;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 l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function
|
|
675
|
+
}`;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 l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function xe(g){const e=new I;return me(e),await e.Config(g),await e.preValidateAndRefresh(),j.Instance.RaiseEvent({event:J.LoggedIn,eventCode:null,component:this,args:null}),await ge.Instance.Startup(),e}d(xe,"setupGraphQLClient");class Te{static{d(this,"SyncRolesAndUsersResult")}}class Le{static{d(this,"RoleInput")}}class Fe{static{d(this,"UserInput")}}class Qe{static{d(this,"RolesAndUsersInput")}}var ee=(g=>(g.Create="Create",g.Update="Update",g.CreateOrUpdate="CreateOrUpdate",g.Delete="Delete",g.DeleteWithFilter="DeleteWithFilter",g))(ee||{});class Ge{static{d(this,"ActionItemInput")}}class Ue{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ve{static{d(this,"ActionItemOutput")}}class _e{static{d(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new k(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return Se(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
670
676
|
GetData(input: $input) {
|
|
671
677
|
Success
|
|
672
678
|
ErrorMessages
|
|
673
679
|
Queries
|
|
674
680
|
Results
|
|
675
681
|
}
|
|
676
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?
|
|
682
|
+
}`,{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]+"."),pe()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
677
683
|
GetAllEntities {
|
|
678
684
|
Success
|
|
679
685
|
ErrorMessage
|
|
@@ -804,7 +810,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
804
810
|
ErrorMessage
|
|
805
811
|
AppliedParameters
|
|
806
812
|
}
|
|
807
|
-
}`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?
|
|
813
|
+
}`,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 l(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
|
|
808
814
|
GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
|
|
809
815
|
QueryID
|
|
810
816
|
QueryName
|
|
@@ -816,7 +822,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
816
822
|
ErrorMessage
|
|
817
823
|
AppliedParameters
|
|
818
824
|
}
|
|
819
|
-
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?
|
|
825
|
+
}`,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 l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQueryExtended($input: CreateQuerySystemUserInput!) {
|
|
820
826
|
CreateQueryExtended(input: $input) {
|
|
821
827
|
Success
|
|
822
828
|
ErrorMessage
|
|
@@ -1027,7 +1033,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1027
1033
|
result
|
|
1028
1034
|
}
|
|
1029
1035
|
}
|
|
1030
|
-
`,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 l(`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
|
|
1036
|
+
`,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 l(`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!) {
|
|
1031
1037
|
TestQuerySQL(input: $input) {
|
|
1032
1038
|
Success
|
|
1033
1039
|
Results
|
|
@@ -1036,7 +1042,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1036
1042
|
ErrorMessage
|
|
1037
1043
|
AppliedParameters
|
|
1038
1044
|
}
|
|
1039
|
-
}`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?
|
|
1045
|
+
}`,{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 l(`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`
|
|
1040
1046
|
query ExecuteSimplePromptSystemUser(
|
|
1041
1047
|
$systemPrompt: String!,
|
|
1042
1048
|
$messages: String,
|
|
@@ -1378,7 +1384,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1378
1384
|
AnalysisID
|
|
1379
1385
|
}
|
|
1380
1386
|
}
|
|
1381
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return l("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=
|
|
1387
|
+
`,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 l("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 Ye{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
|
|
1382
1388
|
mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
|
|
1383
1389
|
MintLiveKitClientToken(input: $input) {
|
|
1384
1390
|
Success
|
|
@@ -1453,7 +1459,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1453
1459
|
NodesJSON
|
|
1454
1460
|
}
|
|
1455
1461
|
}
|
|
1456
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return l("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=
|
|
1462
|
+
`,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 l("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 et{static{d(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:d(n=>n?.success===!0,"validateAck"),isCompletionEvent:d(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:d(n=>this.extractTestResult(n),"extractResult"),onMessage:d(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:d(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:d(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:d(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
|
|
1457
1463
|
query IsTestRunning($testId: String!) {
|
|
1458
1464
|
IsTestRunning(testId: $testId)
|
|
1459
1465
|
}
|
|
@@ -1511,7 +1517,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1511
1517
|
result
|
|
1512
1518
|
}
|
|
1513
1519
|
}
|
|
1514
|
-
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?
|
|
1520
|
+
`}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 l(`${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 tt{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
|
|
1515
1521
|
query GetRegistryComponent(
|
|
1516
1522
|
$registryName: String!,
|
|
1517
1523
|
$namespace: String!,
|
|
@@ -1695,7 +1701,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1695
1701
|
failedAccounts
|
|
1696
1702
|
}
|
|
1697
1703
|
}
|
|
1698
|
-
`,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(
|
|
1704
|
+
`,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 l(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class nt{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
|
|
1699
1705
|
mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
|
|
1700
1706
|
SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
|
|
1701
1707
|
Success
|
|
@@ -1801,7 +1807,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1801
1807
|
IsPersonal
|
|
1802
1808
|
}
|
|
1803
1809
|
}
|
|
1804
|
-
`;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 l(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new
|
|
1810
|
+
`;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 l(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new T(t=>{const r=c`
|
|
1805
1811
|
mutation StreamScopedSearch(
|
|
1806
1812
|
$query: String!,
|
|
1807
1813
|
$maxResults: Float,
|
|
@@ -1834,7 +1840,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1834
1840
|
ElapsedMs
|
|
1835
1841
|
ErrorMessage
|
|
1836
1842
|
}
|
|
1837
|
-
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(
|
|
1843
|
+
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(m=>{const u=m?.SearchStreamEvents;u&&(t.next(u),u.Phase==="final"?(t.complete(),n?.unsubscribe()):u.Phase==="error"&&(t.error(new Error(u.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(m=>t.error(m),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return l(`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 at{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
|
|
1838
1844
|
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1839
1845
|
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1840
1846
|
Success
|
|
@@ -1985,7 +1991,7 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
1985
1991
|
PipelineSteps { Name Status DurationMs Message }
|
|
1986
1992
|
GitCommitSuccess APIRestarted
|
|
1987
1993
|
}
|
|
1988
|
-
}`,
|
|
1994
|
+
}`,m={Connectors:e.map(h=>({CompanyIntegrationID:h.CompanyIntegrationID,SourceObjects:h.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},u=(await this._dataProvider.ExecuteGQL(o,{input:m,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return u?{Success:u.Success,Message:u.Message,Steps:u.PipelineSteps,GitCommitSuccess:u.GitCommitSuccess,APIRestarted:u.APIRestarted,EntityMapsCreated:u.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:u.ConnectorResults?.[0]?.SyncRunID,Warnings:u.ConnectorResults?.flatMap(h=>h.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
|
|
1989
1995
|
$input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1990
1996
|
) {
|
|
1991
1997
|
IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
@@ -2027,5 +2033,5 @@ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0})
|
|
|
2027
2033
|
IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
|
|
2028
2034
|
Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
|
|
2029
2035
|
}
|
|
2030
|
-
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return l(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Ge as ActionItemInput,Ve as ActionItemOutput,Z as BrowserIndexedDBStorageProvider,X as BrowserStorageProviderBase,
|
|
2036
|
+
}`;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 l(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Ge as ActionItemInput,Ve as ActionItemOutput,Z as BrowserIndexedDBStorageProvider,X as BrowserStorageProviderBase,A as FieldMapper,w as FireAndForgetHelper,Oe as GetDataOutput,H as GraphQLAIClient,Be as GraphQLActionClient,Ze as GraphQLClassifyClient,Xe as GraphQLClusterClient,tt as GraphQLComponentRegistryClient,I as GraphQLDataProvider,He as GraphQLEncryptionClient,st as GraphQLFileStorageClient,at as GraphQLIntegrationClient,je as GraphQLListsClient,Ye as GraphQLLiveKitClient,be as GraphQLProviderConfigData,nt as GraphQLSearchClient,_e as GraphQLSystemUserClient,et as GraphQLTestingClient,z as GraphQLTransactionGroup,rt as GraphQLVersionHistoryClient,F as PACKAGE_VERSION,Le as RoleInput,Qe as RolesAndUsersInput,qe as SimpleRemoteEntity,Ke as SimpleRemoteEntityField,ke as SimpleRemoteEntityOutput,ee as SyncDataAction,Ue as SyncDataResult,Te as SyncRolesAndUsersResult,Fe as UserInput,ht as gql,xe as setupGraphQLClient};
|
|
2031
2037
|
//# sourceMappingURL=index.mjs.map
|