@memberjunction/graphql-dataprovider 2.103.0 → 2.104.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +49 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +112 -65
- package/dist/index.d.mts +112 -65
- package/dist/index.mjs +73 -63
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -3
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var pe=Object.defineProperty;var f=(
|
|
1
|
+
"use strict";var pe=Object.defineProperty;var f=(I,e)=>pe(I,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),de=require("@memberjunction/core-entities"),fe=require("@tempfix/idb"),ye=require("rxjs"),me=require("graphql-ws"),Se=require("uuid"),E=require("@memberjunction/global");const K=class K{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(K,"FieldMapper");let P=K;const J=class J extends u.TransactionGroupBase{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 a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let
|
|
9
|
+
`,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let o=0;o<this.PendingTransactions.length;o++){const i=a.ResultsJSON[o],m=E.SafeJSONParse(i),p=this.PendingTransactions[o];n.push(new u.TransactionResult(p,m,m!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(J,"GraphQLTransactionGroup");let $=J;const j=class j{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,7 +65,7 @@
|
|
|
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,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e){try{const
|
|
68
|
+
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{console.log("[GraphQLAIClient] Received statusUpdate message:",n);const o=JSON.parse(n);if(console.log("[GraphQLAIClient] Parsed message:",o),o.resolver==="RunAIAgentResolver"&&o.type==="ExecutionProgress"&&o.status==="ok"&&o.data?.progress){console.log("[GraphQLAIClient] Forwarding progress to callback:",o.data.progress);const i={...o.data.progress,metadata:{...o.data.progress.metadata||{},agentRunId:o.data.agentRunId}};e.onProgress(i)}else console.log("[GraphQLAIClient] Message does not match filter criteria:",{resolver:o.resolver,type:o.type,status:o.status,hasProgress:!!o.data?.progress})}catch(o){console.error("[GraphQLAIClient] Failed to parse progress message:",o,"Raw message:",n)}}));const r=y.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -74,7 +74,8 @@
|
|
|
74
74
|
$templateData: String,
|
|
75
75
|
$lastRunId: String,
|
|
76
76
|
$autoPopulateLastRunPayload: Boolean,
|
|
77
|
-
$configurationId: String
|
|
77
|
+
$configurationId: String,
|
|
78
|
+
$conversationDetailId: String
|
|
78
79
|
) {
|
|
79
80
|
RunAIAgent(
|
|
80
81
|
agentId: $agentId,
|
|
@@ -84,15 +85,16 @@
|
|
|
84
85
|
templateData: $templateData,
|
|
85
86
|
lastRunId: $lastRunId,
|
|
86
87
|
autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
|
|
87
|
-
configurationId: $configurationId
|
|
88
|
+
configurationId: $configurationId,
|
|
89
|
+
conversationDetailId: $conversationDetailId
|
|
88
90
|
) {
|
|
89
91
|
success
|
|
90
92
|
errorMessage
|
|
91
93
|
executionTimeMs
|
|
92
|
-
|
|
94
|
+
result
|
|
93
95
|
}
|
|
94
96
|
}
|
|
95
|
-
`,
|
|
97
|
+
`,s=this.prepareAgentVariables(e),a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgent?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(t.conversationDetailId=e.conversationDetailId),t}processAgentResult(e){return E.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=y.gql`
|
|
96
98
|
mutation ExecuteSimplePrompt(
|
|
97
99
|
$systemPrompt: String!,
|
|
98
100
|
$messages: String,
|
|
@@ -130,7 +132,7 @@
|
|
|
130
132
|
error
|
|
131
133
|
}
|
|
132
134
|
}
|
|
133
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(j,"GraphQLAIClient");let N=j;const z=class z extends u.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,i
|
|
135
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(j,"GraphQLAIClient");let N=j;const z=class z extends u.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,o,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},a,n,o)}};f(z,"GraphQLProviderConfigData");let C=z;const h=class h extends u.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
|
|
134
136
|
${this.userInfoString()}
|
|
135
137
|
UserRoles_UserIDArray {
|
|
136
138
|
${this.userRoleInfoString()}
|
|
@@ -147,19 +149,19 @@
|
|
|
147
149
|
ExecutionTime
|
|
148
150
|
ErrorMessage
|
|
149
151
|
}
|
|
150
|
-
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,n,
|
|
152
|
+
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,n,o){const i=y.gql`
|
|
151
153
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
152
154
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
153
155
|
${this.QueryReturnFieldList}
|
|
154
156
|
}
|
|
155
157
|
}
|
|
156
|
-
`,m={QueryID:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),
|
|
158
|
+
`,m={QueryID:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),o!==void 0&&(m.StartRow=o);const p=await this.ExecuteGQL(i,m);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,n,o){const i=y.gql`
|
|
157
159
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
158
160
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
159
161
|
${this.QueryReturnFieldList}
|
|
160
162
|
}
|
|
161
163
|
}
|
|
162
|
-
`,m={QueryName:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),
|
|
164
|
+
`,m={QueryName:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),o!==void 0&&(m.StartRow=o);const p=await this.ExecuteGQL(i,m);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
163
165
|
Success
|
|
164
166
|
QueryID
|
|
165
167
|
QueryName
|
|
@@ -168,7 +170,7 @@
|
|
|
168
170
|
TotalRowCount
|
|
169
171
|
ExecutionTime
|
|
170
172
|
ErrorMessage
|
|
171
|
-
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 RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let n,
|
|
173
|
+
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 RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let n,o;if(e.ViewEntity)o=e.ViewEntity,n=o.Entity;else{const{entityName:l,v:c}=await this.getEntityNameAndUserView(e,t);o=c,n=l}const i=this.Entities.find(l=>l.Name===n);if(!i)throw new Error(`Entity ${n} not found in metadata`);let m=!1;e.ViewID?(r=`Run${i.ClassName}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${i.ClassName}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(m=!0,r=`Run${i.ClassName}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),m||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const p=this.getViewRunTimeFieldList(i,o,e,m),g=y.gql`
|
|
172
174
|
query RunViewQuery ($input: ${s}!) {
|
|
173
175
|
${r}(input: $input) {
|
|
174
176
|
Results {
|
|
@@ -182,7 +184,7 @@
|
|
|
182
184
|
Success
|
|
183
185
|
ErrorMessage
|
|
184
186
|
}
|
|
185
|
-
}`,d=await this.ExecuteGQL(g,{input:a});if(d&&d[r]){const l=d[r].Results;if(l&&l.length>0){const R=
|
|
187
|
+
}`,d=await this.ExecuteGQL(g,{input:a});if(d&&d[r]){const l=d[r].Results;if(l&&l.length>0){const R=i.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);l.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(D=>{S[D.Name]=S[D.CodeName]})})}const c=d[r];return await this.PostProcessRunView(c,e,t),c}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const i of e){let m="",p="";const g={};let d=null,l=null;if(i.ViewEntity)l=i.ViewEntity,d=l.Get("Entity");else{const{entityName:S,v:D}=await this.getEntityNameAndUserView(i,t);l=D,d=S}const c=this.Entities.find(S=>S.Name===d);if(!c)throw new Error(`Entity ${d} not found in metadata`);s.push(c);let R=!1;i.ViewID?(m=`Run${c.ClassName}ViewByID`,p="RunViewByIDInput",g.ViewID=i.ViewID):i.ViewName?(m=`Run${c.ClassName}ViewByName`,p="RunViewByNameInput",g.ViewName=i.ViewName):(R=!0,m=`Run${c.ClassName}DynamicView`,p="RunDynamicViewInput",g.EntityName=i.EntityName),g.ExtraFilter=i.ExtraFilter||"",g.OrderBy=i.OrderBy||"",g.UserSearchString=i.UserSearchString||"",g.Fields=i.Fields,g.IgnoreMaxRows=i.IgnoreMaxRows||!1,i.MaxRows!==void 0&&(g.MaxRows=i.MaxRows),i.StartRow!==void 0&&(g.StartRow=i.StartRow),g.ForceAuditLog=i.ForceAuditLog||!1,g.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(g.AuditLogDescription=i.AuditLogDescription),R||(g.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=i.OverrideExcludeFilter||"",g.SaveViewResults=i.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(c,l,i,R))}const n=y.gql`
|
|
186
188
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
187
189
|
RunViews(input: $input) {
|
|
188
190
|
Results {
|
|
@@ -200,7 +202,7 @@
|
|
|
200
202
|
Success
|
|
201
203
|
ErrorMessage
|
|
202
204
|
}
|
|
203
|
-
}`,
|
|
205
|
+
}`,o=await this.ExecuteGQL(n,{input:r});if(o&&o.RunViews){const i=o.RunViews;for(const[m,p]of i.entries())p.Results=p.Results.map(g=>{let d=JSON.parse(g.Data);return this.ConvertBackToMJFields(d),d});return await this.PostProcessRunViews(i,e,t),i}return null}catch(r){throw u.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await de.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await de.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 a=[],n=new P;if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);r.Fields.forEach(o=>{a.push(n.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||a.push(n.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)a.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!a.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&a.push(n.MapFieldName(o.EntityField.CodeName))})}return a}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
204
206
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
205
207
|
EntityName
|
|
206
208
|
RelatedEntityName
|
|
@@ -251,32 +253,32 @@
|
|
|
251
253
|
Message
|
|
252
254
|
}
|
|
253
255
|
}
|
|
254
|
-
}`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(
|
|
256
|
+
}`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(i=>({FieldName:i.FieldName,Value:i.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(i=>i.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.MergeRecords}catch(a){return u.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const o=`${n}${e.EntityInfo.ClassName}`,i=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),m=new P,p=` ${o}(input: $input) {
|
|
255
257
|
${e.Fields.map(d=>m.MapFieldName(d.CodeName)).join(`
|
|
256
258
|
`)}
|
|
257
|
-
}`,g=y.gql`mutation ${n}${e.EntityInfo.ClassName} ($input: ${
|
|
259
|
+
}`,g=y.gql`mutation ${n}${e.EntityInfo.ClassName} ($input: ${o}Input!) {
|
|
258
260
|
${p}
|
|
259
261
|
}
|
|
260
|
-
`;for(let d=0;d<
|
|
262
|
+
`;for(let d=0;d<i.length;d++){const l=i[d];let c=l.Value;if(c)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:c=c.getTime();break;case u.EntityFieldTSType.Boolean:typeof c!="boolean"&&(c=parseInt(c)!==0);break;case u.EntityFieldTSType.Number:if(typeof c!="number"){const R=Number(c);isNaN(R)||(c=R)}break}c===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?c=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?c=0:c=""),a.input[l.CodeName]=c}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(l=>{let c=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?c=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?c=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?c=l.OldValue.toString():c=l.OldValue),d.push({Key:l.CodeName,Value:c})}),a.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",p,a,{mutationName:o,mutationInputTypes:d},(l,c)=>{s.EndedAt=new Date,c&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(g,a);if(d&&d[n+e.EntityInfo.ClassName])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[n+e.EntityInfo.ClassName]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let n="",o="";for(let d=0;d<t.KeyValuePairs.length;d++){const l=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,c=t.GetValueByIndex(d),R=l.GraphQLType;if(o.length>0&&(o+=", "),o+=`$${l.CodeName}: ${R}!`,n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${c} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(c)}else a[l.CodeName]=c}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=new P,p=y.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${o}) {
|
|
261
263
|
${e.EntityInfo.ClassName}(${n}) {
|
|
262
264
|
${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
|
|
263
265
|
`)}
|
|
264
|
-
${
|
|
266
|
+
${i}
|
|
265
267
|
}
|
|
266
268
|
}
|
|
267
|
-
`,g=await this.ExecuteGQL(p,a);return g&&g[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(g[e.EntityInfo.ClassName]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new
|
|
268
|
-
${
|
|
269
|
-
${n.Fields.map(
|
|
269
|
+
`,g=await this.ExecuteGQL(p,a);return g&&g[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(g[e.EntityInfo.ClassName]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new P().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 a=e.RelatedEntities[s],n=this.Entities.find(i=>i.ID===a.RelatedEntityID);let o="";a.Type.toLowerCase().trim()==="many to many"?o=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:o=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
270
|
+
${o} {
|
|
271
|
+
${n.Fields.map(i=>i.CodeName).join(`
|
|
270
272
|
`)}
|
|
271
273
|
}
|
|
272
|
-
`}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(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const a={},n=[];let
|
|
273
|
-
`),m+=`${c.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+e.EntityInfo.ClassName,g=y.gql`${p}(${
|
|
274
|
+
`}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(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const a={},n=[];let o="",i="",m="";for(let l of e.PrimaryKey.KeyValuePairs){const c=e.Fields.find(R=>R.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[c.CodeName]=c.Value,n.push({varName:c.CodeName,inputType:c.EntityFieldInfo.GraphQLType+"!"}),o.length>0&&(o+=", "),o+=`${c.CodeName}: $${c.CodeName}`,i.length>0&&(i+=", "),i+=`$${c.CodeName}: ${c.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
|
|
275
|
+
`),m+=`${c.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+e.EntityInfo.ClassName,g=y.gql`${p}(${o}, options___: $options___) {
|
|
274
276
|
${m}
|
|
275
277
|
}
|
|
276
|
-
`,d=y.gql`mutation ${p} (${
|
|
278
|
+
`,d=y.gql`mutation ${p} (${i}, $options___: DeleteOptionsInput!) {
|
|
277
279
|
${g}
|
|
278
280
|
}
|
|
279
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",g,a,{mutationName:p,mutationInputTypes:n},(l,c)=>{if(s.EndedAt=new Date,c&&l){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==l[S.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const l=await this.ExecuteGQL(d,a);if(l&&l[p]){const c=l[p];for(let R of e.PrimaryKey.KeyValuePairs){let S=c[R.FieldName],
|
|
281
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",g,a,{mutationName:p,mutationInputTypes:n},(l,c)=>{if(s.EndedAt=new Date,c&&l){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==l[S.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const l=await this.ExecuteGQL(d,a);if(l&&l[p]){const c=l[p];for(let R of e.PrimaryKey.KeyValuePairs){let S=c[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof S=="number"&&(S=S.toString()),D!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
280
282
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
281
283
|
DatasetID
|
|
282
284
|
DatasetName
|
|
@@ -294,16 +296,16 @@
|
|
|
294
296
|
LatestUpdateDate
|
|
295
297
|
EntityUpdateDates
|
|
296
298
|
}
|
|
297
|
-
}`,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 $(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(
|
|
299
|
+
}`,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 $(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(i=>i.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
298
300
|
GetRecordFavoriteStatus(params: $params) {
|
|
299
301
|
Success
|
|
300
302
|
IsFavorite
|
|
301
303
|
}
|
|
302
|
-
}`,
|
|
304
|
+
}`,o=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(o&&o.GetRecordFavoriteStatus&&o.GetRecordFavoriteStatus.Success)return o.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const n=this.Entities.find(m=>m.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=y.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
303
305
|
SetRecordFavoriteStatus(params: $params){
|
|
304
306
|
Success
|
|
305
307
|
}
|
|
306
|
-
}`,
|
|
308
|
+
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=y.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
307
309
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
308
310
|
Success
|
|
309
311
|
Status
|
|
@@ -336,21 +338,21 @@
|
|
|
336
338
|
}
|
|
337
339
|
}`,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 h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new y.GraphQLClient(e,{headers:a})}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__")+`
|
|
338
340
|
`:s.startsWith("_")||(t+=s+`
|
|
339
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new
|
|
341
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new L),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ye.Observable(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=y.gql`subscription StatusUpdates($sessionId: String!) {
|
|
340
342
|
statusUpdates(sessionId: $sessionId) {
|
|
341
343
|
date
|
|
342
344
|
message
|
|
343
345
|
sessionId
|
|
344
346
|
}
|
|
345
347
|
}
|
|
346
|
-
`,s=new ye.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}};f(h,"GraphQLDataProvider");let v=h;const W=class W{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(W,"BrowserStorageProviderBase");let V=W;const Re="MJ_Metadata",
|
|
348
|
+
`,s=new ye.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates.message),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}};f(h,"GraphQLDataProvider");let v=h;const W=class W{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(W,"BrowserStorageProviderBase");let V=W;const Re="MJ_Metadata",w="Metadata_KVPairs",H=class H extends V{constructor(){super(),this.dbPromise=fe.openDB(Re,1,{upgrade(e){e.objectStoreNames.contains(w)||e.createObjectStore(w)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(w,"readwrite");await s.objectStore(w).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(w).objectStore(w).get(e)}async remove(e){const r=(await this.dbPromise).transaction(w,"readwrite");await r.objectStore(w).delete(e),await r.done}};f(H,"BrowserIndexedDBStorageProvider");let L=H;async function he(I){const e=new v;return u.SetProvider(e),await e.Config(I),E.MJGlobal.Instance.RaiseEvent({event:E.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(he,"setupGraphQLClient");const X=class X{};f(X,"SyncRolesAndUsersResult");let F=X;const Z=class Z{};f(Z,"RoleInput");let x=Z;const Y=class Y{};f(Y,"UserInput");let T=Y;const ee=class ee{};f(ee,"RolesAndUsersInput");let U=ee;var ge=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(ge||{});const te=class te{};f(te,"ActionItemInput");let G=te;const re=class re{constructor(){this.Results=[]}};f(re,"SyncDataResult");let Q=re;const se=class se{};f(se,"ActionItemOutput");let b=se;const ae=class ae{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new y.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
347
349
|
GetData(input: $input) {
|
|
348
350
|
Success
|
|
349
351
|
ErrorMessages
|
|
350
352
|
Queries
|
|
351
353
|
Results
|
|
352
354
|
}
|
|
353
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?
|
|
355
|
+
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?E.SafeJSONParse(a):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){const s=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;return u.LogError(s),{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
354
356
|
GetAllEntities {
|
|
355
357
|
Success
|
|
356
358
|
ErrorMessage
|
|
@@ -481,7 +483,7 @@
|
|
|
481
483
|
ErrorMessage
|
|
482
484
|
AppliedParameters
|
|
483
485
|
}
|
|
484
|
-
}`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?
|
|
486
|
+
}`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?E.SafeJSONParse(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
485
487
|
GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
486
488
|
QueryID
|
|
487
489
|
QueryName
|
|
@@ -493,7 +495,7 @@
|
|
|
493
495
|
ErrorMessage
|
|
494
496
|
AppliedParameters
|
|
495
497
|
}
|
|
496
|
-
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?
|
|
498
|
+
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?E.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
|
|
497
499
|
CreateQuerySystemUser(input: $input) {
|
|
498
500
|
Success
|
|
499
501
|
ErrorMessage
|
|
@@ -661,10 +663,10 @@
|
|
|
661
663
|
success
|
|
662
664
|
errorMessage
|
|
663
665
|
executionTimeMs
|
|
664
|
-
|
|
666
|
+
result
|
|
665
667
|
}
|
|
666
668
|
}
|
|
667
|
-
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser):{success:!1,
|
|
669
|
+
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return E.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=y.gql`
|
|
668
670
|
query ExecuteSimplePromptSystemUser(
|
|
669
671
|
$systemPrompt: String!,
|
|
670
672
|
$messages: String,
|
|
@@ -702,7 +704,7 @@
|
|
|
702
704
|
error
|
|
703
705
|
}
|
|
704
706
|
}
|
|
705
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ae,"GraphQLSystemUserClient");let
|
|
707
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ae,"GraphQLSystemUserClient");let M=ae;const ne=class ne{};f(ne,"GetDataOutput");let q=ne;const oe=class oe{};f(oe,"SimpleRemoteEntityOutput");let A=oe;const ie=class ie{};f(ie,"SimpleRemoteEntity");let O=ie;const ue=class ue{};f(ue,"SimpleRemoteEntityField");let _=ue;const le=class le{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=y.gql`
|
|
706
708
|
mutation RunAction($input: RunActionInput!) {
|
|
707
709
|
RunAction(input: $input) {
|
|
708
710
|
Success
|
|
@@ -719,7 +721,7 @@
|
|
|
719
721
|
ResultData
|
|
720
722
|
}
|
|
721
723
|
}
|
|
722
|
-
`;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}}};f(le,"GraphQLActionClient");let
|
|
724
|
+
`;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}}};f(le,"GraphQLActionClient");let k=le;const ce=class ce{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
|
|
723
725
|
query GetRegistryComponent(
|
|
724
726
|
$registryName: String!,
|
|
725
727
|
$namespace: String!,
|
|
@@ -761,7 +763,7 @@
|
|
|
761
763
|
specification
|
|
762
764
|
}
|
|
763
765
|
}
|
|
764
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let n;if(a.specification)try{n=JSON.parse(a.specification)}catch(
|
|
766
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let n;if(a.specification)try{n=JSON.parse(a.specification)}catch(o){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${o}`),n=void 0}return{specification:n,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw 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`
|
|
765
767
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
766
768
|
SearchRegistryComponents(params: $params) {
|
|
767
769
|
components
|
|
@@ -795,5 +797,13 @@
|
|
|
795
797
|
}
|
|
796
798
|
}
|
|
797
799
|
}
|
|
798
|
-
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u.LogError(s),null}}
|
|
800
|
+
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u.LogError(s),null}}async SendComponentFeedback(e){try{const t=y.gql`
|
|
801
|
+
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
802
|
+
SendComponentFeedback(feedback: $feedback) {
|
|
803
|
+
success
|
|
804
|
+
feedbackID
|
|
805
|
+
error
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
`,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"}}}};f(ce,"GraphQLComponentRegistryClient");let B=ce;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return y.gql}}),exports.ActionItemInput=G,exports.ActionItemOutput=b,exports.FieldMapper=P,exports.GetDataOutput=q,exports.GraphQLAIClient=N,exports.GraphQLActionClient=k,exports.GraphQLComponentRegistryClient=B,exports.GraphQLDataProvider=v,exports.GraphQLProviderConfigData=C,exports.GraphQLSystemUserClient=M,exports.GraphQLTransactionGroup=$,exports.RoleInput=x,exports.RolesAndUsersInput=U,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=_,exports.SimpleRemoteEntityOutput=A,exports.SyncDataAction=ge,exports.SyncDataResult=Q,exports.SyncRolesAndUsersResult=F,exports.UserInput=T,exports.setupGraphQLClient=he;
|
|
799
809
|
//# sourceMappingURL=index.cjs.map
|