@memberjunction/graphql-dataprovider 2.111.0 → 2.112.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.mjs CHANGED
@@ -1,148 +1,142 @@
1
- var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0});var h;import{gql as m,GraphQLClient as ye}from"graphql-request";import{gql as je}from"graphql-request";import{TransactionGroupBase as Ee,TransactionResult as $e,LogError as d,ProviderConfigDataBase as Pe,ProviderBase as Ne,UserInfo as me,ProviderType as ve,BaseEntityResult as ge,EntityFieldTSType as E,TransactionItem as pe,UserRoleInfo as Ce,SetProvider as Ve}from"@memberjunction/core";import{ViewInfo as fe}from"@memberjunction/core-entities";import{openDB as xe}from"@tempfix/idb";import{Observable as Se}from"rxjs";import{createClient as Re}from"graphql-ws";import{v4 as Qe}from"uuid";import{SafeJSONParse as N,MJGlobal as Ge,MJEventType as Fe}from"@memberjunction/global";const J=class J{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(J,"FieldMapper");let P=J;const j=class j extends Ee{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m`
2
- mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
- ExecuteTransactionGroup(group: $group) {
4
- Success
5
- ErrorMessages
6
- ResultsJSON
7
- }
1
+ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0});var h;import{gql as m,GraphQLClient as ye}from"graphql-request";import{gql as Je}from"graphql-request";import{TransactionGroupBase as Ee,SafeJSONParse as N,TransactionResult as $e,LogError as d,ProviderConfigDataBase as Pe,ProviderBase as Ne,UserInfo as me,ProviderType as ve,BaseEntityResult as ge,EntityFieldTSType as E,TransactionItem as pe,UserRoleInfo as Ce,SetProvider as Ve,MJGlobal as xe,MJEventType as Qe}from"@memberjunction/global";import{ViewInfo as fe}from"@memberjunction/core-entities";import{openDB as Ge}from"@tempfix/idb";import{Observable as Se}from"rxjs";import{createClient as Re}from"graphql-ws";import{v4 as Fe}from"uuid";const J=class J{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(J,"FieldMapper");let P=J;const j=class j extends Ee{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m`
2
+ mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
+ ExecuteTransactionGroup(group: $group) {
4
+ Success
5
+ ErrorMessages
6
+ ResultsJSON
8
7
  }
9
- `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=a.ResultsJSON[i],u=N(o),p=this.PendingTransactions[i];n.push(new $e(p,u,u!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(j,"GraphQLTransactionGroup");let v=j;const z=class z{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m`
10
- mutation RunAIPrompt(
11
- $promptId: String!,
12
- $data: String,
13
- $overrideModelId: String,
14
- $overrideVendorId: String,
15
- $configurationId: String,
16
- $skipValidation: Boolean,
17
- $templateData: String,
18
- $responseFormat: String,
19
- $temperature: Float,
20
- $topP: Float,
21
- $topK: Int,
22
- $minP: Float,
23
- $frequencyPenalty: Float,
24
- $presencePenalty: Float,
25
- $seed: Int,
26
- $stopSequences: [String!],
27
- $includeLogProbs: Boolean,
28
- $topLogProbs: Int,
29
- $messages: String,
30
- $rerunFromPromptRunID: String,
31
- $systemPromptOverride: String
32
- ) {
33
- RunAIPrompt(
34
- promptId: $promptId,
35
- data: $data,
36
- overrideModelId: $overrideModelId,
37
- overrideVendorId: $overrideVendorId,
38
- configurationId: $configurationId,
39
- skipValidation: $skipValidation,
40
- templateData: $templateData,
41
- responseFormat: $responseFormat,
42
- temperature: $temperature,
43
- topP: $topP,
44
- topK: $topK,
45
- minP: $minP,
46
- frequencyPenalty: $frequencyPenalty,
47
- presencePenalty: $presencePenalty,
48
- seed: $seed,
49
- stopSequences: $stopSequences,
50
- includeLogProbs: $includeLogProbs,
51
- topLogProbs: $topLogProbs,
52
- messages: $messages,
53
- rerunFromPromptRunID: $rerunFromPromptRunID,
54
- systemPromptOverride: $systemPromptOverride
55
- ) {
56
- success
57
- output
58
- parsedResult
59
- error
60
- executionTimeMs
61
- tokensUsed
62
- promptRunId
63
- rawResult
64
- validationResult
65
- chatResult
66
- }
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,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=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:a}}handlePromptError(e){const t=e;return d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{console.log("[GraphQLAIClient] Received statusUpdate message:",o);const u=JSON.parse(o);if(console.log("[GraphQLAIClient] Parsed message:",u),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){console.log("[GraphQLAIClient] Forwarding progress to callback:",u.data.progress);const p={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(p)}else console.log("[GraphQLAIClient] Message does not match filter criteria:",{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",o)}}));const a=m`
69
- mutation RunAIAgent(
70
- $agentId: String!,
71
- $messages: String!,
72
- $sessionId: String!,
73
- $data: String,
74
- $payload: String,
75
- $templateData: String,
76
- $lastRunId: String,
77
- $autoPopulateLastRunPayload: Boolean,
78
- $configurationId: String,
79
- $conversationDetailId: String,
80
- $createArtifacts: Boolean,
81
- $createNotification: Boolean,
82
- $sourceArtifactId: String,
83
- $sourceArtifactVersionId: String
84
- ) {
85
- RunAIAgent(
86
- agentId: $agentId,
87
- messages: $messages,
88
- sessionId: $sessionId,
89
- data: $data,
90
- payload: $payload,
91
- templateData: $templateData,
92
- lastRunId: $lastRunId,
93
- autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
94
- configurationId: $configurationId,
95
- conversationDetailId: $conversationDetailId,
96
- createArtifacts: $createArtifacts,
97
- createNotification: $createNotification,
98
- sourceArtifactId: $sourceArtifactId,
99
- sourceArtifactVersionId: $sourceArtifactVersionId
100
- ) {
101
- success
102
- errorMessage
103
- executionTimeMs
104
- result
105
- }
106
- }
107
- `,n=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,n);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return N(e)}handleAgentError(e){return d(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=m`
108
- mutation ExecuteSimplePrompt(
109
- $systemPrompt: String!,
110
- $messages: String,
111
- $preferredModels: [String!],
112
- $modelPower: String,
113
- $responseFormat: String
114
- ) {
115
- ExecuteSimplePrompt(
116
- systemPrompt: $systemPrompt,
117
- messages: $messages,
118
- preferredModels: $preferredModels,
119
- modelPower: $modelPower,
120
- responseFormat: $responseFormat
121
- ) {
122
- success
123
- result
124
- resultObject
125
- modelName
126
- error
127
- executionTimeMs
128
- }
129
- }
130
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return d(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m`
131
- mutation EmbedText(
132
- $textToEmbed: [String!]!,
133
- $modelSize: String!
134
- ) {
135
- EmbedText(
136
- textToEmbed: $textToEmbed,
137
- modelSize: $modelSize
138
- ) {
139
- embeddings
140
- modelName
141
- vectorDimensions
142
- error
143
- }
144
- }
145
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return d(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(z,"GraphQLAIClient");let C=z;const W=class W extends Pe{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 URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,i,o){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,RefreshTokenFunction:s},a,n,i)}};f(W,"GraphQLProviderConfigData");let V=W;const he=(h=class extends Ne{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
8
+ }
9
+ `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=a.ResultsJSON[i],u=N(o),p=this.PendingTransactions[i];n.push(new $e(p,u,u!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(j,"GraphQLTransactionGroup");let v=j;const z=class z{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m`
10
+ mutation RunAIPrompt(
11
+ $promptId: String!
12
+ $data: String
13
+ $overrideModelId: String
14
+ $overrideVendorId: String
15
+ $configurationId: String
16
+ $skipValidation: Boolean
17
+ $templateData: String
18
+ $responseFormat: String
19
+ $temperature: Float
20
+ $topP: Float
21
+ $topK: Int
22
+ $minP: Float
23
+ $frequencyPenalty: Float
24
+ $presencePenalty: Float
25
+ $seed: Int
26
+ $stopSequences: [String!]
27
+ $includeLogProbs: Boolean
28
+ $topLogProbs: Int
29
+ $messages: String
30
+ $rerunFromPromptRunID: String
31
+ $systemPromptOverride: String
32
+ ) {
33
+ RunAIPrompt(
34
+ promptId: $promptId
35
+ data: $data
36
+ overrideModelId: $overrideModelId
37
+ overrideVendorId: $overrideVendorId
38
+ configurationId: $configurationId
39
+ skipValidation: $skipValidation
40
+ templateData: $templateData
41
+ responseFormat: $responseFormat
42
+ temperature: $temperature
43
+ topP: $topP
44
+ topK: $topK
45
+ minP: $minP
46
+ frequencyPenalty: $frequencyPenalty
47
+ presencePenalty: $presencePenalty
48
+ seed: $seed
49
+ stopSequences: $stopSequences
50
+ includeLogProbs: $includeLogProbs
51
+ topLogProbs: $topLogProbs
52
+ messages: $messages
53
+ rerunFromPromptRunID: $rerunFromPromptRunID
54
+ systemPromptOverride: $systemPromptOverride
55
+ ) {
56
+ success
57
+ output
58
+ parsedResult
59
+ error
60
+ executionTimeMs
61
+ tokensUsed
62
+ promptRunId
63
+ rawResult
64
+ validationResult
65
+ chatResult
66
+ }
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,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=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:a}}handlePromptError(e){const t=e;return d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{console.log("[GraphQLAIClient] Received statusUpdate message:",o);const u=JSON.parse(o);if(console.log("[GraphQLAIClient] Parsed message:",u),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){console.log("[GraphQLAIClient] Forwarding progress to callback:",u.data.progress);const p={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(p)}else console.log("[GraphQLAIClient] Message does not match filter criteria:",{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",o)}}));const a=m`
69
+ mutation RunAIAgent(
70
+ $agentId: String!
71
+ $messages: String!
72
+ $sessionId: String!
73
+ $data: String
74
+ $payload: String
75
+ $templateData: String
76
+ $lastRunId: String
77
+ $autoPopulateLastRunPayload: Boolean
78
+ $configurationId: String
79
+ $conversationDetailId: String
80
+ $createArtifacts: Boolean
81
+ $createNotification: Boolean
82
+ $sourceArtifactId: String
83
+ $sourceArtifactVersionId: String
84
+ ) {
85
+ RunAIAgent(
86
+ agentId: $agentId
87
+ messages: $messages
88
+ sessionId: $sessionId
89
+ data: $data
90
+ payload: $payload
91
+ templateData: $templateData
92
+ lastRunId: $lastRunId
93
+ autoPopulateLastRunPayload: $autoPopulateLastRunPayload
94
+ configurationId: $configurationId
95
+ conversationDetailId: $conversationDetailId
96
+ createArtifacts: $createArtifacts
97
+ createNotification: $createNotification
98
+ sourceArtifactId: $sourceArtifactId
99
+ sourceArtifactVersionId: $sourceArtifactVersionId
100
+ ) {
101
+ success
102
+ errorMessage
103
+ executionTimeMs
104
+ result
105
+ }
106
+ }
107
+ `,n=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,n);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return N(e)}handleAgentError(e){return d(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=m`
108
+ mutation ExecuteSimplePrompt(
109
+ $systemPrompt: String!
110
+ $messages: String
111
+ $preferredModels: [String!]
112
+ $modelPower: String
113
+ $responseFormat: String
114
+ ) {
115
+ ExecuteSimplePrompt(
116
+ systemPrompt: $systemPrompt
117
+ messages: $messages
118
+ preferredModels: $preferredModels
119
+ modelPower: $modelPower
120
+ responseFormat: $responseFormat
121
+ ) {
122
+ success
123
+ result
124
+ resultObject
125
+ modelName
126
+ error
127
+ executionTimeMs
128
+ }
129
+ }
130
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return d(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m`
131
+ mutation EmbedText($textToEmbed: [String!]!, $modelSize: String!) {
132
+ EmbedText(textToEmbed: $textToEmbed, modelSize: $modelSize) {
133
+ embeddings
134
+ modelName
135
+ vectorDimensions
136
+ error
137
+ }
138
+ }
139
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return d(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(z,"GraphQLAIClient");let C=z;const W=class W extends Pe{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 URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,i,o){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,RefreshTokenFunction:s},a,n,i)}};f(W,"GraphQLProviderConfigData");let V=W;const he=(h=class extends Ne{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
146
140
  ${this.userInfoString()}
147
141
  UserRoles_UserIDArray {
148
142
  ${this.userRoleInfoString()}
@@ -150,16 +144,17 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
150
144
  }
151
145
  `,this._currentUserQuery=m`query CurrentUserAndRoles {
152
146
  ${this._innerCurrentUserQueryString}
153
- }`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new C(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Qe()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return r?(this._configData=e,this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId)),super.Config(e)}catch(a){throw d(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new me(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
154
- query GetReportDataQuery ($ReportID: String!) {
155
- GetReportData(ReportID: $ReportID) {
156
- Success
157
- Results
158
- RowCount
159
- ExecutionTime
160
- ErrorMessage
161
- }
162
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,n,i){const o=m`
147
+ }`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new C(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Fe()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return r?(this._configData=e,this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId)),super.Config(e)}catch(a){throw d(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new me(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
148
+ query GetReportDataQuery($ReportID: String!) {
149
+ GetReportData(ReportID: $ReportID) {
150
+ Success
151
+ Results
152
+ RowCount
153
+ ExecutionTime
154
+ ErrorMessage
155
+ }
156
+ }
157
+ `,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,n,i){const o=m`
163
158
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
164
159
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
165
160
  ${this.QueryReturnFieldList}
@@ -195,75 +190,82 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
195
190
  ErrorMessage
196
191
  }
197
192
  }`,y=await this.ExecuteGQL(D,{input:a});if(y&&y[r]){const c=y[r].Results;if(c&&c.length>0){const R=o.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);c.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(w=>{S[w.Name]=S[w.CodeName]})})}const l=y[r];return await this.PostProcessRunView(l,e,t),l}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const o of e){let u="",p="";const g={};let D=null,y=null;if(o.ViewEntity)y=o.ViewEntity,D=y.Get("Entity");else{const{entityName:S,v:w}=await this.getEntityNameAndUserView(o,t);y=w,D=S}const c=this.Entities.find(S=>S.Name===D);if(!c)throw new Error(`Entity ${D} not found in metadata`);s.push(c);let l=!1;const R=this.getGraphQLTypeNameBase(c);o.ViewID?(u=`Run${R}ViewByID`,p="RunViewByIDInput",g.ViewID=o.ViewID):o.ViewName?(u=`Run${R}ViewByName`,p="RunViewByNameInput",g.ViewName=o.ViewName):(l=!0,u=`Run${R}DynamicView`,p="RunDynamicViewInput",g.EntityName=o.EntityName),g.ExtraFilter=o.ExtraFilter||"",g.OrderBy=o.OrderBy||"",g.UserSearchString=o.UserSearchString||"",g.Fields=o.Fields,g.IgnoreMaxRows=o.IgnoreMaxRows||!1,o.MaxRows!==void 0&&(g.MaxRows=o.MaxRows),o.StartRow!==void 0&&(g.StartRow=o.StartRow),g.ForceAuditLog=o.ForceAuditLog||!1,g.ResultType=o.ResultType||"simple",o.AuditLogDescription&&o.AuditLogDescription.length>0&&(g.AuditLogDescription=o.AuditLogDescription),l||(g.ExcludeUserViewRunID=o.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=o.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=o.OverrideExcludeFilter||"",g.SaveViewResults=o.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(c,y,o,l))}const n=m`
198
- query RunViewsQuery ($input: [RunViewGenericInput!]!) {
199
- RunViews(input: $input) {
200
- Results {
201
- PrimaryKey {
202
- FieldName
203
- Value
204
- }
205
- EntityID
206
- Data
207
- }
208
- UserViewRunID
209
- RowCount
210
- TotalRowCount
211
- ExecutionTime
212
- Success
213
- ErrorMessage
214
- }
215
- }`,i=await this.ExecuteGQL(n,{input:r});if(i&&i.RunViews){const o=i.RunViews;for(const[u,p]of o.entries())p.Results=p.Results.map(g=>{let D=JSON.parse(g.Data);return this.ConvertBackToMJFields(D),D});return await this.PostProcessRunViews(o,e,t),o}return null}catch(r){throw d(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await fe.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await fe.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 a=[],n=new P;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(n.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(n.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(n.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return ve.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw d(r),r}}async GetRecordDependencies(e,t){try{const r=m`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
216
- GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
217
- EntityName
218
- RelatedEntityName
219
- FieldName
220
- CompositeKey {
221
- KeyValuePairs {
222
- FieldName
223
- Value
224
- }
225
- }
226
- }
227
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw d(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
228
- GetRecordDuplicates(params: $params) {
229
- Status
230
- ErrorMessage
231
- PotentialDuplicateResult {
232
- EntityID
233
- DuplicateRunDetailMatchRecordIDs
234
- RecordPrimaryKeys {
235
- KeyValuePairs {
236
- FieldName
237
- Value
238
- }
239
- }
240
- Duplicates {
241
- ProbabilityScore
242
- KeyValuePairs {
243
- FieldName
244
- Value
245
- }
246
- }
247
- }
193
+ query RunViewsQuery($input: [RunViewGenericInput!]!) {
194
+ RunViews(input: $input) {
195
+ Results {
196
+ PrimaryKey {
197
+ FieldName
198
+ Value
199
+ }
200
+ EntityID
201
+ Data
248
202
  }
249
- }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(n=>n.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=m`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
250
- MergeRecords(request: $request) {
251
- Success
252
- OverallStatus
253
- RecordMergeLogID
254
- RecordStatus {
255
- CompositeKey {
256
- KeyValuePairs {
257
- FieldName
258
- Value
259
- }
260
- }
261
- Success
262
- RecordMergeDeletionLogID
263
- Message
264
- }
265
- }
266
- }`,n={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(a,{request:n}))?.MergeRecords}catch(a){return d(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new ge;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=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.ResultHistory.push(s);const i=this.getGraphQLTypeNameBase(e.EntityInfo),o=`${n}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new P,g=` ${o}(input: $input) {
203
+ UserViewRunID
204
+ RowCount
205
+ TotalRowCount
206
+ ExecutionTime
207
+ Success
208
+ ErrorMessage
209
+ }
210
+ }
211
+ `,i=await this.ExecuteGQL(n,{input:r});if(i&&i.RunViews){const o=i.RunViews;for(const[u,p]of o.entries())p.Results=p.Results.map(g=>{let D=JSON.parse(g.Data);return this.ConvertBackToMJFields(D),D});return await this.PostProcessRunViews(o,e,t),o}return null}catch(r){throw d(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await fe.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await fe.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 a=[],n=new P;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(n.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(n.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(n.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return ve.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw d(r),r}}async GetRecordDependencies(e,t){try{const r=m`
212
+ query GetRecordDependenciesQuery($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
213
+ GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
214
+ EntityName
215
+ RelatedEntityName
216
+ FieldName
217
+ CompositeKey {
218
+ KeyValuePairs {
219
+ FieldName
220
+ Value
221
+ }
222
+ }
223
+ }
224
+ }
225
+ `,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw d(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m`
226
+ query GetRecordDuplicatesQuery($params: PotentialDuplicateRequestType!) {
227
+ GetRecordDuplicates(params: $params) {
228
+ Status
229
+ ErrorMessage
230
+ PotentialDuplicateResult {
231
+ EntityID
232
+ DuplicateRunDetailMatchRecordIDs
233
+ RecordPrimaryKeys {
234
+ KeyValuePairs {
235
+ FieldName
236
+ Value
237
+ }
238
+ }
239
+ Duplicates {
240
+ ProbabilityScore
241
+ KeyValuePairs {
242
+ FieldName
243
+ Value
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+ `;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(n=>n.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=m`
250
+ mutation MergeRecordsMutation($request: RecordMergeRequest!) {
251
+ MergeRecords(request: $request) {
252
+ Success
253
+ OverallStatus
254
+ RecordMergeLogID
255
+ RecordStatus {
256
+ CompositeKey {
257
+ KeyValuePairs {
258
+ FieldName
259
+ Value
260
+ }
261
+ }
262
+ Success
263
+ RecordMergeDeletionLogID
264
+ Message
265
+ }
266
+ }
267
+ }
268
+ `,n={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(a,{request:n}))?.MergeRecords}catch(a){return d(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new ge;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=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.ResultHistory.push(s);const i=this.getGraphQLTypeNameBase(e.EntityInfo),o=`${n}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new P,g=` ${o}(input: $input) {
267
269
  ${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
268
270
  `)}
269
271
  }`,D=m`mutation ${n}${i} ($input: ${o}Input!) {
@@ -288,74 +290,91 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
288
290
  `,y=m`mutation ${g} (${o}, $options___: DeleteOptionsInput!) {
289
291
  ${D}
290
292
  }
291
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new pe(e,"Delete",D,a,{mutationName:g,mutationInputTypes:n},(c,l)=>{if(s.EndedAt=new Date,l&&c){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==c[S.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 c=await this.ExecuteGQL(y,a);if(c&&c[g]){const l=c[g];for(let R of e.PrimaryKey.KeyValuePairs){let S=l[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof S=="number"&&(S=S.toString()),w!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,d(a),!1}}async GetDatasetByName(e,t){const r=m`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
292
- GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
293
- DatasetID
294
- DatasetName
295
- Success
296
- Status
297
- LatestUpdateDate
298
- Results
299
- }
300
- }`,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}}async GetDatasetStatusByName(e,t){const r=m`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
301
- GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
302
- DatasetID
303
- DatasetName
304
- Success
305
- Status
306
- LatestUpdateDate
307
- EntityUpdateDates
308
- }
309
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new v(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(o=>o.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=m`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
310
- GetRecordFavoriteStatus(params: $params) {
311
- Success
312
- IsFavorite
313
- }
314
- }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const n=this.Entities.find(u=>u.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const i=m`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
315
- SetRecordFavoriteStatus(params: $params){
316
- Success
317
- }
318
- }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
319
- GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
320
- Success
321
- Status
322
- RecordName
323
- }
324
- }`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=m`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
325
- GetEntityRecordNames(info: $info) {
326
- Success
327
- Status
328
- CompositeKey {
329
- KeyValuePairs {
330
- FieldName
331
- Value
332
- }
333
- }
334
- EntityName
335
- RecordName
293
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new pe(e,"Delete",D,a,{mutationName:g,mutationInputTypes:n},(c,l)=>{if(s.EndedAt=new Date,l&&c){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==c[S.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 c=await this.ExecuteGQL(y,a);if(c&&c[g]){const l=c[g];for(let R of e.PrimaryKey.KeyValuePairs){let S=l[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof S=="number"&&(S=S.toString()),w!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,d(a),!1}}async GetDatasetByName(e,t){const r=m`
294
+ query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
295
+ GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
296
+ DatasetID
297
+ DatasetName
298
+ Success
299
+ Status
300
+ LatestUpdateDate
301
+ Results
302
+ }
303
+ }
304
+ `,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}}async GetDatasetStatusByName(e,t){const r=m`
305
+ query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
306
+ GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
307
+ DatasetID
308
+ DatasetName
309
+ Success
310
+ Status
311
+ LatestUpdateDate
312
+ EntityUpdateDates
313
+ }
314
+ }
315
+ `,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new v(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(o=>o.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=m`
316
+ query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
317
+ GetRecordFavoriteStatus(params: $params) {
318
+ Success
319
+ IsFavorite
320
+ }
321
+ }
322
+ `,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const n=this.Entities.find(u=>u.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const i=m`
323
+ mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
324
+ SetRecordFavoriteStatus(params: $params) {
325
+ Success
326
+ }
327
+ }
328
+ `,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m`
329
+ query GetEntityRecordNameQuery($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
330
+ GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
331
+ Success
332
+ Status
333
+ RecordName
334
+ }
335
+ }
336
+ `,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=m`
337
+ query GetEntityRecordNamesQuery($info: [EntityRecordNameInput!]!) {
338
+ GetEntityRecordNames(info: $info) {
339
+ Success
340
+ Status
341
+ CompositeKey {
342
+ KeyValuePairs {
343
+ FieldName
344
+ Value
336
345
  }
337
- }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=m`query GetDataContextData ($DataContextID: String!) {
338
- GetDataContextData(DataContextID: $DataContextID) {
339
- Success
340
- ErrorMessages
341
- Results
342
- }
343
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw d(t),t}}async GetDataContextItemData(e){try{const t=m`query GetDataContextItemData ($DataContextItemID: String!) {
344
- GetDataContextItemData(DataContextItemID: $DataContextItemID) {
345
- Success
346
- ErrorMessage
347
- Result
348
- }
349
- }`,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 d(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(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 d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new ye(e,{headers:a})}userInfoString(){return this.infoString(new me(null,null))}userRoleInfoString(){return this.infoString(new Ce(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
346
+ }
347
+ EntityName
348
+ RecordName
349
+ }
350
+ }
351
+ `,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=m`
352
+ query GetDataContextData($DataContextID: String!) {
353
+ GetDataContextData(DataContextID: $DataContextID) {
354
+ Success
355
+ ErrorMessages
356
+ Results
357
+ }
358
+ }
359
+ `,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw d(t),t}}async GetDataContextItemData(e){try{const t=m`
360
+ query GetDataContextItemData($DataContextItemID: String!) {
361
+ GetDataContextItemData(DataContextItemID: $DataContextItemID) {
362
+ Success
363
+ ErrorMessage
364
+ Result
365
+ }
366
+ }
367
+ `,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 d(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(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 d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new ye(e,{headers:a})}userInfoString(){return this.infoString(new me(null,null))}userRoleInfoString(){return this.infoString(new Ce(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
350
368
  `:s.startsWith("_")||(t+=s+`
351
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new Q),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=Re({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new Se(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=Re({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=m`subscription StatusUpdates($sessionId: String!) {
352
- statusUpdates(sessionId: $sessionId) {
353
- date
354
- message
355
- sessionId
356
- }
369
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new Q),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=Re({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new Se(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=Re({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=m`
370
+ subscription StatusUpdates($sessionId: String!) {
371
+ statusUpdates(sessionId: $sessionId) {
372
+ date
373
+ message
374
+ sessionId
357
375
  }
358
- `,s=new Se(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates.message),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}},f(h,"_GraphQLDataProvider"),h);he.MJ_CORE_SCHEMA="__mj";let De=he;const H=class H{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(H,"BrowserStorageProviderBase");let x=H;const Te="MJ_Metadata",$="Metadata_KVPairs",X=class X extends x{constructor(){super(),this.dbPromise=xe(Te,1,{upgrade(e){e.objectStoreNames.contains($)||e.createObjectStore($)}})}async setItem(e,t){const s=(await this.dbPromise).transaction($,"readwrite");await s.objectStore($).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction($).objectStore($).get(e)}async remove(e){const r=(await this.dbPromise).transaction($,"readwrite");await r.objectStore($).delete(e),await r.done}};f(X,"BrowserIndexedDBStorageProvider");let Q=X;async function Ue(I){const e=new De;return Ve(e),await e.Config(I),Ge.Instance.RaiseEvent({event:Fe.LoggedIn,eventCode:null,component:this,args:null}),e}f(Ue,"setupGraphQLClient");const Z=class Z{};f(Z,"SyncRolesAndUsersResult");let G=Z;const Y=class Y{};f(Y,"RoleInput");let F=Y;const ee=class ee{};f(ee,"UserInput");let T=ee;const te=class te{};f(te,"RolesAndUsersInput");let U=te;var Ie=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(Ie||{});const re=class re{};f(re,"ActionItemInput");let b=re;const se=class se{constructor(){this.Results=[]}};f(se,"SyncDataResult");let M=se;const ae=class ae{};f(ae,"ActionItemOutput");let L=ae;const ne=class ne{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new ye(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
376
+ }
377
+ `,s=new Se(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates.message),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}},f(h,"_GraphQLDataProvider"),h);he.MJ_CORE_SCHEMA="__mj";let De=he;const H=class H{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(H,"BrowserStorageProviderBase");let x=H;const Te="MJ_Metadata",$="Metadata_KVPairs",X=class X extends x{constructor(){super(),this.dbPromise=Ge(Te,1,{upgrade(e){e.objectStoreNames.contains($)||e.createObjectStore($)}})}async setItem(e,t){const s=(await this.dbPromise).transaction($,"readwrite");await s.objectStore($).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction($).objectStore($).get(e)}async remove(e){const r=(await this.dbPromise).transaction($,"readwrite");await r.objectStore($).delete(e),await r.done}};f(X,"BrowserIndexedDBStorageProvider");let Q=X;async function Ue(I){const e=new De;return Ve(e),await e.Config(I),xe.Instance.RaiseEvent({event:Qe.LoggedIn,eventCode:null,component:this,args:null}),e}f(Ue,"setupGraphQLClient");const Z=class Z{};f(Z,"SyncRolesAndUsersResult");let G=Z;const Y=class Y{};f(Y,"RoleInput");let F=Y;const ee=class ee{};f(ee,"UserInput");let T=ee;const te=class te{};f(te,"RolesAndUsersInput");let U=te;var Ie=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(Ie||{});const re=class re{};f(re,"ActionItemInput");let b=re;const se=class se{constructor(){this.Results=[]}};f(se,"SyncDataResult");let M=se;const ae=class ae{};f(ae,"ActionItemOutput");let L=ae;const ne=class ne{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new ye(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
359
378
  GetData(input: $input) {
360
379
  Success
361
380
  ErrorMessages
@@ -591,229 +610,193 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
591
610
  QueryData
592
611
  }
593
612
  }`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return d(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=m`
594
- query RunAIPromptSystemUser(
595
- $promptId: String!,
596
- $data: String,
597
- $overrideModelId: String,
598
- $overrideVendorId: String,
599
- $configurationId: String,
600
- $skipValidation: Boolean,
601
- $templateData: String,
602
- $responseFormat: String,
603
- $temperature: Float,
604
- $topP: Float,
605
- $topK: Int,
606
- $minP: Float,
607
- $frequencyPenalty: Float,
608
- $presencePenalty: Float,
609
- $seed: Int,
610
- $stopSequences: [String!],
611
- $includeLogProbs: Boolean,
612
- $topLogProbs: Int,
613
- $messages: String,
614
- $rerunFromPromptRunID: String,
615
- $systemPromptOverride: String
616
- ) {
617
- RunAIPromptSystemUser(
618
- promptId: $promptId,
619
- data: $data,
620
- overrideModelId: $overrideModelId,
621
- overrideVendorId: $overrideVendorId,
622
- configurationId: $configurationId,
623
- skipValidation: $skipValidation,
624
- templateData: $templateData,
625
- responseFormat: $responseFormat,
626
- temperature: $temperature,
627
- topP: $topP,
628
- topK: $topK,
629
- minP: $minP,
630
- frequencyPenalty: $frequencyPenalty,
631
- presencePenalty: $presencePenalty,
632
- seed: $seed,
633
- stopSequences: $stopSequences,
634
- includeLogProbs: $includeLogProbs,
635
- topLogProbs: $topLogProbs,
636
- messages: $messages,
637
- rerunFromPromptRunID: $rerunFromPromptRunID,
638
- systemPromptOverride: $systemPromptOverride
639
- ) {
640
- success
641
- output
642
- parsedResult
643
- error
644
- executionTimeMs
645
- tokensUsed
646
- promptRunId
647
- rawResult
648
- validationResult
649
- chatResult
650
- }
651
- }
652
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return d(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m`
653
- query RunAIAgentSystemUser(
654
- $agentId: String!,
655
- $messages: String!,
656
- $sessionId: String!,
657
- $data: String,
658
- $templateData: String,
659
- $lastRunId: String,
660
- $autoPopulateLastRunPayload: Boolean,
661
- $configurationId: String
662
- ) {
663
- RunAIAgentSystemUser(
664
- agentId: $agentId,
665
- messages: $messages,
666
- sessionId: $sessionId,
667
- data: $data,
668
- templateData: $templateData,
669
- lastRunId: $lastRunId,
670
- autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
671
- configurationId: $configurationId
672
- ) {
673
- success
674
- errorMessage
675
- executionTimeMs
676
- result
677
- }
678
- }
679
- `,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 d(`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 N(e)}async ExecuteSimplePrompt(e){try{const t=m`
680
- query ExecuteSimplePromptSystemUser(
681
- $systemPrompt: String!,
682
- $messages: String,
683
- $preferredModels: [String!],
684
- $modelPower: String,
685
- $responseFormat: String
686
- ) {
687
- ExecuteSimplePromptSystemUser(
688
- systemPrompt: $systemPrompt,
689
- messages: $messages,
690
- preferredModels: $preferredModels,
691
- modelPower: $modelPower,
692
- responseFormat: $responseFormat
693
- ) {
694
- success
695
- result
696
- resultObject
697
- modelName
698
- error
699
- executionTimeMs
700
- }
701
- }
702
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return d(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m`
703
- query EmbedTextSystemUser(
704
- $textToEmbed: [String!]!,
705
- $modelSize: String!
706
- ) {
707
- EmbedTextSystemUser(
708
- textToEmbed: $textToEmbed,
709
- modelSize: $modelSize
710
- ) {
711
- embeddings
712
- modelName
713
- vectorDimensions
714
- error
715
- }
716
- }
717
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return d(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ne,"GraphQLSystemUserClient");let A=ne;const oe=class oe{};f(oe,"GetDataOutput");let q=oe;const ie=class ie{};f(ie,"SimpleRemoteEntityOutput");let _=ie;const ue=class ue{};f(ue,"SimpleRemoteEntity");let O=ue;const ce=class ce{};f(ce,"SimpleRemoteEntityField");let B=ce;const le=class le{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=m`
718
- mutation RunAction($input: RunActionInput!) {
719
- RunAction(input: $input) {
720
- Success
721
- Message
722
- ResultCode
723
- ResultData
724
- }
725
- }
726
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){d(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return d(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m`
727
- mutation RunEntityAction($input: EntityActionInput!) {
728
- RunEntityAction(input: $input) {
729
- Success
730
- Message
731
- ResultData
732
- }
613
+ query RunAIPromptSystemUser(
614
+ $promptId: String!
615
+ $data: String
616
+ $overrideModelId: String
617
+ $overrideVendorId: String
618
+ $configurationId: String
619
+ $skipValidation: Boolean
620
+ $templateData: String
621
+ $responseFormat: String
622
+ $temperature: Float
623
+ $topP: Float
624
+ $topK: Int
625
+ $minP: Float
626
+ $frequencyPenalty: Float
627
+ $presencePenalty: Float
628
+ $seed: Int
629
+ $stopSequences: [String!]
630
+ $includeLogProbs: Boolean
631
+ $topLogProbs: Int
632
+ $messages: String
633
+ $rerunFromPromptRunID: String
634
+ $systemPromptOverride: String
635
+ ) {
636
+ RunAIPromptSystemUser(
637
+ promptId: $promptId
638
+ data: $data
639
+ overrideModelId: $overrideModelId
640
+ overrideVendorId: $overrideVendorId
641
+ configurationId: $configurationId
642
+ skipValidation: $skipValidation
643
+ templateData: $templateData
644
+ responseFormat: $responseFormat
645
+ temperature: $temperature
646
+ topP: $topP
647
+ topK: $topK
648
+ minP: $minP
649
+ frequencyPenalty: $frequencyPenalty
650
+ presencePenalty: $presencePenalty
651
+ seed: $seed
652
+ stopSequences: $stopSequences
653
+ includeLogProbs: $includeLogProbs
654
+ topLogProbs: $topLogProbs
655
+ messages: $messages
656
+ rerunFromPromptRunID: $rerunFromPromptRunID
657
+ systemPromptOverride: $systemPromptOverride
658
+ ) {
659
+ success
660
+ output
661
+ parsedResult
662
+ error
663
+ executionTimeMs
664
+ tokensUsed
665
+ promptRunId
666
+ rawResult
667
+ validationResult
668
+ chatResult
669
+ }
670
+ }
671
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return d(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m`
672
+ query RunAIAgentSystemUser(
673
+ $agentId: String!
674
+ $messages: String!
675
+ $sessionId: String!
676
+ $data: String
677
+ $templateData: String
678
+ $lastRunId: String
679
+ $autoPopulateLastRunPayload: Boolean
680
+ $configurationId: String
681
+ ) {
682
+ RunAIAgentSystemUser(
683
+ agentId: $agentId
684
+ messages: $messages
685
+ sessionId: $sessionId
686
+ data: $data
687
+ templateData: $templateData
688
+ lastRunId: $lastRunId
689
+ autoPopulateLastRunPayload: $autoPopulateLastRunPayload
690
+ configurationId: $configurationId
691
+ ) {
692
+ success
693
+ errorMessage
694
+ executionTimeMs
695
+ result
696
+ }
697
+ }
698
+ `,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 d(`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 N(e)}async ExecuteSimplePrompt(e){try{const t=m`
699
+ query ExecuteSimplePromptSystemUser(
700
+ $systemPrompt: String!
701
+ $messages: String
702
+ $preferredModels: [String!]
703
+ $modelPower: String
704
+ $responseFormat: String
705
+ ) {
706
+ ExecuteSimplePromptSystemUser(
707
+ systemPrompt: $systemPrompt
708
+ messages: $messages
709
+ preferredModels: $preferredModels
710
+ modelPower: $modelPower
711
+ responseFormat: $responseFormat
712
+ ) {
713
+ success
714
+ result
715
+ resultObject
716
+ modelName
717
+ error
718
+ executionTimeMs
719
+ }
720
+ }
721
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return d(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m`
722
+ query EmbedTextSystemUser($textToEmbed: [String!]!, $modelSize: String!) {
723
+ EmbedTextSystemUser(textToEmbed: $textToEmbed, modelSize: $modelSize) {
724
+ embeddings
725
+ modelName
726
+ vectorDimensions
727
+ error
728
+ }
729
+ }
730
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return d(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ne,"GraphQLSystemUserClient");let A=ne;const oe=class oe{};f(oe,"GetDataOutput");let q=oe;const ie=class ie{};f(ie,"SimpleRemoteEntityOutput");let _=ie;const ue=class ue{};f(ue,"SimpleRemoteEntity");let O=ue;const ce=class ce{};f(ce,"SimpleRemoteEntityField");let B=ce;const le=class le{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=m`
731
+ mutation RunAction($input: RunActionInput!) {
732
+ RunAction(input: $input) {
733
+ Success
734
+ Message
735
+ ResultCode
736
+ ResultData
737
+ }
738
+ }
739
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){d(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return d(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m`
740
+ mutation RunEntityAction($input: EntityActionInput!) {
741
+ RunEntityAction(input: $input) {
742
+ Success
743
+ Message
744
+ ResultData
745
+ }
746
+ }
747
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){d(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(le,"GraphQLActionClient");let k=le;const de=class de{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m`
748
+ query GetRegistryComponent($registryName: String!, $namespace: String!, $name: String!, $version: String, $hash: String) {
749
+ GetRegistryComponent(registryName: $registryName, namespace: $namespace, name: $name, version: $version, hash: $hash) {
750
+ hash
751
+ notModified
752
+ message
753
+ specification
754
+ }
755
+ }
756
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(n){return d(`Failed to parse component specification: ${n}`),null}}return null}return null}catch(t){throw d(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m`
757
+ query GetRegistryComponent($registryName: String!, $namespace: String!, $name: String!, $version: String, $hash: String) {
758
+ GetRegistryComponent(registryName: $registryName, namespace: $namespace, name: $name, version: $version, hash: $hash) {
759
+ hash
760
+ notModified
761
+ message
762
+ specification
763
+ }
764
+ }
765
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let n;if(a.specification)try{n=JSON.parse(a.specification)}catch(i){d(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),n=void 0}return{specification:n,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw d(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m`
766
+ query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
767
+ SearchRegistryComponents(params: $params) {
768
+ components
769
+ total
770
+ offset
771
+ limit
772
+ }
773
+ }
774
+ `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw d(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m`
775
+ query ResolveComponentDependencies($registryId: String!, $componentId: String!) {
776
+ ResolveComponentDependencies(registryId: $registryId, componentId: $componentId) {
777
+ componentId
778
+ name
779
+ namespace
780
+ version
781
+ circular
782
+ totalCount
783
+ dependencies {
784
+ componentId
785
+ name
786
+ namespace
787
+ version
788
+ circular
789
+ totalCount
733
790
  }
734
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){d(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(le,"GraphQLActionClient");let k=le;const de=class de{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m`
735
- query GetRegistryComponent(
736
- $registryName: String!,
737
- $namespace: String!,
738
- $name: String!,
739
- $version: String,
740
- $hash: String
741
- ) {
742
- GetRegistryComponent(
743
- registryName: $registryName,
744
- namespace: $namespace,
745
- name: $name,
746
- version: $version,
747
- hash: $hash
748
- ) {
749
- hash
750
- notModified
751
- message
752
- specification
753
- }
754
- }
755
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(n){return d(`Failed to parse component specification: ${n}`),null}}return null}return null}catch(t){throw d(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m`
756
- query GetRegistryComponent(
757
- $registryName: String!,
758
- $namespace: String!,
759
- $name: String!,
760
- $version: String,
761
- $hash: String
762
- ) {
763
- GetRegistryComponent(
764
- registryName: $registryName,
765
- namespace: $namespace,
766
- name: $name,
767
- version: $version,
768
- hash: $hash
769
- ) {
770
- hash
771
- notModified
772
- message
773
- specification
774
- }
775
- }
776
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let n;if(a.specification)try{n=JSON.parse(a.specification)}catch(i){d(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),n=void 0}return{specification:n,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw d(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m`
777
- query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
778
- SearchRegistryComponents(params: $params) {
779
- components
780
- total
781
- offset
782
- limit
783
- }
784
- }
785
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw d(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m`
786
- query ResolveComponentDependencies(
787
- $registryId: String!,
788
- $componentId: String!
789
- ) {
790
- ResolveComponentDependencies(
791
- registryId: $registryId,
792
- componentId: $componentId
793
- ) {
794
- componentId
795
- name
796
- namespace
797
- version
798
- circular
799
- totalCount
800
- dependencies {
801
- componentId
802
- name
803
- namespace
804
- version
805
- circular
806
- totalCount
807
- }
808
- }
809
- }
810
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw d(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return d(s),null}}async SendComponentFeedback(e){try{const t=m`
811
- mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
812
- SendComponentFeedback(feedback: $feedback) {
813
- success
814
- feedbackID
815
- error
816
- }
817
- }
818
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(de,"GraphQLComponentRegistryClient");let K=de;export{b as ActionItemInput,L as ActionItemOutput,P as FieldMapper,q as GetDataOutput,C as GraphQLAIClient,k as GraphQLActionClient,K as GraphQLComponentRegistryClient,De as GraphQLDataProvider,V as GraphQLProviderConfigData,A as GraphQLSystemUserClient,v as GraphQLTransactionGroup,F as RoleInput,U as RolesAndUsersInput,O as SimpleRemoteEntity,B as SimpleRemoteEntityField,_ as SimpleRemoteEntityOutput,Ie as SyncDataAction,M as SyncDataResult,G as SyncRolesAndUsersResult,T as UserInput,je as gql,Ue as setupGraphQLClient};
791
+ }
792
+ }
793
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw d(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return d(s),null}}async SendComponentFeedback(e){try{const t=m`
794
+ mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
795
+ SendComponentFeedback(feedback: $feedback) {
796
+ success
797
+ feedbackID
798
+ error
799
+ }
800
+ }
801
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(de,"GraphQLComponentRegistryClient");let K=de;export{b as ActionItemInput,L as ActionItemOutput,P as FieldMapper,q as GetDataOutput,C as GraphQLAIClient,k as GraphQLActionClient,K as GraphQLComponentRegistryClient,De as GraphQLDataProvider,V as GraphQLProviderConfigData,A as GraphQLSystemUserClient,v as GraphQLTransactionGroup,F as RoleInput,U as RolesAndUsersInput,O as SimpleRemoteEntity,B as SimpleRemoteEntityField,_ as SimpleRemoteEntityOutput,Ie as SyncDataAction,M as SyncDataResult,G as SyncRolesAndUsersResult,T as UserInput,Je as gql,Ue as setupGraphQLClient};
819
802
  //# sourceMappingURL=index.mjs.map