@memberjunction/graphql-dataprovider 2.122.0 → 2.122.2
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 +51 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -474
- package/dist/index.d.mts +1 -474
- package/dist/index.mjs +58 -58
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -7
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var fe=Object.defineProperty;var S=(E,e)=>fe(E,"name",{value:e,configurable:!0});var
|
|
1
|
+
"use strict";var fe=Object.defineProperty;var S=(E,e)=>fe(E,"name",{value:e,configurable:!0});var I,g=require("graphql-request"),u=require("@memberjunction/core"),ge=require("@memberjunction/core-entities"),Re=require("@tempfix/idb"),$=require("rxjs"),Ie=require("graphql-ws"),Ee=require("uuid"),w=require("@memberjunction/global");const j=class j{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};S(j,"FieldMapper");let v=j;const W=class W extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=g.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,a=[];for(let o=0;o<this.PendingTransactions.length;o++){const i=n.ResultsJSON[o],c=w.SafeJSONParse(i),p=this.PendingTransactions[o];a.push(new u.TransactionResult(p,c,c!==null))}return a}else throw new Error("Failed to execute transaction group")}};S(W,"GraphQLTransactionGroup");let N=W;const z=class z{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let o=0;o<this.PendingTransactions.length;o++){const i=n.ResultsJSON[o],c=w.SafeJSONParse(i),p=this.PendingTransactions[o];a.push(new u.TransactionResult(p,c,c!==null))}return a}else throw new Error("Failed to execute transaction group")}};S(W,"GraphQLTransactionGroup");let N=W;const z=class z{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=g.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,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){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(i=>{try{u.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[i]});const c=JSON.parse(i);if(u.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[c]}),c.resolver==="RunAIAgentResolver"&&c.type==="ExecutionProgress"&&c.status==="ok"&&c.data?.progress){u.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[c.data.progress]});const p={...c.data.progress,metadata:{...c.data.progress.metadata||{},agentRunId:c.data.agentRunId}};e.onProgress(p)}else u.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:c.resolver,type:c.type,status:c.status,hasProgress:!!c.data?.progress}]})}catch(c){console.error("[GraphQLAIClient] Failed to parse progress message:",c,"Raw message:",i)}}));const n=
|
|
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){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(i=>{try{u.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[i]});const c=JSON.parse(i);if(u.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[c]}),c.resolver==="RunAIAgentResolver"&&c.type==="ExecutionProgress"&&c.status==="ok"&&c.data?.progress){u.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[c.data.progress]});const p={...c.data.progress,metadata:{...c.data.progress.metadata||{},agentRunId:c.data.agentRunId}};e.onProgress(p)}else u.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:c.resolver,type:c.type,status:c.status,hasProgress:!!c.data?.progress}]})}catch(c){console.error("[GraphQLAIClient] Failed to parse progress message:",c,"Raw message:",i)}}));const n=g.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
result
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,a=this.prepareAgentVariables(e,t,r),o=await this._dataProvider.ExecuteGQL(n,a);return this.processAgentResult(o.RunAIAgent?.result)}catch(n){return this.handleAgentError(n)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return w.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=
|
|
107
|
+
`,a=this.prepareAgentVariables(e,t,r),o=await this._dataProvider.ExecuteGQL(n,a);return this.processAgentResult(o.RunAIAgent?.result)}catch(n){return this.handleAgentError(n)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return w.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=g.gql`
|
|
108
108
|
mutation ExecuteSimplePrompt(
|
|
109
109
|
$systemPrompt: String!,
|
|
110
110
|
$messages: String,
|
|
@@ -127,7 +127,7 @@
|
|
|
127
127
|
executionTimeMs
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=
|
|
130
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=g.gql`
|
|
131
131
|
mutation EmbedText(
|
|
132
132
|
$textToEmbed: [String!]!,
|
|
133
133
|
$modelSize: String!
|
|
@@ -142,15 +142,15 @@
|
|
|
142
142
|
error
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};S(z,"GraphQLAIClient");let C=z;const
|
|
145
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};S(z,"GraphQLAIClient");let C=z;const X=class X 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,n,a,o,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},n,a,o)}};S(X,"GraphQLProviderConfigData");let b=X;const pe=(I=class extends u.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
|
|
146
146
|
${this.userInfoString()}
|
|
147
147
|
UserRoles_UserIDArray {
|
|
148
148
|
${this.userRoleInfoString()}
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
`,this._currentUserQuery=
|
|
151
|
+
`,this._currentUserQuery=g.gql`query CurrentUserAndRoles {
|
|
152
152
|
${this._innerCurrentUserQueryString}
|
|
153
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,
|
|
153
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,I._instance||(I._instance=this)}static get Instance(){return I._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===I.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new C(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Ee.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 r?(this._configData=e,this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId)),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.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=g.gql`
|
|
154
154
|
query GetReportDataQuery ($ReportID: String!) {
|
|
155
155
|
GetReportData(ReportID: $ReportID) {
|
|
156
156
|
Success
|
|
@@ -159,13 +159,13 @@
|
|
|
159
159
|
ExecutionTime
|
|
160
160
|
ErrorMessage
|
|
161
161
|
}
|
|
162
|
-
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,n,a,o){const i=
|
|
162
|
+
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,n,a,o){const i=g.gql`
|
|
163
163
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
164
164
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
165
165
|
${this.QueryReturnFieldList}
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
|
-
`,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),a!==void 0&&(c.MaxRows=a),o!==void 0&&(c.StartRow=o);const p=await this.ExecuteGQL(i,c);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,o){const i=
|
|
168
|
+
`,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),a!==void 0&&(c.MaxRows=a),o!==void 0&&(c.StartRow=o);const p=await this.ExecuteGQL(i,c);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,o){const i=g.gql`
|
|
169
169
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
170
170
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
171
171
|
${this.QueryReturnFieldList}
|
|
@@ -180,11 +180,11 @@
|
|
|
180
180
|
TotalRowCount
|
|
181
181
|
ExecutionTime
|
|
182
182
|
ErrorMessage
|
|
183
|
-
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 n={};let a,o;if(e.ViewEntity)o=e.ViewEntity,a=o.Entity;else{const{entityName:l,v:d}=await this.getEntityNameAndUserView(e,t);o=d,a=l}const i=this.Entities.find(l=>l.Name===a);if(!i)throw new Error(`Entity ${a} not found in metadata`);let c=!1;const p=this.getGraphQLTypeNameBase(i);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${p}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);const
|
|
183
|
+
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 n={};let a,o;if(e.ViewEntity)o=e.ViewEntity,a=o.Entity;else{const{entityName:l,v:d}=await this.getEntityNameAndUserView(e,t);o=d,a=l}const i=this.Entities.find(l=>l.Name===a);if(!i)throw new Error(`Entity ${a} not found in metadata`);let c=!1;const p=this.getGraphQLTypeNameBase(i);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${p}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);const m=this.getViewRunTimeFieldList(i,o,e,c),f=g.gql`
|
|
184
184
|
query RunViewQuery ($input: ${s}!) {
|
|
185
185
|
${r}(input: $input) {
|
|
186
186
|
Results {
|
|
187
|
-
${
|
|
187
|
+
${m.join(`
|
|
188
188
|
`)}
|
|
189
189
|
}
|
|
190
190
|
UserViewRunID
|
|
@@ -194,7 +194,7 @@
|
|
|
194
194
|
Success
|
|
195
195
|
ErrorMessage
|
|
196
196
|
}
|
|
197
|
-
}`,y=await this.ExecuteGQL(
|
|
197
|
+
}`,y=await this.ExecuteGQL(f,{input:n});if(y&&y[r]){const l=y[r].Results;if(l&&l.length>0){const R=i.Fields.filter(h=>h.CodeName!==h.Name&&h.CodeName!==void 0);l.forEach(h=>{this.ConvertBackToMJFields(h),R.forEach(D=>{h[D.Name]=h[D.CodeName]})})}const d=y[r];return await this.PostProcessRunView(d,e,t),d}}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=[],n=[];for(const i of e){let c="",p="";const m={};let f=null,y=null;if(i.ViewEntity)y=i.ViewEntity,f=y.Get("Entity");else{const{entityName:h,v:D}=await this.getEntityNameAndUserView(i,t);y=D,f=h}const l=this.Entities.find(h=>h.Name===f);if(!l)throw new Error(`Entity ${f} not found in metadata`);s.push(l);let d=!1;const R=this.getGraphQLTypeNameBase(l);i.ViewID?(c=`Run${R}ViewByID`,p="RunViewByIDInput",m.ViewID=i.ViewID):i.ViewName?(c=`Run${R}ViewByName`,p="RunViewByNameInput",m.ViewName=i.ViewName):(d=!0,c=`Run${R}DynamicView`,p="RunDynamicViewInput",m.EntityName=i.EntityName),m.ExtraFilter=i.ExtraFilter||"",m.OrderBy=i.OrderBy||"",m.UserSearchString=i.UserSearchString||"",m.Fields=i.Fields,m.IgnoreMaxRows=i.IgnoreMaxRows||!1,i.MaxRows!==void 0&&(m.MaxRows=i.MaxRows),i.StartRow!==void 0&&(m.StartRow=i.StartRow),m.ForceAuditLog=i.ForceAuditLog||!1,m.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(m.AuditLogDescription=i.AuditLogDescription),d||(m.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=i.OverrideExcludeFilter||"",m.SaveViewResults=i.SaveViewResults||!1),r.push(m),n.push(...this.getViewRunTimeFieldList(l,y,i,d))}const a=g.gql`
|
|
198
198
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
199
199
|
RunViews(input: $input) {
|
|
200
200
|
Results {
|
|
@@ -212,7 +212,7 @@
|
|
|
212
212
|
Success
|
|
213
213
|
ErrorMessage
|
|
214
214
|
}
|
|
215
|
-
}`,o=await this.ExecuteGQL(a,{input:r});if(o&&o.RunViews){const i=o.RunViews;for(const[c,p]of i.entries())p.Results=p.Results.map(
|
|
215
|
+
}`,o=await this.ExecuteGQL(a,{input:r});if(o&&o.RunViews){const i=o.RunViews;for(const[c,p]of i.entries())p.Results=p.Results.map(m=>{let f=JSON.parse(m.Data);return this.ConvertBackToMJFields(f),f});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 ge.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await ge.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=[],a=new v;if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(a.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(a.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(a.MapFieldName(o.EntityField.CodeName))})}return n}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((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=g.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
216
216
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
217
217
|
EntityName
|
|
218
218
|
RelatedEntityName
|
|
@@ -224,7 +224,7 @@
|
|
|
224
224
|
}
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=
|
|
227
|
+
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=g.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
228
228
|
GetRecordDuplicates(params: $params) {
|
|
229
229
|
Status
|
|
230
230
|
ErrorMessage
|
|
@@ -246,7 +246,7 @@
|
|
|
246
246
|
}
|
|
247
247
|
}
|
|
248
248
|
}
|
|
249
|
-
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.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=
|
|
249
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.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=g.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
250
250
|
MergeRecords(request: $request) {
|
|
251
251
|
Success
|
|
252
252
|
OverallStatus
|
|
@@ -263,32 +263,32 @@
|
|
|
263
263
|
Message
|
|
264
264
|
}
|
|
265
265
|
}
|
|
266
|
-
}`,a={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(n,{request:a}))?.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){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const o=this.getGraphQLTypeNameBase(e.EntityInfo),i=`${a}${o}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new v,
|
|
266
|
+
}`,a={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(n,{request:a}))?.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){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const o=this.getGraphQLTypeNameBase(e.EntityInfo),i=`${a}${o}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new v,m=` ${i}(input: $input) {
|
|
267
267
|
${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
|
|
268
268
|
`)}
|
|
269
|
-
}`,
|
|
270
|
-
${
|
|
269
|
+
}`,f=g.gql`mutation ${a}${o} ($input: ${i}Input!) {
|
|
270
|
+
${m}
|
|
271
271
|
}
|
|
272
|
-
`;for(let y=0;y<c.length;y++){const l=c[y];let d=l.Value;if(d)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:d=d.getTime();break;case u.EntityFieldTSType.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case u.EntityFieldTSType.Number:if(typeof d!="number"){const
|
|
272
|
+
`;for(let y=0;y<c.length;y++){const l=c[y];let d=l.Value;if(d)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:d=d.getTime();break;case u.EntityFieldTSType.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case u.EntityFieldTSType.Number:if(typeof d!="number"){const R=Number(d);isNaN(R)||(d=R)}break}d===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?d=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?d=0:d=""),n.input[l.CodeName]=d}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(l=>{let d=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?d=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?d=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?d=l.OldValue.toString():d=l.OldValue),y.push({Key:l.CodeName,Value:d})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:i+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",m,n,{mutationName:i,mutationInputTypes:y},(l,d)=>{s.EndedAt=new Date,d&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(f,n);if(y&&y[i])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[i]),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 a="",o="";for(let y=0;y<t.KeyValuePairs.length;y++){const l=e.Fields.find(h=>h.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),R=l.GraphQLType;if(o.length>0&&(o+=", "),o+=`$${l.CodeName}: ${R}!`,a.length>0&&(a+=", "),a+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${l.Name}) is not a valid number`);n[l.CodeName]=parseInt(d)}else n[l.CodeName]=d}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=this.getGraphQLTypeNameBase(e.EntityInfo),p=new v,m=g.gql`query Single${c}${i.length>0?"Full":""} (${o}) {
|
|
273
273
|
${c}(${a}) {
|
|
274
274
|
${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
|
|
275
275
|
`)}
|
|
276
276
|
${i}
|
|
277
277
|
}
|
|
278
278
|
}
|
|
279
|
-
`,
|
|
279
|
+
`,f=await this.ExecuteGQL(m,n);return f&&f[c]?this.ConvertBackToMJFields(f[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(i=>i.ID===n.RelatedEntityID);let o="";n.Type.toLowerCase().trim()==="many to many"?o=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:o=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
280
280
|
${o} {
|
|
281
281
|
${a.Fields.map(i=>i.CodeName).join(`
|
|
282
282
|
`)}
|
|
283
283
|
}
|
|
284
|
-
`}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 n={},a=[];let o="",i="",c="";for(let l of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(
|
|
285
|
-
`),c+=`${d.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const
|
|
284
|
+
`}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 n={},a=[];let o="",i="",c="";for(let l of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(R=>R.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());n[d.CodeName]=d.Value,a.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),o.length>0&&(o+=", "),o+=`${d.CodeName}: $${d.CodeName}`,i.length>0&&(i+=", "),i+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
|
|
285
|
+
`),c+=`${d.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const m="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),f=g.gql`${m}(${o}, options___: $options___) {
|
|
286
286
|
${c}
|
|
287
287
|
}
|
|
288
|
-
`,y=
|
|
289
|
-
${
|
|
288
|
+
`,y=g.gql`mutation ${m} (${i}, $options___: DeleteOptionsInput!) {
|
|
289
|
+
${f}
|
|
290
290
|
}
|
|
291
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",
|
|
291
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",f,n,{mutationName:m,mutationInputTypes:a},(l,d)=>{if(s.EndedAt=new Date,d&&l){let R=!0;for(const h of e.PrimaryKey.KeyValuePairs)h.Value!==l[h.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(y,n);if(l&&l[m]){const d=l[m];for(let R of e.PrimaryKey.KeyValuePairs){let h=d[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof h=="number"&&(h=h.toString()),D!==h)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${h}`)}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=g.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
292
292
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
293
293
|
DatasetID
|
|
294
294
|
DatasetName
|
|
@@ -297,7 +297,7 @@
|
|
|
297
297
|
LatestUpdateDate
|
|
298
298
|
Results
|
|
299
299
|
}
|
|
300
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=
|
|
300
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=g.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
301
301
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
302
302
|
DatasetID
|
|
303
303
|
DatasetName
|
|
@@ -306,22 +306,22 @@
|
|
|
306
306
|
LatestUpdateDate
|
|
307
307
|
EntityUpdateDates
|
|
308
308
|
}
|
|
309
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new N(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(i=>i.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=
|
|
309
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new N(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(i=>i.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=g.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
310
310
|
GetRecordFavoriteStatus(params: $params) {
|
|
311
311
|
Success
|
|
312
312
|
IsFavorite
|
|
313
313
|
}
|
|
314
|
-
}`,o=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(o&&o.GetRecordFavoriteStatus&&o.GetRecordFavoriteStatus.Success)return o.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(c=>c.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=
|
|
314
|
+
}`,o=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(o&&o.GetRecordFavoriteStatus&&o.GetRecordFavoriteStatus.Success)return o.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(c=>c.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=g.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
315
315
|
SetRecordFavoriteStatus(params: $params){
|
|
316
316
|
Success
|
|
317
317
|
}
|
|
318
|
-
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.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=
|
|
318
|
+
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.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=g.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
319
319
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
320
320
|
Success
|
|
321
321
|
Status
|
|
322
322
|
RecordName
|
|
323
323
|
}
|
|
324
|
-
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=
|
|
324
|
+
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=g.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
325
325
|
GetEntityRecordNames(info: $info) {
|
|
326
326
|
Success
|
|
327
327
|
Status
|
|
@@ -334,28 +334,28 @@
|
|
|
334
334
|
EntityName
|
|
335
335
|
RecordName
|
|
336
336
|
}
|
|
337
|
-
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=
|
|
337
|
+
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=g.gql`query GetDataContextData ($DataContextID: String!) {
|
|
338
338
|
GetDataContextData(DataContextID: $DataContextID) {
|
|
339
339
|
Success
|
|
340
340
|
ErrorMessages
|
|
341
341
|
Results
|
|
342
342
|
}
|
|
343
|
-
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=
|
|
343
|
+
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=g.gql`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
344
344
|
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
345
345
|
Success
|
|
346
346
|
ErrorMessage
|
|
347
347
|
Result
|
|
348
348
|
}
|
|
349
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return
|
|
349
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(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 I.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const n={"x-session-id":r};return t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),new g.GraphQLClient(e,{headers:n})}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__")+`
|
|
350
350
|
`:s.startsWith("_")||(t+=s+`
|
|
351
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new
|
|
351
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new L),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=Ie.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),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,a])=>{const o=e-a.lastRequestedAt,i=e-a.lastEmissionAt;a.activeSubscribers===0&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(o/1e3)}s, timeSinceEmission=${Math.round(i/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(o){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,o)}}),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:a=>{r.next(a.data)},error:async a=>{const o=a;if(o?.extensions?.code==="JWT_EXPIRED"||o?.message?.includes("token has expired")||o?.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(a)},complete:()=>{r.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(i=>{r.activeSubscribers++;const c=r.subject.subscribe(i);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,c.unsubscribe()}});const s=g.gql`subscription StatusUpdates($sessionId: String!) {
|
|
352
352
|
statusUpdates(sessionId: $sessionId) {
|
|
353
353
|
date
|
|
354
354
|
message
|
|
355
355
|
sessionId
|
|
356
356
|
}
|
|
357
357
|
}
|
|
358
|
-
`,n=new $.Subject,a=this.getOrCreateWSClient(),o=new $.Subscription;return o.add(new $.Observable(i=>{const c=a.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const
|
|
358
|
+
`,n=new $.Subject,a=this.getOrCreateWSClient(),o=new $.Subscription;return o.add(new $.Observable(i=>{const c=a.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const m=this._pushStatusSubjects.get(e);m&&(m.lastEmissionAt=Date.now()),i.next(p.data.statusUpdates.message)},error:async p=>{const m=p;if(m?.extensions?.code==="JWT_EXPIRED"||m?.message?.includes("token has expired")||m?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),i.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),i.error(y)}}else i.error(p)},complete:()=>{i.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:i=>n.next(i),error:i=>{n.error(i),this._pushStatusSubjects.delete(e)},complete:()=>{n.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:n,subscription:o,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(i=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const p=n.subscribe(i);return()=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers>0&&m.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}},S(I,"_GraphQLDataProvider"),I);pe.MJ_CORE_SCHEMA="__mj";let Se=pe;const H=class H{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};S(H,"BrowserStorageProviderBase");let T=H;const De="MJ_Metadata",P="Metadata_KVPairs",Z=class Z extends T{constructor(){super(),this.dbPromise=Re.openDB(De,1,{upgrade(e){e.objectStoreNames.contains(P)||e.createObjectStore(P)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(P,"readwrite");await s.objectStore(P).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(P).objectStore(P).get(e)}async remove(e){const r=(await this.dbPromise).transaction(P,"readwrite");await r.objectStore(P).delete(e),await r.done}};S(Z,"BrowserIndexedDBStorageProvider");let L=Z;async function we(E){const e=new Se;return u.SetProvider(e),await e.Config(E),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}S(we,"setupGraphQLClient");const Y=class Y{};S(Y,"SyncRolesAndUsersResult");let V=Y;const ee=class ee{};S(ee,"RoleInput");let x=ee;const te=class te{};S(te,"UserInput");let G=te;const re=class re{};S(re,"RolesAndUsersInput");let M=re;var he=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(he||{});const se=class se{};S(se,"ActionItemInput");let F=se;const ne=class ne{constructor(){this.Results=[]}};S(ne,"SyncDataResult");let Q=ne;const ae=class ae{};S(ae,"ActionItemOutput");let A=ae;const ie=class ie{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 g.GraphQLClient(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
359
359
|
GetData(input: $input) {
|
|
360
360
|
Success
|
|
361
361
|
ErrorMessages
|
|
@@ -622,7 +622,7 @@
|
|
|
622
622
|
ID
|
|
623
623
|
Name
|
|
624
624
|
}
|
|
625
|
-
}`,s={ID:e};t!==void 0&&(s.options=t);const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=
|
|
625
|
+
}`,s={ID:e};t!==void 0&&(s.options=t);const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=g.gql`
|
|
626
626
|
query RunAIPromptSystemUser(
|
|
627
627
|
$promptId: String!,
|
|
628
628
|
$data: String,
|
|
@@ -681,7 +681,7 @@
|
|
|
681
681
|
chatResult
|
|
682
682
|
}
|
|
683
683
|
}
|
|
684
|
-
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=
|
|
684
|
+
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=g.gql`
|
|
685
685
|
query RunAIAgentSystemUser(
|
|
686
686
|
$agentId: String!,
|
|
687
687
|
$messages: String!,
|
|
@@ -708,7 +708,7 @@
|
|
|
708
708
|
result
|
|
709
709
|
}
|
|
710
710
|
}
|
|
711
|
-
`,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 w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=
|
|
711
|
+
`,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 w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=g.gql`
|
|
712
712
|
query ExecuteSimplePromptSystemUser(
|
|
713
713
|
$systemPrompt: String!,
|
|
714
714
|
$messages: String,
|
|
@@ -731,7 +731,7 @@
|
|
|
731
731
|
executionTimeMs
|
|
732
732
|
}
|
|
733
733
|
}
|
|
734
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=
|
|
734
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=g.gql`
|
|
735
735
|
query EmbedTextSystemUser(
|
|
736
736
|
$textToEmbed: [String!]!,
|
|
737
737
|
$modelSize: String!
|
|
@@ -746,7 +746,7 @@
|
|
|
746
746
|
error
|
|
747
747
|
}
|
|
748
748
|
}
|
|
749
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};S(ie,"GraphQLSystemUserClient");let U=ie;const oe=class oe{};S(oe,"GetDataOutput");let
|
|
749
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};S(ie,"GraphQLSystemUserClient");let U=ie;const oe=class oe{};S(oe,"GetDataOutput");let _=oe;const ue=class ue{};S(ue,"SimpleRemoteEntityOutput");let q=ue;const ce=class ce{};S(ce,"SimpleRemoteEntity");let O=ce;const le=class le{};S(le,"SimpleRemoteEntityField");let k=le;const de=class de{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=g.gql`
|
|
750
750
|
mutation RunAction($input: RunActionInput!) {
|
|
751
751
|
RunAction(input: $input) {
|
|
752
752
|
Success
|
|
@@ -755,7 +755,7 @@
|
|
|
755
755
|
ResultData
|
|
756
756
|
}
|
|
757
757
|
}
|
|
758
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=
|
|
758
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=g.gql`
|
|
759
759
|
mutation RunEntityAction($input: EntityActionInput!) {
|
|
760
760
|
RunEntityAction(input: $input) {
|
|
761
761
|
Success
|
|
@@ -763,7 +763,7 @@
|
|
|
763
763
|
ResultData
|
|
764
764
|
}
|
|
765
765
|
}
|
|
766
|
-
`;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}}};S(de,"GraphQLActionClient");let
|
|
766
|
+
`;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}}};S(de,"GraphQLActionClient");let B=de;const ye=class ye{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const o=JSON.parse(a);o.resolver==="RunTestResolver"&&o.type==="TestExecutionProgress"&&o.status==="ok"&&o.data?.progress&&e.onProgress(o.data.progress)}catch(o){console.error("[GraphQLTestingClient] Failed to parse progress message:",o)}}));const r=g.gql`
|
|
767
767
|
mutation RunTest(
|
|
768
768
|
$testId: String!,
|
|
769
769
|
$verbose: Boolean,
|
|
@@ -780,7 +780,7 @@
|
|
|
780
780
|
result
|
|
781
781
|
}
|
|
782
782
|
}
|
|
783
|
-
`,s={testId:e.testId,verbose:e.verbose,environment:e.environment},n=await this._dataProvider.ExecuteGQL(r,s);return this.processTestResult(n.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const o=JSON.parse(a);o.resolver==="RunTestResolver"&&o.type==="TestExecutionProgress"&&o.status==="ok"&&o.data?.progress&&e.onProgress(o.data.progress)}catch(o){console.error("[GraphQLTestingClient] Failed to parse progress message:",o)}}));const r=
|
|
783
|
+
`,s={testId:e.testId,verbose:e.verbose,environment:e.environment},n=await this._dataProvider.ExecuteGQL(r,s);return this.processTestResult(n.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const o=JSON.parse(a);o.resolver==="RunTestResolver"&&o.type==="TestExecutionProgress"&&o.status==="ok"&&o.data?.progress&&e.onProgress(o.data.progress)}catch(o){console.error("[GraphQLTestingClient] Failed to parse progress message:",o)}}));const r=g.gql`
|
|
784
784
|
mutation RunTestSuite(
|
|
785
785
|
$suiteId: String!,
|
|
786
786
|
$verbose: Boolean,
|
|
@@ -799,11 +799,11 @@
|
|
|
799
799
|
result
|
|
800
800
|
}
|
|
801
801
|
}
|
|
802
|
-
`,s={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel},n=await this._dataProvider.ExecuteGQL(r,s);return this.processSuiteResult(n.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=
|
|
802
|
+
`,s={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel},n=await this._dataProvider.ExecuteGQL(r,s);return this.processSuiteResult(n.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=g.gql`
|
|
803
803
|
query IsTestRunning($testId: String!) {
|
|
804
804
|
IsTestRunning(testId: $testId)
|
|
805
805
|
}
|
|
806
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};S(ye,"GraphQLTestingClient");let
|
|
806
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};S(ye,"GraphQLTestingClient");let J=ye;const me=class me{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=g.gql`
|
|
807
807
|
query GetRegistryComponent(
|
|
808
808
|
$registryName: String!,
|
|
809
809
|
$namespace: String!,
|
|
@@ -824,7 +824,7 @@
|
|
|
824
824
|
specification
|
|
825
825
|
}
|
|
826
826
|
}
|
|
827
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return u.LogError(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=
|
|
827
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return u.LogError(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=g.gql`
|
|
828
828
|
query GetRegistryComponent(
|
|
829
829
|
$registryName: String!,
|
|
830
830
|
$namespace: String!,
|
|
@@ -845,7 +845,7 @@
|
|
|
845
845
|
specification
|
|
846
846
|
}
|
|
847
847
|
}
|
|
848
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(o){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${o}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=
|
|
848
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(o){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${o}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=g.gql`
|
|
849
849
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
850
850
|
SearchRegistryComponents(params: $params) {
|
|
851
851
|
components
|
|
@@ -854,7 +854,7 @@
|
|
|
854
854
|
limit
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=
|
|
857
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=g.gql`
|
|
858
858
|
query ResolveComponentDependencies(
|
|
859
859
|
$registryId: String!,
|
|
860
860
|
$componentId: String!
|
|
@@ -879,7 +879,7 @@
|
|
|
879
879
|
}
|
|
880
880
|
}
|
|
881
881
|
}
|
|
882
|
-
`,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=
|
|
882
|
+
`,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=g.gql`
|
|
883
883
|
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
884
884
|
SendComponentFeedback(feedback: $feedback) {
|
|
885
885
|
success
|
|
@@ -887,5 +887,5 @@
|
|
|
887
887
|
error
|
|
888
888
|
}
|
|
889
889
|
}
|
|
890
|
-
`,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"}}}};S(me,"GraphQLComponentRegistryClient");let
|
|
890
|
+
`,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"}}}};S(me,"GraphQLComponentRegistryClient");let K=me;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return g.gql}}),exports.ActionItemInput=F,exports.ActionItemOutput=A,exports.FieldMapper=v,exports.GetDataOutput=_,exports.GraphQLAIClient=C,exports.GraphQLActionClient=B,exports.GraphQLComponentRegistryClient=K,exports.GraphQLDataProvider=Se,exports.GraphQLProviderConfigData=b,exports.GraphQLSystemUserClient=U,exports.GraphQLTestingClient=J,exports.GraphQLTransactionGroup=N,exports.RoleInput=x,exports.RolesAndUsersInput=M,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=k,exports.SimpleRemoteEntityOutput=q,exports.SyncDataAction=he,exports.SyncDataResult=Q,exports.SyncRolesAndUsersResult=V,exports.UserInput=G,exports.setupGraphQLClient=we;
|
|
891
891
|
//# sourceMappingURL=index.cjs.map
|