@memberjunction/graphql-dataprovider 5.3.1 → 5.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +184 -178
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +181 -73
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +181 -73
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +208 -202
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),b=require("@memberjunction/core-entities"),$=require("rxjs"),V=require("graphql-ws"),q=require("uuid"),C=require("@memberjunction/global"),_=require("@tempfix/idb");class A{static{p(this,"FieldMapper")}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}}class x extends u.TransactionGroupBase{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],c=C.SafeJSONParse(a),d=this.PendingTransactions[i];o.push(new u.TransactionResult(d,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class P{static{p(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:o,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,o,s);const a=await P.executeMutation(e);if(!e.validateAck(a)){s&&clearTimeout(s);const c=a?.errorMessage??"Server rejected the request";return u.LogError(`[FireAndForget:${t}] Server rejected: ${c}`),e.createErrorResult(c)}return u.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const o=n;throw u.LogError(`[FireAndForget:${t}] Error: ${o.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(o=>{try{const i=JSON.parse(o);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),u.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class L{static{p(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -65,85 +65,87 @@
|
|
|
65
65
|
chatResult
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
68
|
+
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:p(o=>o?.success===!0,"validateAck"),isCompletionEvent:p(o=>this.isAgentCompletionEvent(o),"isCompletionEvent"),extractResult:p(o=>this.extractAgentResult(o),"extractResult"),onMessage:e.onProgress?o=>this.forwardAgentProgress(o,e.onProgress):void 0,createErrorResult:p(o=>this.createAgentErrorResult(o),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return y.gql`
|
|
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
|
+
$fireAndForget: Boolean
|
|
85
|
+
) {
|
|
86
|
+
RunAIAgent(
|
|
87
|
+
agentId: $agentId,
|
|
88
|
+
messages: $messages,
|
|
89
|
+
sessionId: $sessionId,
|
|
90
|
+
data: $data,
|
|
91
|
+
payload: $payload,
|
|
92
|
+
templateData: $templateData,
|
|
93
|
+
lastRunId: $lastRunId,
|
|
94
|
+
autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
|
|
95
|
+
configurationId: $configurationId,
|
|
96
|
+
conversationDetailId: $conversationDetailId,
|
|
97
|
+
createArtifacts: $createArtifacts,
|
|
98
|
+
createNotification: $createNotification,
|
|
99
|
+
sourceArtifactId: $sourceArtifactId,
|
|
100
|
+
sourceArtifactVersionId: $sourceArtifactVersionId,
|
|
101
|
+
fireAndForget: $fireAndForget
|
|
84
102
|
) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
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
|
-
}
|
|
103
|
+
success
|
|
104
|
+
errorMessage
|
|
105
|
+
executionTimeMs
|
|
106
|
+
result
|
|
106
107
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
108
|
+
}
|
|
109
|
+
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return C.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);u.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let o;return s?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=r,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:p(s=>s?.success===!0,"validateAck"),isCompletionEvent:p(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:p(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,createErrorResult:p(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return y.gql`
|
|
110
|
+
mutation RunAIAgentFromConversationDetail(
|
|
111
|
+
$conversationDetailId: String!,
|
|
112
|
+
$agentId: String!,
|
|
113
|
+
$sessionId: String!,
|
|
114
|
+
$maxHistoryMessages: Int,
|
|
115
|
+
$data: String,
|
|
116
|
+
$payload: String,
|
|
117
|
+
$lastRunId: String,
|
|
118
|
+
$autoPopulateLastRunPayload: Boolean,
|
|
119
|
+
$configurationId: String,
|
|
120
|
+
$createArtifacts: Boolean,
|
|
121
|
+
$createNotification: Boolean,
|
|
122
|
+
$sourceArtifactId: String,
|
|
123
|
+
$sourceArtifactVersionId: String,
|
|
124
|
+
$fireAndForget: Boolean
|
|
125
|
+
) {
|
|
126
|
+
RunAIAgentFromConversationDetail(
|
|
127
|
+
conversationDetailId: $conversationDetailId,
|
|
128
|
+
agentId: $agentId,
|
|
129
|
+
sessionId: $sessionId,
|
|
130
|
+
maxHistoryMessages: $maxHistoryMessages,
|
|
131
|
+
data: $data,
|
|
132
|
+
payload: $payload,
|
|
133
|
+
lastRunId: $lastRunId,
|
|
134
|
+
autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
|
|
135
|
+
configurationId: $configurationId,
|
|
136
|
+
createArtifacts: $createArtifacts,
|
|
137
|
+
createNotification: $createNotification,
|
|
138
|
+
sourceArtifactId: $sourceArtifactId,
|
|
139
|
+
sourceArtifactVersionId: $sourceArtifactVersionId,
|
|
140
|
+
fireAndForget: $fireAndForget
|
|
123
141
|
) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
maxHistoryMessages: $maxHistoryMessages,
|
|
129
|
-
data: $data,
|
|
130
|
-
payload: $payload,
|
|
131
|
-
lastRunId: $lastRunId,
|
|
132
|
-
autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
|
|
133
|
-
configurationId: $configurationId,
|
|
134
|
-
createArtifacts: $createArtifacts,
|
|
135
|
-
createNotification: $createNotification,
|
|
136
|
-
sourceArtifactId: $sourceArtifactId,
|
|
137
|
-
sourceArtifactVersionId: $sourceArtifactVersionId,
|
|
138
|
-
fireAndForget: $fireAndForget
|
|
139
|
-
) {
|
|
140
|
-
success
|
|
141
|
-
errorMessage
|
|
142
|
-
executionTimeMs
|
|
143
|
-
result
|
|
144
|
-
}
|
|
142
|
+
success
|
|
143
|
+
errorMessage
|
|
144
|
+
executionTimeMs
|
|
145
|
+
result
|
|
145
146
|
}
|
|
146
|
-
|
|
147
|
+
}
|
|
148
|
+
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?C.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=y.gql`
|
|
147
149
|
mutation ExecuteSimplePrompt(
|
|
148
150
|
$systemPrompt: String!,
|
|
149
151
|
$messages: String,
|
|
@@ -166,7 +168,7 @@
|
|
|
166
168
|
executionTimeMs
|
|
167
169
|
}
|
|
168
170
|
}
|
|
169
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let
|
|
171
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=y.gql`
|
|
170
172
|
mutation EmbedText(
|
|
171
173
|
$textToEmbed: [String!]!,
|
|
172
174
|
$modelSize: String!
|
|
@@ -181,7 +183,7 @@
|
|
|
181
183
|
error
|
|
182
184
|
}
|
|
183
185
|
}
|
|
184
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const
|
|
186
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const v="default";class T{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||v;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||v).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||v).set(e,t)}async Remove(e,t){this.getCategoryMap(t||v).delete(e)}async ClearCategory(e){const t=e||v;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||v);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",K=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class G extends T{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,K,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||v;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||v;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||v,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||v,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const a=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class B extends u.ProviderConfigDataBase{static{p(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,o,i,a,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:s},n,o,i)}}class S extends u.ProviderBase{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
|
|
185
187
|
${this.userInfoString()}
|
|
186
188
|
MJUserRoles_UserIDArray {
|
|
187
189
|
${this.userRoleInfoString()}
|
|
@@ -189,7 +191,7 @@
|
|
|
189
191
|
}
|
|
190
192
|
`,this._currentUserQuery=y.gql`query CurrentUserAndRoles {
|
|
191
193
|
${this._innerCurrentUserQueryString}
|
|
192
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,
|
|
194
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,S._instance||(S._instance=this)}static get Instance(){return S._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(S.Instance._configData=e,S.Instance._sessionId===void 0&&(S.Instance._sessionId=await this.GetPreferredUUID(s)),S.Instance._client||(S.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,S.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await S.Instance.SaveStoredSessionID(S.Instance._sessionId),this._sessionId=S.Instance._sessionId,this._client=S.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}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.MJUserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.MJUserRoles_UserIDArray=r,new u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=y.gql`
|
|
193
195
|
query GetReportDataQuery ($ReportID: String!) {
|
|
194
196
|
GetReportData(ReportID: $ReportID) {
|
|
195
197
|
Success
|
|
@@ -204,25 +206,25 @@
|
|
|
204
206
|
${this.QueryReturnFieldList}
|
|
205
207
|
}
|
|
206
208
|
}
|
|
207
|
-
`,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const
|
|
209
|
+
`,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const o=await this.ExecuteGQL(s,{input:n});return o?.ExecuteAdhocQuery?this.TransformQueryPayload(o.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=y.gql`
|
|
208
210
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
209
211
|
RunQueries(input: $input) {
|
|
210
212
|
${this.QueryReturnFieldList}
|
|
211
213
|
}
|
|
212
214
|
}
|
|
213
|
-
`,s=e.map(
|
|
215
|
+
`,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i){const a=y.gql`
|
|
214
216
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
215
217
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
216
218
|
${this.QueryReturnFieldList}
|
|
217
219
|
}
|
|
218
220
|
}
|
|
219
|
-
`,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),
|
|
221
|
+
`,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const d=await this.ExecuteGQL(a,c);if(d&&d.GetQueryData)return this.TransformQueryPayload(d.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i){const a=y.gql`
|
|
220
222
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
221
223
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
222
224
|
${this.QueryReturnFieldList}
|
|
223
225
|
}
|
|
224
226
|
}
|
|
225
|
-
`,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),
|
|
227
|
+
`,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const d=await this.ExecuteGQL(a,c);if(d&&d.GetQueryDataByName)return this.TransformQueryPayload(d.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
226
228
|
Success
|
|
227
229
|
QueryID
|
|
228
230
|
QueryName
|
|
@@ -231,7 +233,7 @@
|
|
|
231
233
|
TotalRowCount
|
|
232
234
|
ExecutionTime
|
|
233
235
|
ErrorMessage
|
|
234
|
-
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(
|
|
236
|
+
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=y.gql`
|
|
235
237
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
236
238
|
RunQueriesWithCacheCheck(input: $input) {
|
|
237
239
|
success
|
|
@@ -247,14 +249,14 @@
|
|
|
247
249
|
}
|
|
248
250
|
}
|
|
249
251
|
}
|
|
250
|
-
`,
|
|
252
|
+
`,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const c=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:c,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:m,v:I}=await this.getEntityNameAndUserView(e,t);i=I,o=m}const a=this.Entities.find(m=>m.Name===o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const d=u.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${d}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${d}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(m=>({expression:m.expression,alias:m.alias})));const f=this.getViewRunTimeFieldList(a,i,e,c),R=e.Aggregates&&e.Aggregates.length>0?`
|
|
251
253
|
AggregateResults {
|
|
252
254
|
alias
|
|
253
255
|
expression
|
|
254
256
|
value
|
|
255
257
|
error
|
|
256
258
|
}
|
|
257
|
-
AggregateExecutionTime`:"",
|
|
259
|
+
AggregateExecutionTime`:"",l=y.gql`
|
|
258
260
|
query RunViewQuery ($input: ${s}!) {
|
|
259
261
|
${r}(input: $input) {
|
|
260
262
|
Results {
|
|
@@ -266,16 +268,16 @@
|
|
|
266
268
|
TotalRowCount
|
|
267
269
|
ExecutionTime
|
|
268
270
|
Success
|
|
269
|
-
ErrorMessage${
|
|
271
|
+
ErrorMessage${R}
|
|
270
272
|
}
|
|
271
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:
|
|
273
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(l,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const I=g[r].Results;if(I&&I.length>0){const w=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),w.forEach(N=>{D[N.Name]=D[N.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let f="",R="";const l={};let g=null,m=null;if(d.ViewEntity)m=d.ViewEntity,g=m.Get("Entity");else{const{entityName:D,v:N}=await this.getEntityNameAndUserView(d,t);m=N,g=D}const I=this.Entities.find(D=>D.Name===g);if(!I)throw new Error(`Entity ${g} not found in metadata`);s.push(I);let E=!1;const w=u.getGraphQLTypeNameBase(I);d.ViewID?(f=`Run${w}ViewByID`,R="RunViewByIDInput",l.ViewID=d.ViewID):d.ViewName?(f=`Run${w}ViewByName`,R="RunViewByNameInput",l.ViewName=d.ViewName):(E=!0,f=`Run${w}DynamicView`,R="RunDynamicViewInput",l.EntityName=d.EntityName),l.ExtraFilter=d.ExtraFilter||"",l.OrderBy=d.OrderBy||"",l.UserSearchString=d.UserSearchString||"",l.Fields=d.Fields,l.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(l.MaxRows=d.MaxRows),d.StartRow!==void 0&&(l.StartRow=d.StartRow),l.ForceAuditLog=d.ForceAuditLog||!1,l.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(l.AuditLogDescription=d.AuditLogDescription),E||(l.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",l.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,l.OverrideExcludeFilter=d.OverrideExcludeFilter||"",l.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(l.Aggregates=d.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(l),n.push(...this.getViewRunTimeFieldList(I,m,d,E))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
|
|
272
274
|
AggregateResults {
|
|
273
275
|
alias
|
|
274
276
|
expression
|
|
275
277
|
value
|
|
276
278
|
error
|
|
277
279
|
}
|
|
278
|
-
AggregateExecutionTime`:"",
|
|
280
|
+
AggregateExecutionTime`:"",a=y.gql`
|
|
279
281
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
280
282
|
RunViews(input: $input) {
|
|
281
283
|
Results {
|
|
@@ -293,7 +295,7 @@
|
|
|
293
295
|
Success
|
|
294
296
|
ErrorMessage${i}
|
|
295
297
|
}
|
|
296
|
-
}`,c=await this.ExecuteGQL(
|
|
298
|
+
}`,c=await this.ExecuteGQL(a,{input:r});if(c&&c.RunViews){const d=c.RunViews;for(const[f,R]of d.entries())R.Results=R.Results.map(l=>{let g=JSON.parse(l.Data);return this.ConvertBackToMJFields(g),g});return d}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=y.gql`
|
|
297
299
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
298
300
|
RunViewsWithCacheCheck(input: $input) {
|
|
299
301
|
success
|
|
@@ -326,7 +328,7 @@
|
|
|
326
328
|
}
|
|
327
329
|
}
|
|
328
330
|
}
|
|
329
|
-
`,
|
|
331
|
+
`,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,c)=>{const d=e[c];if(a.status==="differential"&&a.differentialData){const f=a.differentialData.updatedRows.map(R=>{const l=JSON.parse(R.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const f=a.Results.map(R=>{const l=JSON.parse(R.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:a.viewIndex,status:a.status,results:f,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await b.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await b.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],o=new A;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(o.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
330
332
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
331
333
|
EntityName
|
|
332
334
|
RelatedEntityName
|
|
@@ -360,7 +362,7 @@
|
|
|
360
362
|
}
|
|
361
363
|
}
|
|
362
364
|
}
|
|
363
|
-
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(
|
|
365
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=y.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
364
366
|
MergeRecords(request: $request) {
|
|
365
367
|
Success
|
|
366
368
|
OverallStatus
|
|
@@ -377,32 +379,32 @@
|
|
|
377
379
|
Message
|
|
378
380
|
}
|
|
379
381
|
}
|
|
380
|
-
}`,
|
|
381
|
-
${e.Fields.map(d
|
|
382
|
+
}`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const i=u.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,c=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),d=new A,f=` ${a}(input: $input) {
|
|
383
|
+
${e.Fields.map(l=>d.MapFieldName(l.CodeName)).join(`
|
|
382
384
|
`)}
|
|
383
|
-
}`,
|
|
385
|
+
}`,R=y.gql`mutation ${o}${i} ($input: ${a}Input!) {
|
|
384
386
|
${f}
|
|
385
387
|
}
|
|
386
|
-
`;for(let
|
|
387
|
-
${c}(${
|
|
388
|
-
${e.Fields.filter(
|
|
388
|
+
`;for(let l=0;l<c.length;l++){const g=c[l];let m=e.Get(g.Name);if(m)switch(g.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:m=m.getTime();break;case u.EntityFieldTSType.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case u.EntityFieldTSType.Number:if(typeof m!="number"){const I=Number(m);isNaN(I)||(m=I)}break}m===null&&g.EntityFieldInfo.AllowsNull===!1&&(g.EntityFieldInfo.DefaultValue!==null?m=g.EntityFieldInfo.DefaultValue:g.FieldType===u.EntityFieldTSType.Number||g.FieldType===u.EntityFieldTSType.Boolean?m=0:m=""),n.input[g.CodeName]=m}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const l=[];e.Fields.forEach(g=>{let m=null;g.OldValue!==null&&g.OldValue!==void 0&&(g.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?m=g.OldValue.getTime().toString():g.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?m=g.OldValue===!0?"1":"0":typeof g.OldValue!="string"?m=g.OldValue.toString():m=g.OldValue),l.push({Key:g.CodeName,Value:m})}),n.input.OldValues___=l}if(e.TransactionGroup){const l=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:a,mutationInputTypes:l},(g,m)=>{s.EndedAt=new Date,m&&g?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(g)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const l=await this.ExecuteGQL(R,n);if(l&&l[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(l[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let l=0;l<t.KeyValuePairs.length;l++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(l),I=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${g.CodeName}: $${g.CodeName}`,g.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(l)))throw new Error(`Primary Key value ${m} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(m)}else n[g.CodeName]=m}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),d=new A,f=y.gql`query Single${c}${a.length>0?"Full":""} (${i}) {
|
|
389
|
+
${c}(${o}) {
|
|
390
|
+
${e.Fields.filter(l=>!l.EntityFieldInfo.IsBinaryFieldType).map(l=>l.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?l.CodeName.replace("__mj_","_mj__"):l.CodeName).join(`
|
|
389
391
|
`)}
|
|
390
|
-
${
|
|
392
|
+
${a}
|
|
391
393
|
}
|
|
392
394
|
}
|
|
393
|
-
`,
|
|
395
|
+
`,R=await this.ExecuteGQL(f,n);return R&&R[c]?this.ConvertBackToMJFields(R[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new A().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],o=this.Entities.find(a=>a.ID===n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
394
396
|
${i} {
|
|
395
|
-
${
|
|
397
|
+
${o.Fields.map(a=>a.CodeName).join(`
|
|
396
398
|
`)}
|
|
397
399
|
}
|
|
398
|
-
`}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.ResultHistory.push(s);const n={},
|
|
399
|
-
`),c+=`${m.CodeName}`}
|
|
400
|
+
`}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.ResultHistory.push(s);const n={},o=[];let i="",a="",c="";for(let g of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(I=>I.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());n[m.CodeName]=m.Value,o.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,a.length>0&&(a+=", "),a+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
|
|
401
|
+
`),c+=`${m.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),R=y.gql`${f}(${i}, options___: $options___) {
|
|
400
402
|
${c}
|
|
401
403
|
}
|
|
402
|
-
`,
|
|
403
|
-
${
|
|
404
|
+
`,l=y.gql`mutation ${f} (${a}, $options___: DeleteOptionsInput!) {
|
|
405
|
+
${R}
|
|
404
406
|
}
|
|
405
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",
|
|
407
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,n,{mutationName:f,mutationInputTypes:o},(g,m)=>{if(s.EndedAt=new Date,m&&g){let I=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==g[E.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(l,n);if(g&&g[f]){const m=g[f];for(let I of e.PrimaryKey.KeyValuePairs){let E=m[I.FieldName],w=I.Value;if(typeof w=="number"&&(w=w.toString()),typeof E=="number"&&(E=E.toString()),w!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${w}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
406
408
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
407
409
|
DatasetID
|
|
408
410
|
DatasetName
|
|
@@ -420,16 +422,16 @@
|
|
|
420
422
|
LatestUpdateDate
|
|
421
423
|
EntityUpdateDates
|
|
422
424
|
}
|
|
423
|
-
}`,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 x(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(
|
|
425
|
+
}`,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 x(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(a=>a.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
424
426
|
GetRecordFavoriteStatus(params: $params) {
|
|
425
427
|
Success
|
|
426
428
|
IsFavorite
|
|
427
429
|
}
|
|
428
|
-
}`,i=await this.ExecuteGQL(
|
|
430
|
+
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=y.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
429
431
|
SetRecordFavoriteStatus(params: $params){
|
|
430
432
|
Success
|
|
431
433
|
}
|
|
432
|
-
}`,
|
|
434
|
+
}`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(a&&a.SetRecordFavoriteStatus!==null)return a.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=y.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
433
435
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
434
436
|
Success
|
|
435
437
|
Status
|
|
@@ -460,16 +462,16 @@
|
|
|
460
462
|
ErrorMessage
|
|
461
463
|
Result
|
|
462
464
|
}
|
|
463
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return
|
|
465
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return S.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){const e=S.Instance&&S.Instance._configData===this._configData;if(e&&S.Instance._refreshPromise)return S.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(S.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&S.Instance&&(S.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,S.Instance&&S.Instance._configData===this._configData&&(S.Instance._client=t)}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 S.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n),new y.GraphQLClient(e,{headers:o})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
464
466
|
`:s.startsWith("_")||(t+=s+`
|
|
465
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new
|
|
467
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new G:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=V.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:p(o=>{r.next(o.data)},"next"),error:p(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(a=>{r.activeSubscribers++;const c=r.subject.subscribe(a);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,c.unsubscribe()}});const s=y.gql`subscription StatusUpdates($sessionId: String!) {
|
|
466
468
|
statusUpdates(sessionId: $sessionId) {
|
|
467
469
|
date
|
|
468
470
|
message
|
|
469
471
|
sessionId
|
|
470
472
|
}
|
|
471
473
|
}
|
|
472
|
-
`,n=new
|
|
474
|
+
`,n=new $.Subject,o=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(a=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:p(d=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),a.next(d.data.statusUpdates.message)},"next"),error:p(async d=>{const f=d;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",l),a.error(l)}}else a.error(d)},"error"),complete:p(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:p(a=>n.next(a),"next"),error:p(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(a=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const d=n.subscribe(a);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
|
|
473
475
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
474
476
|
Success
|
|
475
477
|
ChildEntityName
|
|
@@ -481,14 +483,14 @@
|
|
|
481
483
|
ChildEntityNames
|
|
482
484
|
ErrorMessage
|
|
483
485
|
}
|
|
484
|
-
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(
|
|
486
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=Date.now();console.log(`[DIAG][${e}] setupGraphQLClient() ENTER`);const t=new S;console.log(`[DIAG][${e}] setupGraphQLClient() calling SetProvider() (Metadata.Provider will be set BEFORE Config completes)`),u.SetProvider(t),console.log(`[DIAG][${e}] setupGraphQLClient() SetProvider() done. Metadata.Provider is now set. Starting async Config()...`);const r=Date.now();await t.Config(h),console.log(`[DIAG][${e}] setupGraphQLClient() provider.Config() completed in ${Date.now()-r}ms. Provider is now fully ready.`);const s=Date.now();return console.log(`[DIAG][${e}] setupGraphQLClient() calling StartupManager.Startup()...`),await u.StartupManager.Instance.Startup(),console.log(`[DIAG][${e}] setupGraphQLClient() StartupManager.Startup() completed in ${Date.now()-s}ms`),C.MJGlobal.Instance.RaiseEvent({event:C.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),console.log(`[DIAG][${e}] setupGraphQLClient() EXIT - total time: ${Date.now()-e}ms`),t}p(j,"setupGraphQLClient");class J{static{p(this,"SyncRolesAndUsersResult")}}class W{static{p(this,"RoleInput")}}class z{static{p(this,"UserInput")}}class H{static{p(this,"RolesAndUsersInput")}}var Q=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(Q||{});class X{static{p(this,"ActionItemInput")}}class Y{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{p(this,"ActionItemOutput")}}class ee{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new y.GraphQLClient(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
485
487
|
GetData(input: $input) {
|
|
486
488
|
Success
|
|
487
489
|
ErrorMessages
|
|
488
490
|
Queries
|
|
489
491
|
Results
|
|
490
492
|
}
|
|
491
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?C.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),u.IsVerboseLoggingEnabled()){const
|
|
493
|
+
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?C.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
492
494
|
GetAllEntities {
|
|
493
495
|
Success
|
|
494
496
|
ErrorMessage
|
|
@@ -857,7 +859,7 @@
|
|
|
857
859
|
executionTimeMs
|
|
858
860
|
}
|
|
859
861
|
}
|
|
860
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let
|
|
862
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=y.gql`
|
|
861
863
|
query EmbedTextSystemUser(
|
|
862
864
|
$textToEmbed: [String!]!,
|
|
863
865
|
$modelSize: String!
|
|
@@ -872,7 +874,7 @@
|
|
|
872
874
|
error
|
|
873
875
|
}
|
|
874
876
|
}
|
|
875
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const
|
|
877
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class te{static{p(this,"GetDataOutput")}}class re{static{p(this,"SimpleRemoteEntityOutput")}}class se{static{p(this,"SimpleRemoteEntity")}}class ne{static{p(this,"SimpleRemoteEntityField")}}class oe{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=y.gql`
|
|
876
878
|
mutation RunAction($input: RunActionInput!) {
|
|
877
879
|
RunAction(input: $input) {
|
|
878
880
|
Success
|
|
@@ -889,7 +891,7 @@
|
|
|
889
891
|
ResultData
|
|
890
892
|
}
|
|
891
893
|
}
|
|
892
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class
|
|
894
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ae{static{p(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=y.gql`
|
|
893
895
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
894
896
|
CreateAPIKey(input: $input) {
|
|
895
897
|
Success
|
|
@@ -905,61 +907,65 @@
|
|
|
905
907
|
Error
|
|
906
908
|
}
|
|
907
909
|
}
|
|
908
|
-
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
$verbose: Boolean,
|
|
912
|
-
$environment: String,
|
|
913
|
-
$tags: String,
|
|
914
|
-
$variables: String
|
|
915
|
-
) {
|
|
916
|
-
RunTest(
|
|
917
|
-
testId: $testId,
|
|
918
|
-
verbose: $verbose,
|
|
919
|
-
environment: $environment,
|
|
920
|
-
tags: $tags,
|
|
921
|
-
variables: $variables
|
|
922
|
-
) {
|
|
923
|
-
success
|
|
924
|
-
errorMessage
|
|
925
|
-
executionTimeMs
|
|
926
|
-
result
|
|
927
|
-
}
|
|
910
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ie{static{p(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:p(s=>s?.success===!0,"validateAck"),isCompletionEvent:p(s=>this.isTestCompletionEvent(s,e.testId),"isCompletionEvent"),extractResult:p(s=>this.extractTestResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:p(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:p(s=>s?.success===!0,"validateAck"),isCompletionEvent:p(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:p(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:p(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=y.gql`
|
|
911
|
+
query IsTestRunning($testId: String!) {
|
|
912
|
+
IsTestRunning(testId: $testId)
|
|
928
913
|
}
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
914
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return y.gql`
|
|
915
|
+
mutation RunTest(
|
|
916
|
+
$testId: String!,
|
|
917
|
+
$verbose: Boolean,
|
|
918
|
+
$environment: String,
|
|
919
|
+
$tags: String,
|
|
920
|
+
$variables: String,
|
|
921
|
+
$fireAndForget: Boolean
|
|
922
|
+
) {
|
|
923
|
+
RunTest(
|
|
924
|
+
testId: $testId,
|
|
925
|
+
verbose: $verbose,
|
|
926
|
+
environment: $environment,
|
|
927
|
+
tags: $tags,
|
|
928
|
+
variables: $variables,
|
|
929
|
+
fireAndForget: $fireAndForget
|
|
940
930
|
) {
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
parallel: $parallel,
|
|
946
|
-
tags: $tags,
|
|
947
|
-
variables: $variables,
|
|
948
|
-
selectedTestIds: $selectedTestIds,
|
|
949
|
-
sequenceStart: $sequenceStart,
|
|
950
|
-
sequenceEnd: $sequenceEnd
|
|
951
|
-
) {
|
|
952
|
-
success
|
|
953
|
-
errorMessage
|
|
954
|
-
executionTimeMs
|
|
955
|
-
result
|
|
956
|
-
}
|
|
931
|
+
success
|
|
932
|
+
errorMessage
|
|
933
|
+
executionTimeMs
|
|
934
|
+
result
|
|
957
935
|
}
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
936
|
+
}
|
|
937
|
+
`}buildRunTestSuiteMutation(){return y.gql`
|
|
938
|
+
mutation RunTestSuite(
|
|
939
|
+
$suiteId: String!,
|
|
940
|
+
$verbose: Boolean,
|
|
941
|
+
$environment: String,
|
|
942
|
+
$parallel: Boolean,
|
|
943
|
+
$tags: String,
|
|
944
|
+
$variables: String,
|
|
945
|
+
$selectedTestIds: String,
|
|
946
|
+
$sequenceStart: Int,
|
|
947
|
+
$sequenceEnd: Int,
|
|
948
|
+
$fireAndForget: Boolean
|
|
949
|
+
) {
|
|
950
|
+
RunTestSuite(
|
|
951
|
+
suiteId: $suiteId,
|
|
952
|
+
verbose: $verbose,
|
|
953
|
+
environment: $environment,
|
|
954
|
+
parallel: $parallel,
|
|
955
|
+
tags: $tags,
|
|
956
|
+
variables: $variables,
|
|
957
|
+
selectedTestIds: $selectedTestIds,
|
|
958
|
+
sequenceStart: $sequenceStart,
|
|
959
|
+
sequenceEnd: $sequenceEnd,
|
|
960
|
+
fireAndForget: $fireAndForget
|
|
961
|
+
) {
|
|
962
|
+
success
|
|
963
|
+
errorMessage
|
|
964
|
+
executionTimeMs
|
|
965
|
+
result
|
|
961
966
|
}
|
|
962
|
-
|
|
967
|
+
}
|
|
968
|
+
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class ue{static{p(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
|
|
963
969
|
query GetRegistryComponent(
|
|
964
970
|
$registryName: String!,
|
|
965
971
|
$namespace: String!,
|
|
@@ -980,7 +986,7 @@
|
|
|
980
986
|
specification
|
|
981
987
|
}
|
|
982
988
|
}
|
|
983
|
-
`,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&&
|
|
989
|
+
`,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=Date.now();console.log(`[DIAG][${s}] GetRegistryComponent() calling ExecuteGQL for ${e.registryName}/${e.name}`,{variables:r,dataProviderType:this._dataProvider?.constructor?.name});const n=Date.now(),o=await this._dataProvider.ExecuteGQL(t,r);if(console.log(`[DIAG][${s}] GetRegistryComponent() ExecuteGQL returned in ${Date.now()-n}ms`,{resultExists:!!o,hasGetRegistryComponent:o?!!o.GetRegistryComponent:!1,resultKeys:o?Object.keys(o):[],rawResult:o?JSON.stringify(o).substring(0,500):"null"}),o&&o.GetRegistryComponent){const i=o.GetRegistryComponent;if(console.log(`[DIAG][${s}] GetRegistryComponent() response details:`,{notModified:i.notModified,hasSpecification:!!i.specification,specType:i.specification?typeof i.specification:"N/A",specLength:i.specification?typeof i.specification=="string"?i.specification.length:JSON.stringify(i.specification).length:0,hash:i.hash,message:i.message}),i.notModified&&!i.specification)return console.log(`[DIAG][${s}] GetRegistryComponent() returning null - notModified with no spec`),null;if(i.specification){if(typeof i.specification=="object")return console.log(`[DIAG][${s}] GetRegistryComponent() returning spec as object`),i.specification;try{const a=JSON.parse(i.specification);return console.log(`[DIAG][${s}] GetRegistryComponent() returning parsed spec`,{name:a.name,hasCode:!!a.code,codeLength:a.code?.length}),a}catch(a){return console.error(`[DIAG][${s}] GetRegistryComponent() JSON PARSE FAILED:`,a),u.LogError(`Failed to parse component specification: ${a}`),null}}return console.warn(`[DIAG][${s}] GetRegistryComponent() response has GetRegistryComponent but no specification - returning null`),null}return console.warn(`[DIAG][${s}] GetRegistryComponent() result missing GetRegistryComponent field - returning null`,{resultExists:!!o,resultKeys:o?Object.keys(o):[]}),null}catch(t){throw console.error("[DIAG] GetRegistryComponent() CAUGHT ERROR:",t),u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=y.gql`
|
|
984
990
|
query GetRegistryComponent(
|
|
985
991
|
$registryName: String!,
|
|
986
992
|
$namespace: String!,
|
|
@@ -1001,7 +1007,7 @@
|
|
|
1001
1007
|
specification
|
|
1002
1008
|
}
|
|
1003
1009
|
}
|
|
1004
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let
|
|
1010
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=y.gql`
|
|
1005
1011
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
1006
1012
|
SearchRegistryComponents(params: $params) {
|
|
1007
1013
|
components
|
|
@@ -1043,7 +1049,7 @@
|
|
|
1043
1049
|
error
|
|
1044
1050
|
}
|
|
1045
1051
|
}
|
|
1046
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class
|
|
1052
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ce{static{p(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=y.gql`
|
|
1047
1053
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1048
1054
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1049
1055
|
Success
|
|
@@ -1059,7 +1065,7 @@
|
|
|
1059
1065
|
}
|
|
1060
1066
|
}
|
|
1061
1067
|
}
|
|
1062
|
-
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class
|
|
1068
|
+
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class le{static{p(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=y.gql`
|
|
1063
1069
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1064
1070
|
ListStorageObjects(input: $input) {
|
|
1065
1071
|
objects {
|
|
@@ -1076,18 +1082,18 @@
|
|
|
1076
1082
|
prefixes
|
|
1077
1083
|
}
|
|
1078
1084
|
}
|
|
1079
|
-
`,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},
|
|
1085
|
+
`,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(s){const n=s;throw u.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return u.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=y.gql`
|
|
1080
1086
|
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1081
1087
|
CreateDirectory(input: $input)
|
|
1082
1088
|
}
|
|
1083
|
-
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return u.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(
|
|
1089
|
+
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return u.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(o=>o.name===s||o.fullPath===t)}catch(r){const s=r;return u.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=y.gql`
|
|
1084
1090
|
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1085
1091
|
CreatePreAuthUploadUrl(input: $input) {
|
|
1086
1092
|
UploadUrl
|
|
1087
1093
|
ProviderKey
|
|
1088
1094
|
}
|
|
1089
1095
|
}
|
|
1090
|
-
`,n={input:{AccountID:e,ObjectName:t,ContentType:r}},
|
|
1096
|
+
`,n={input:{AccountID:e,ObjectName:t,ContentType:r}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw u.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=y.gql`
|
|
1091
1097
|
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1092
1098
|
CreatePreAuthDownloadUrl(input: $input)
|
|
1093
1099
|
}
|
|
@@ -1115,7 +1121,7 @@
|
|
|
1115
1121
|
destinationPath
|
|
1116
1122
|
}
|
|
1117
1123
|
}
|
|
1118
|
-
`,
|
|
1124
|
+
`,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,o);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const o=n;return u.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=y.gql`
|
|
1119
1125
|
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1120
1126
|
SearchAcrossAccounts(input: $input) {
|
|
1121
1127
|
accountResults {
|
|
@@ -1143,5 +1149,5 @@
|
|
|
1143
1149
|
failedAccounts
|
|
1144
1150
|
}
|
|
1145
1151
|
}
|
|
1146
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},
|
|
1152
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:p(function(){return y.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=G,exports.BrowserStorageProviderBase=T,exports.FieldMapper=A,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=S,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLProviderConfigData=B,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=Q,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
|
|
1147
1153
|
//# sourceMappingURL=index.cjs.map
|