@memberjunction/graphql-dataprovider 2.111.1 → 2.113.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 +38 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +37 -37
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ee=Object.defineProperty;var f=(I,e)=>Ee(I,"name",{value:e,configurable:!0});var h;import{gql as m,GraphQLClient as me}from"graphql-request";import{gql as ze}from"graphql-request";import{TransactionGroupBase as $e,TransactionResult as Pe,LogError as d,LogStatusEx as v,ProviderConfigDataBase as Ne,ProviderBase as ve,UserInfo as ge,ProviderType as Ce,BaseEntityResult as pe,EntityFieldTSType as E,TransactionItem as fe,UserRoleInfo as Ve,SetProvider as xe}from"@memberjunction/core";import{ViewInfo as Se}from"@memberjunction/core-entities";import{openDB as Qe}from"@tempfix/idb";import{Observable as Re}from"rxjs";import{createClient as he}from"graphql-ws";import{v4 as Ge}from"uuid";import{SafeJSONParse as N,MJGlobal as Fe,MJEventType as Te}from"@memberjunction/global";const j=class j{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(j,"FieldMapper");let P=j;const z=class z extends $e{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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,
|
|
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,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],u=N(n),p=this.PendingTransactions[i];o.push(new Pe(p,u,u!==null))}return o}else throw new Error("Failed to execute transaction group")}};f(z,"GraphQLTransactionGroup");let C=z;const W=class W{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -65,7 +65,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
65
65
|
chatResult
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(
|
|
68
|
+
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{v({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[n]});const u=JSON.parse(n);if(v({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){v({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const p={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(p)}else v({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",n)}}));const a=m`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -104,7 +104,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
104
104
|
result
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,
|
|
107
|
+
`,o=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,o);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return N(e)}handleAgentError(e){return d(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=m`
|
|
108
108
|
mutation ExecuteSimplePrompt(
|
|
109
109
|
$systemPrompt: String!,
|
|
110
110
|
$messages: String,
|
|
@@ -127,7 +127,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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 a=s.ExecuteSimplePrompt;let
|
|
130
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return d(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m`
|
|
131
131
|
mutation EmbedText(
|
|
132
132
|
$textToEmbed: [String!]!,
|
|
133
133
|
$modelSize: String!
|
|
@@ -142,7 +142,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
142
142
|
error
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const
|
|
145
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const o=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return d(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(W,"GraphQLAIClient");let V=W;const H=class H extends Ne{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,o,i,n){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,RefreshTokenFunction:s},a,o,i)}};f(H,"GraphQLProviderConfigData");let x=H;const De=(h=class extends ve{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
|
|
146
146
|
${this.userInfoString()}
|
|
147
147
|
UserRoles_UserIDArray {
|
|
148
148
|
${this.userRoleInfoString()}
|
|
@@ -150,7 +150,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
150
150
|
}
|
|
151
151
|
`,this._currentUserQuery=m`query CurrentUserAndRoles {
|
|
152
152
|
${this._innerCurrentUserQueryString}
|
|
153
|
-
}`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new
|
|
153
|
+
}`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new V(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Ge()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return r?(this._configData=e,this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId)),super.Config(e)}catch(a){throw d(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new ge(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
|
|
154
154
|
query GetReportDataQuery ($ReportID: String!) {
|
|
155
155
|
GetReportData(ReportID: $ReportID) {
|
|
156
156
|
Success
|
|
@@ -159,19 +159,19 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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,a,
|
|
162
|
+
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,o,i){const n=m`
|
|
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
|
-
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),
|
|
168
|
+
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(n,u);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=m`
|
|
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}
|
|
172
172
|
}
|
|
173
173
|
}
|
|
174
|
-
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),
|
|
174
|
+
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(n,u);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
175
175
|
Success
|
|
176
176
|
QueryID
|
|
177
177
|
QueryName
|
|
@@ -180,7 +180,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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 d(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let
|
|
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 d(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:c,v:l}=await this.getEntityNameAndUserView(e,t);i=l,o=c}const n=this.Entities.find(c=>c.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let u=!1;const p=this.getGraphQLTypeNameBase(n);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(u=!0,r=`Run${p}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),u||(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 g=this.getViewRunTimeFieldList(n,i,e,u),D=m`
|
|
184
184
|
query RunViewQuery ($input: ${s}!) {
|
|
185
185
|
${r}(input: $input) {
|
|
186
186
|
Results {
|
|
@@ -194,7 +194,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
194
194
|
Success
|
|
195
195
|
ErrorMessage
|
|
196
196
|
}
|
|
197
|
-
}`,y=await this.ExecuteGQL(D,{input:a});if(y&&y[r]){const c=y[r].Results;if(c&&c.length>0){const R=
|
|
197
|
+
}`,y=await this.ExecuteGQL(D,{input:a});if(y&&y[r]){const c=y[r].Results;if(c&&c.length>0){const R=n.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);c.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(w=>{S[w.Name]=S[w.CodeName]})})}const l=y[r];return await this.PostProcessRunView(l,e,t),l}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const n of e){let u="",p="";const g={};let D=null,y=null;if(n.ViewEntity)y=n.ViewEntity,D=y.Get("Entity");else{const{entityName:S,v:w}=await this.getEntityNameAndUserView(n,t);y=w,D=S}const c=this.Entities.find(S=>S.Name===D);if(!c)throw new Error(`Entity ${D} not found in metadata`);s.push(c);let l=!1;const R=this.getGraphQLTypeNameBase(c);n.ViewID?(u=`Run${R}ViewByID`,p="RunViewByIDInput",g.ViewID=n.ViewID):n.ViewName?(u=`Run${R}ViewByName`,p="RunViewByNameInput",g.ViewName=n.ViewName):(l=!0,u=`Run${R}DynamicView`,p="RunDynamicViewInput",g.EntityName=n.EntityName),g.ExtraFilter=n.ExtraFilter||"",g.OrderBy=n.OrderBy||"",g.UserSearchString=n.UserSearchString||"",g.Fields=n.Fields,g.IgnoreMaxRows=n.IgnoreMaxRows||!1,n.MaxRows!==void 0&&(g.MaxRows=n.MaxRows),n.StartRow!==void 0&&(g.StartRow=n.StartRow),g.ForceAuditLog=n.ForceAuditLog||!1,g.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(g.AuditLogDescription=n.AuditLogDescription),l||(g.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=n.OverrideExcludeFilter||"",g.SaveViewResults=n.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(c,y,n,l))}const o=m`
|
|
198
198
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
199
199
|
RunViews(input: $input) {
|
|
200
200
|
Results {
|
|
@@ -212,7 +212,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
212
212
|
Success
|
|
213
213
|
ErrorMessage
|
|
214
214
|
}
|
|
215
|
-
}`,i=await this.ExecuteGQL(
|
|
215
|
+
}`,i=await this.ExecuteGQL(o,{input:r});if(i&&i.RunViews){const n=i.RunViews;for(const[u,p]of n.entries())p.Results=p.Results.map(g=>{let D=JSON.parse(g.Data);return this.ConvertBackToMJFields(D),D});return await this.PostProcessRunViews(n,e,t),n}return null}catch(r){throw d(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await Se.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Se.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=[],o=new P;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return Ce.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,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw d(r),r}}async GetRecordDependencies(e,t){try{const r=m`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
216
216
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
217
217
|
EntityName
|
|
218
218
|
RelatedEntityName
|
|
@@ -246,7 +246,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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(
|
|
249
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=m`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
250
250
|
MergeRecords(request: $request) {
|
|
251
251
|
Success
|
|
252
252
|
OverallStatus
|
|
@@ -263,32 +263,32 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
263
263
|
Message
|
|
264
264
|
}
|
|
265
265
|
}
|
|
266
|
-
}`,
|
|
266
|
+
}`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(n=>({FieldName:n.FieldName,Value:n.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(n=>n.Copy())};return(await this.ExecuteGQL(a,{request:o}))?.MergeRecords}catch(a){return d(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new pe;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=this.getGraphQLTypeNameBase(e.EntityInfo),n=`${o}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new P,g=` ${n}(input: $input) {
|
|
267
267
|
${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
|
|
268
268
|
`)}
|
|
269
|
-
}`,D=m`mutation ${
|
|
269
|
+
}`,D=m`mutation ${o}${i} ($input: ${n}Input!) {
|
|
270
270
|
${g}
|
|
271
271
|
}
|
|
272
|
-
`;for(let y=0;y<u.length;y++){const c=u[y];let l=c.Value;if(l)switch(c.EntityFieldInfo.TSType){case E.Date:l=l.getTime();break;case E.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case E.Number:if(typeof l!="number"){const R=Number(l);isNaN(R)||(l=R)}break}l===null&&c.EntityFieldInfo.AllowsNull===!1&&(c.EntityFieldInfo.DefaultValue!==null?l=c.EntityFieldInfo.DefaultValue:c.FieldType===E.Number||c.FieldType===E.Boolean?l=0:l=""),a.input[c.CodeName]=l}if(
|
|
273
|
-
${u}(${
|
|
272
|
+
`;for(let y=0;y<u.length;y++){const c=u[y];let l=c.Value;if(l)switch(c.EntityFieldInfo.TSType){case E.Date:l=l.getTime();break;case E.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case E.Number:if(typeof l!="number"){const R=Number(l);isNaN(R)||(l=R)}break}l===null&&c.EntityFieldInfo.AllowsNull===!1&&(c.EntityFieldInfo.DefaultValue!==null?l=c.EntityFieldInfo.DefaultValue:c.FieldType===E.Number||c.FieldType===E.Boolean?l=0:l=""),a.input[c.CodeName]=l}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(c=>{let l=null;c.OldValue!==null&&c.OldValue!==void 0&&(c.EntityFieldInfo.TSType===E.Date?l=c.OldValue.getTime().toString():c.EntityFieldInfo.TSType===E.Boolean?l=c.OldValue===!0?"1":"0":typeof c.OldValue!="string"?l=c.OldValue.toString():l=c.OldValue),y.push({Key:c.CodeName,Value:l})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new fe(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:n,mutationInputTypes:y},(c,l)=>{s.EndedAt=new Date,l&&c?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(c)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(D,a);if(y&&y[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[n]),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,d(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const c=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,l=t.GetValueByIndex(y),R=c.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${c.CodeName}: ${R}!`,o.length>0&&(o+=", "),o+=`${c.CodeName}: $${c.CodeName}`,c.TSType===E.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${l} (${c.Name}) is not a valid number`);a[c.CodeName]=parseInt(l)}else a[c.CodeName]=l}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=this.getGraphQLTypeNameBase(e.EntityInfo),p=new P,g=m`query Single${u}${n.length>0?"Full":""} (${i}) {
|
|
273
|
+
${u}(${o}) {
|
|
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
|
+
${n}
|
|
277
277
|
}
|
|
278
278
|
}
|
|
279
|
-
`,D=await this.ExecuteGQL(g,a);return D&&D[u]?this.ConvertBackToMJFields(D[u]):null}catch(a){return d(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],
|
|
279
|
+
`,D=await this.ExecuteGQL(g,a);return D&&D[u]?this.ConvertBackToMJFields(D[u]):null}catch(a){return d(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],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
280
280
|
${i} {
|
|
281
|
-
${
|
|
281
|
+
${o.Fields.map(n=>n.CodeName).join(`
|
|
282
282
|
`)}
|
|
283
283
|
}
|
|
284
|
-
`}return r}async Delete(e,t,r){const s=new
|
|
285
|
-
`),u+=`${l.CodeName}`}
|
|
284
|
+
`}return r}async Delete(e,t,r){const s=new pe;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",u="";for(let c of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(R=>R.Name.trim().toLowerCase()===c.FieldName.trim().toLowerCase());a[l.CodeName]=l.Value,o.push({varName:l.CodeName,inputType:l.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${l.CodeName}: $${l.CodeName}`,n.length>0&&(n+=", "),n+=`$${l.CodeName}: ${l.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
|
|
285
|
+
`),u+=`${l.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),D=m`${g}(${i}, options___: $options___) {
|
|
286
286
|
${u}
|
|
287
287
|
}
|
|
288
|
-
`,y=m`mutation ${g} (${
|
|
288
|
+
`,y=m`mutation ${g} (${n}, $options___: DeleteOptionsInput!) {
|
|
289
289
|
${D}
|
|
290
290
|
}
|
|
291
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new
|
|
291
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new fe(e,"Delete",D,a,{mutationName:g,mutationInputTypes:o},(c,l)=>{if(s.EndedAt=new Date,l&&c){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==c[S.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const c=await this.ExecuteGQL(y,a);if(c&&c[g]){const l=c[g];for(let R of e.PrimaryKey.KeyValuePairs){let S=l[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof S=="number"&&(S=S.toString()),w!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,d(a),!1}}async GetDatasetByName(e,t){const r=m`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
292
292
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
293
293
|
DatasetID
|
|
294
294
|
DatasetName
|
|
@@ -306,16 +306,16 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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
|
|
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 C(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=m`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
310
310
|
GetRecordFavoriteStatus(params: $params) {
|
|
311
311
|
Success
|
|
312
312
|
IsFavorite
|
|
313
313
|
}
|
|
314
|
-
}`,i=await this.ExecuteGQL(
|
|
314
|
+
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(u=>u.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=m`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
315
315
|
SetRecordFavoriteStatus(params: $params){
|
|
316
316
|
Success
|
|
317
317
|
}
|
|
318
|
-
}`,
|
|
318
|
+
}`,n=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
319
319
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
320
320
|
Success
|
|
321
321
|
Status
|
|
@@ -346,16 +346,16 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
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 d(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new
|
|
349
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw d(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new me(e,{headers:a})}userInfoString(){return this.infoString(new ge(null,null))}userRoleInfoString(){return this.infoString(new Ve(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 G),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=he({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new Re(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=he({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=m`subscription StatusUpdates($sessionId: String!) {
|
|
352
352
|
statusUpdates(sessionId: $sessionId) {
|
|
353
353
|
date
|
|
354
354
|
message
|
|
355
355
|
sessionId
|
|
356
356
|
}
|
|
357
357
|
}
|
|
358
|
-
`,s=new
|
|
358
|
+
`,s=new Re(a=>{const o=this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:i=>a.next(i.data.statusUpdates.message),error:i=>a.error(i),complete:()=>a.complete()});return()=>{o()}});return this._pushStatusRequests.push({sessionId:e,observable:s}),s}},f(h,"_GraphQLDataProvider"),h);De.MJ_CORE_SCHEMA="__mj";let Ie=De;const X=class X{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(X,"BrowserStorageProviderBase");let Q=X;const Ue="MJ_Metadata",$="Metadata_KVPairs",Z=class Z extends Q{constructor(){super(),this.dbPromise=Qe(Ue,1,{upgrade(e){e.objectStoreNames.contains($)||e.createObjectStore($)}})}async setItem(e,t){const s=(await this.dbPromise).transaction($,"readwrite");await s.objectStore($).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction($).objectStore($).get(e)}async remove(e){const r=(await this.dbPromise).transaction($,"readwrite");await r.objectStore($).delete(e),await r.done}};f(Z,"BrowserIndexedDBStorageProvider");let G=Z;async function be(I){const e=new Ie;return xe(e),await e.Config(I),Fe.Instance.RaiseEvent({event:Te.LoggedIn,eventCode:null,component:this,args:null}),e}f(be,"setupGraphQLClient");const Y=class Y{};f(Y,"SyncRolesAndUsersResult");let F=Y;const ee=class ee{};f(ee,"RoleInput");let T=ee;const te=class te{};f(te,"UserInput");let U=te;const re=class re{};f(re,"RolesAndUsersInput");let b=re;var we=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(we||{});const se=class se{};f(se,"ActionItemInput");let M=se;const ae=class ae{constructor(){this.Results=[]}};f(ae,"SyncDataResult");let A=ae;const ne=class ne{};f(ne,"ActionItemOutput");let L=ne;const oe=class oe{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 me(e,{headers:a})}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
|
|
@@ -699,7 +699,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
699
699
|
executionTimeMs
|
|
700
700
|
}
|
|
701
701
|
}
|
|
702
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let
|
|
702
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return d(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m`
|
|
703
703
|
query EmbedTextSystemUser(
|
|
704
704
|
$textToEmbed: [String!]!,
|
|
705
705
|
$modelSize: String!
|
|
@@ -714,7 +714,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
714
714
|
error
|
|
715
715
|
}
|
|
716
716
|
}
|
|
717
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const
|
|
717
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return d(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(oe,"GraphQLSystemUserClient");let q=oe;const ie=class ie{};f(ie,"GetDataOutput");let _=ie;const ue=class ue{};f(ue,"SimpleRemoteEntityOutput");let O=ue;const ce=class ce{};f(ce,"SimpleRemoteEntity");let B=ce;const le=class le{};f(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),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=m`
|
|
718
718
|
mutation RunAction($input: RunActionInput!) {
|
|
719
719
|
RunAction(input: $input) {
|
|
720
720
|
Success
|
|
@@ -731,7 +731,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
731
731
|
ResultData
|
|
732
732
|
}
|
|
733
733
|
}
|
|
734
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){d(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(
|
|
734
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){d(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(de,"GraphQLActionClient");let K=de;const ye=class ye{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m`
|
|
735
735
|
query GetRegistryComponent(
|
|
736
736
|
$registryName: String!,
|
|
737
737
|
$namespace: String!,
|
|
@@ -752,7 +752,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
752
752
|
specification
|
|
753
753
|
}
|
|
754
754
|
}
|
|
755
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(
|
|
755
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(o){return d(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw d(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m`
|
|
756
756
|
query GetRegistryComponent(
|
|
757
757
|
$registryName: String!,
|
|
758
758
|
$namespace: String!,
|
|
@@ -773,7 +773,7 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
773
773
|
specification
|
|
774
774
|
}
|
|
775
775
|
}
|
|
776
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let
|
|
776
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let o;if(a.specification)try{o=JSON.parse(a.specification)}catch(i){d(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw d(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m`
|
|
777
777
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
778
778
|
SearchRegistryComponents(params: $params) {
|
|
779
779
|
components
|
|
@@ -815,5 +815,5 @@ var we=Object.defineProperty;var f=(I,e)=>we(I,"name",{value:e,configurable:!0})
|
|
|
815
815
|
error
|
|
816
816
|
}
|
|
817
817
|
}
|
|
818
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(
|
|
818
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(ye,"GraphQLComponentRegistryClient");let J=ye;export{M as ActionItemInput,L as ActionItemOutput,P as FieldMapper,_ as GetDataOutput,V as GraphQLAIClient,K as GraphQLActionClient,J as GraphQLComponentRegistryClient,Ie as GraphQLDataProvider,x as GraphQLProviderConfigData,q as GraphQLSystemUserClient,C as GraphQLTransactionGroup,T as RoleInput,b as RolesAndUsersInput,B as SimpleRemoteEntity,k as SimpleRemoteEntityField,O as SimpleRemoteEntityOutput,we as SyncDataAction,A as SyncDataResult,F as SyncRolesAndUsersResult,U as UserInput,ze as gql,be as setupGraphQLClient};
|
|
819
819
|
//# sourceMappingURL=index.mjs.map
|