@memberjunction/graphql-dataprovider 2.104.0 → 2.105.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 CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var pe=Object.defineProperty;var f=(I,e)=>pe(I,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),de=require("@memberjunction/core-entities"),fe=require("@tempfix/idb"),ye=require("rxjs"),me=require("graphql-ws"),Se=require("uuid"),E=require("@memberjunction/global");const K=class K{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(K,"FieldMapper");let P=K;const J=class J extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
1
+ "use strict";var Se=Object.defineProperty;var f=(I,e)=>Se(I,"name",{value:e,configurable:!0});var h,y=require("graphql-request"),u=require("@memberjunction/core"),de=require("@memberjunction/core-entities"),Re=require("@tempfix/idb"),ye=require("rxjs"),me=require("graphql-ws"),he=require("uuid"),E=require("@memberjunction/global");const K=class K{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(K,"FieldMapper");let $=K;const J=class J extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let o=0;o<this.PendingTransactions.length;o++){const i=a.ResultsJSON[o],m=E.SafeJSONParse(i),p=this.PendingTransactions[o];n.push(new u.TransactionResult(p,m,m!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(J,"GraphQLTransactionGroup");let $=J;const j=class j{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.gql`
9
+ `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let o=0;o<this.PendingTransactions.length;o++){const i=a.ResultsJSON[o],m=E.SafeJSONParse(i),p=this.PendingTransactions[o];n.push(new u.TransactionResult(p,m,m!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(J,"GraphQLTransactionGroup");let N=J;const j=class j{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -71,6 +71,7 @@
71
71
  $messages: String!,
72
72
  $sessionId: String!,
73
73
  $data: String,
74
+ $payload: String,
74
75
  $templateData: String,
75
76
  $lastRunId: String,
76
77
  $autoPopulateLastRunPayload: Boolean,
@@ -82,6 +83,7 @@
82
83
  messages: $messages,
83
84
  sessionId: $sessionId,
84
85
  data: $data,
86
+ payload: $payload,
85
87
  templateData: $templateData,
86
88
  lastRunId: $lastRunId,
87
89
  autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
@@ -94,7 +96,7 @@
94
96
  result
95
97
  }
96
98
  }
97
- `,s=this.prepareAgentVariables(e),a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgent?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(t.conversationDetailId=e.conversationDetailId),t}processAgentResult(e){return E.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=y.gql`
99
+ `,s=this.prepareAgentVariables(e),a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgent?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(t.conversationDetailId=e.conversationDetailId),t}processAgentResult(e){return E.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=y.gql`
98
100
  mutation ExecuteSimplePrompt(
99
101
  $systemPrompt: String!,
100
102
  $messages: String,
@@ -132,7 +134,7 @@
132
134
  error
133
135
  }
134
136
  }
135
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(j,"GraphQLAIClient");let N=j;const z=class z extends u.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,o,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},a,n,o)}};f(z,"GraphQLProviderConfigData");let C=z;const h=class h extends u.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
137
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(j,"GraphQLAIClient");let v=j;const z=class z extends u.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,o,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},a,n,o)}};f(z,"GraphQLProviderConfigData");let C=z;const ge=(h=class extends u.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
136
138
  ${this.userInfoString()}
137
139
  UserRoles_UserIDArray {
138
140
  ${this.userRoleInfoString()}
@@ -140,7 +142,7 @@
140
142
  }
141
143
  `,this._currentUserQuery=y.gql`query CurrentUserAndRoles {
142
144
  ${this._innerCurrentUserQueryString}
143
- }`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new N(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Se.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)):(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 u.LogError(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 u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=y.gql`
145
+ }`,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 he.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)):(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 u.LogError(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 u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=y.gql`
144
146
  query GetReportDataQuery ($ReportID: String!) {
145
147
  GetReportData(ReportID: $ReportID) {
146
148
  Success
@@ -170,11 +172,11 @@
170
172
  TotalRowCount
171
173
  ExecutionTime
172
174
  ErrorMessage
173
- AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let n,o;if(e.ViewEntity)o=e.ViewEntity,n=o.Entity;else{const{entityName:l,v:c}=await this.getEntityNameAndUserView(e,t);o=c,n=l}const i=this.Entities.find(l=>l.Name===n);if(!i)throw new Error(`Entity ${n} not found in metadata`);let m=!1;e.ViewID?(r=`Run${i.ClassName}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${i.ClassName}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(m=!0,r=`Run${i.ClassName}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),m||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const p=this.getViewRunTimeFieldList(i,o,e,m),g=y.gql`
175
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let n,o;if(e.ViewEntity)o=e.ViewEntity,n=o.Entity;else{const{entityName:l,v:c}=await this.getEntityNameAndUserView(e,t);o=c,n=l}const i=this.Entities.find(l=>l.Name===n);if(!i)throw new Error(`Entity ${n} not found in metadata`);let m=!1;const p=this.getGraphQLTypeNameBase(i);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(m=!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),m||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(i,o,e,m),D=y.gql`
174
176
  query RunViewQuery ($input: ${s}!) {
175
177
  ${r}(input: $input) {
176
178
  Results {
177
- ${p.join(`
179
+ ${g.join(`
178
180
  `)}
179
181
  }
180
182
  UserViewRunID
@@ -184,7 +186,7 @@
184
186
  Success
185
187
  ErrorMessage
186
188
  }
187
- }`,d=await this.ExecuteGQL(g,{input:a});if(d&&d[r]){const l=d[r].Results;if(l&&l.length>0){const R=i.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);l.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(D=>{S[D.Name]=S[D.CodeName]})})}const c=d[r];return await this.PostProcessRunView(c,e,t),c}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const i of e){let m="",p="";const g={};let d=null,l=null;if(i.ViewEntity)l=i.ViewEntity,d=l.Get("Entity");else{const{entityName:S,v:D}=await this.getEntityNameAndUserView(i,t);l=D,d=S}const c=this.Entities.find(S=>S.Name===d);if(!c)throw new Error(`Entity ${d} not found in metadata`);s.push(c);let R=!1;i.ViewID?(m=`Run${c.ClassName}ViewByID`,p="RunViewByIDInput",g.ViewID=i.ViewID):i.ViewName?(m=`Run${c.ClassName}ViewByName`,p="RunViewByNameInput",g.ViewName=i.ViewName):(R=!0,m=`Run${c.ClassName}DynamicView`,p="RunDynamicViewInput",g.EntityName=i.EntityName),g.ExtraFilter=i.ExtraFilter||"",g.OrderBy=i.OrderBy||"",g.UserSearchString=i.UserSearchString||"",g.Fields=i.Fields,g.IgnoreMaxRows=i.IgnoreMaxRows||!1,i.MaxRows!==void 0&&(g.MaxRows=i.MaxRows),i.StartRow!==void 0&&(g.StartRow=i.StartRow),g.ForceAuditLog=i.ForceAuditLog||!1,g.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(g.AuditLogDescription=i.AuditLogDescription),R||(g.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=i.OverrideExcludeFilter||"",g.SaveViewResults=i.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(c,l,i,R))}const n=y.gql`
189
+ }`,d=await this.ExecuteGQL(D,{input:a});if(d&&d[r]){const l=d[r].Results;if(l&&l.length>0){const R=i.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);l.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(w=>{S[w.Name]=S[w.CodeName]})})}const c=d[r];return await this.PostProcessRunView(c,e,t),c}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const i of e){let m="",p="";const g={};let D=null,d=null;if(i.ViewEntity)d=i.ViewEntity,D=d.Get("Entity");else{const{entityName:S,v:w}=await this.getEntityNameAndUserView(i,t);d=w,D=S}const l=this.Entities.find(S=>S.Name===D);if(!l)throw new Error(`Entity ${D} not found in metadata`);s.push(l);let c=!1;const R=this.getGraphQLTypeNameBase(l);i.ViewID?(m=`Run${R}ViewByID`,p="RunViewByIDInput",g.ViewID=i.ViewID):i.ViewName?(m=`Run${R}ViewByName`,p="RunViewByNameInput",g.ViewName=i.ViewName):(c=!0,m=`Run${R}DynamicView`,p="RunDynamicViewInput",g.EntityName=i.EntityName),g.ExtraFilter=i.ExtraFilter||"",g.OrderBy=i.OrderBy||"",g.UserSearchString=i.UserSearchString||"",g.Fields=i.Fields,g.IgnoreMaxRows=i.IgnoreMaxRows||!1,i.MaxRows!==void 0&&(g.MaxRows=i.MaxRows),i.StartRow!==void 0&&(g.StartRow=i.StartRow),g.ForceAuditLog=i.ForceAuditLog||!1,g.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(g.AuditLogDescription=i.AuditLogDescription),c||(g.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=i.OverrideExcludeFilter||"",g.SaveViewResults=i.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(l,d,i,c))}const n=y.gql`
188
190
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
189
191
  RunViews(input: $input) {
190
192
  Results {
@@ -202,7 +204,7 @@
202
204
  Success
203
205
  ErrorMessage
204
206
  }
205
- }`,o=await this.ExecuteGQL(n,{input:r});if(o&&o.RunViews){const i=o.RunViews;for(const[m,p]of i.entries())p.Results=p.Results.map(g=>{let d=JSON.parse(g.Data);return this.ConvertBackToMJFields(d),d});return await this.PostProcessRunViews(i,e,t),i}return null}catch(r){throw u.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await de.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await de.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],n=new P;if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);r.Fields.forEach(o=>{a.push(n.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||a.push(n.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)a.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!a.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&a.push(n.MapFieldName(o.EntityField.CodeName))})}return a}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
207
+ }`,o=await this.ExecuteGQL(n,{input:r});if(o&&o.RunViews){const i=o.RunViews;for(const[m,p]of i.entries())p.Results=p.Results.map(g=>{let D=JSON.parse(g.Data);return this.ConvertBackToMJFields(D),D});return await this.PostProcessRunViews(i,e,t),i}return null}catch(r){throw u.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await de.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await de.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],n=new $;if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);r.Fields.forEach(o=>{a.push(n.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||a.push(n.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)a.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!a.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&a.push(n.MapFieldName(o.EntityField.CodeName))})}return a}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
206
208
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
207
209
  EntityName
208
210
  RelatedEntityName
@@ -253,32 +255,32 @@
253
255
  Message
254
256
  }
255
257
  }
256
- }`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(i=>({FieldName:i.FieldName,Value:i.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(i=>i.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.MergeRecords}catch(a){return u.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const o=`${n}${e.EntityInfo.ClassName}`,i=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),m=new P,p=` ${o}(input: $input) {
257
- ${e.Fields.map(d=>m.MapFieldName(d.CodeName)).join(`
258
+ }`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(i=>({FieldName:i.FieldName,Value:i.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(i=>i.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.MergeRecords}catch(a){return u.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const o=this.getGraphQLTypeNameBase(e.EntityInfo),i=`${n}${o}`,m=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),p=new $,g=` ${i}(input: $input) {
259
+ ${e.Fields.map(d=>p.MapFieldName(d.CodeName)).join(`
258
260
  `)}
259
- }`,g=y.gql`mutation ${n}${e.EntityInfo.ClassName} ($input: ${o}Input!) {
260
- ${p}
261
+ }`,D=y.gql`mutation ${n}${o} ($input: ${i}Input!) {
262
+ ${g}
261
263
  }
262
- `;for(let d=0;d<i.length;d++){const l=i[d];let c=l.Value;if(c)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:c=c.getTime();break;case u.EntityFieldTSType.Boolean:typeof c!="boolean"&&(c=parseInt(c)!==0);break;case u.EntityFieldTSType.Number:if(typeof c!="number"){const R=Number(c);isNaN(R)||(c=R)}break}c===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?c=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?c=0:c=""),a.input[l.CodeName]=c}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(l=>{let c=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?c=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?c=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?c=l.OldValue.toString():c=l.OldValue),d.push({Key:l.CodeName,Value:c})}),a.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",p,a,{mutationName:o,mutationInputTypes:d},(l,c)=>{s.EndedAt=new Date,c&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(g,a);if(d&&d[n+e.EntityInfo.ClassName])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[n+e.EntityInfo.ClassName]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let n="",o="";for(let d=0;d<t.KeyValuePairs.length;d++){const l=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,c=t.GetValueByIndex(d),R=l.GraphQLType;if(o.length>0&&(o+=", "),o+=`$${l.CodeName}: ${R}!`,n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${c} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(c)}else a[l.CodeName]=c}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=new P,p=y.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${o}) {
263
- ${e.EntityInfo.ClassName}(${n}) {
264
+ `;for(let d=0;d<m.length;d++){const l=m[d];let c=l.Value;if(c)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:c=c.getTime();break;case u.EntityFieldTSType.Boolean:typeof c!="boolean"&&(c=parseInt(c)!==0);break;case u.EntityFieldTSType.Number:if(typeof c!="number"){const R=Number(c);isNaN(R)||(c=R)}break}c===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?c=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?c=0:c=""),a.input[l.CodeName]=c}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(l=>{let c=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?c=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?c=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?c=l.OldValue.toString():c=l.OldValue),d.push({Key:l.CodeName,Value:c})}),a.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:i+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:i,mutationInputTypes:d},(l,c)=>{s.EndedAt=new Date,c&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(D,a);if(d&&d[i])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[i]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let n="",o="";for(let d=0;d<t.KeyValuePairs.length;d++){const l=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,c=t.GetValueByIndex(d),R=l.GraphQLType;if(o.length>0&&(o+=", "),o+=`$${l.CodeName}: ${R}!`,n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${c} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(c)}else a[l.CodeName]=c}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=this.getGraphQLTypeNameBase(e.EntityInfo),p=new $,g=y.gql`query Single${m}${i.length>0?"Full":""} (${o}) {
265
+ ${m}(${n}) {
264
266
  ${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
265
267
  `)}
266
268
  ${i}
267
269
  }
268
270
  }
269
- `,g=await this.ExecuteGQL(p,a);return g&&g[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(g[e.EntityInfo.ClassName]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new P().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],n=this.Entities.find(i=>i.ID===a.RelatedEntityID);let o="";a.Type.toLowerCase().trim()==="many to many"?o=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:o=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
271
+ `,D=await this.ExecuteGQL(g,a);return D&&D[m]?this.ConvertBackToMJFields(D[m]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new $().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],n=this.Entities.find(i=>i.ID===a.RelatedEntityID);let o="";a.Type.toLowerCase().trim()==="many to many"?o=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:o=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
270
272
  ${o} {
271
273
  ${n.Fields.map(i=>i.CodeName).join(`
272
274
  `)}
273
275
  }
274
276
  `}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const a={},n=[];let o="",i="",m="";for(let l of e.PrimaryKey.KeyValuePairs){const c=e.Fields.find(R=>R.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[c.CodeName]=c.Value,n.push({varName:c.CodeName,inputType:c.EntityFieldInfo.GraphQLType+"!"}),o.length>0&&(o+=", "),o+=`${c.CodeName}: $${c.CodeName}`,i.length>0&&(i+=", "),i+=`$${c.CodeName}: ${c.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
275
- `),m+=`${c.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+e.EntityInfo.ClassName,g=y.gql`${p}(${o}, options___: $options___) {
277
+ `),m+=`${c.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),D=y.gql`${g}(${o}, options___: $options___) {
276
278
  ${m}
277
279
  }
278
- `,d=y.gql`mutation ${p} (${i}, $options___: DeleteOptionsInput!) {
279
- ${g}
280
+ `,d=y.gql`mutation ${g} (${i}, $options___: DeleteOptionsInput!) {
281
+ ${D}
280
282
  }
281
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",g,a,{mutationName:p,mutationInputTypes:n},(l,c)=>{if(s.EndedAt=new Date,c&&l){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==l[S.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const l=await this.ExecuteGQL(d,a);if(l&&l[p]){const c=l[p];for(let R of e.PrimaryKey.KeyValuePairs){let S=c[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof S=="number"&&(S=S.toString()),D!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
283
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",D,a,{mutationName:g,mutationInputTypes:n},(l,c)=>{if(s.EndedAt=new Date,c&&l){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==l[S.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const l=await this.ExecuteGQL(d,a);if(l&&l[g]){const c=l[g];for(let R of e.PrimaryKey.KeyValuePairs){let S=c[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,u.LogError(a),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
282
284
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
283
285
  DatasetID
284
286
  DatasetName
@@ -296,7 +298,7 @@
296
298
  LatestUpdateDate
297
299
  EntityUpdateDates
298
300
  }
299
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new $(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(i=>i.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
301
+ }`,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 a=this.Entities.find(i=>i.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
300
302
  GetRecordFavoriteStatus(params: $params) {
301
303
  Success
302
304
  IsFavorite
@@ -338,14 +340,14 @@
338
340
  }
339
341
  }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new y.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
340
342
  `:s.startsWith("_")||(t+=s+`
341
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new L),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ye.Observable(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=y.gql`subscription StatusUpdates($sessionId: String!) {
343
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new V),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ye.Observable(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=y.gql`subscription StatusUpdates($sessionId: String!) {
342
344
  statusUpdates(sessionId: $sessionId) {
343
345
  date
344
346
  message
345
347
  sessionId
346
348
  }
347
349
  }
348
- `,s=new ye.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates.message),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}};f(h,"GraphQLDataProvider");let v=h;const W=class W{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(W,"BrowserStorageProviderBase");let V=W;const Re="MJ_Metadata",w="Metadata_KVPairs",H=class H extends V{constructor(){super(),this.dbPromise=fe.openDB(Re,1,{upgrade(e){e.objectStoreNames.contains(w)||e.createObjectStore(w)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(w,"readwrite");await s.objectStore(w).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(w).objectStore(w).get(e)}async remove(e){const r=(await this.dbPromise).transaction(w,"readwrite");await r.objectStore(w).delete(e),await r.done}};f(H,"BrowserIndexedDBStorageProvider");let L=H;async function he(I){const e=new v;return u.SetProvider(e),await e.Config(I),E.MJGlobal.Instance.RaiseEvent({event:E.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(he,"setupGraphQLClient");const X=class X{};f(X,"SyncRolesAndUsersResult");let F=X;const Z=class Z{};f(Z,"RoleInput");let x=Z;const Y=class Y{};f(Y,"UserInput");let T=Y;const ee=class ee{};f(ee,"RolesAndUsersInput");let U=ee;var ge=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(ge||{});const te=class te{};f(te,"ActionItemInput");let G=te;const re=class re{constructor(){this.Results=[]}};f(re,"SyncDataResult");let Q=re;const se=class se{};f(se,"ActionItemOutput");let b=se;const ae=class ae{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new y.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
350
+ `,s=new ye.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates.message),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}},f(h,"_GraphQLDataProvider"),h);ge.MJ_CORE_SCHEMA="__mj";let pe=ge;const W=class W{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(W,"BrowserStorageProviderBase");let L=W;const De="MJ_Metadata",P="Metadata_KVPairs",H=class H extends L{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}};f(H,"BrowserIndexedDBStorageProvider");let V=H;async function Ie(I){const e=new pe;return u.SetProvider(e),await e.Config(I),E.MJGlobal.Instance.RaiseEvent({event:E.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(Ie,"setupGraphQLClient");const X=class X{};f(X,"SyncRolesAndUsersResult");let Q=X;const Z=class Z{};f(Z,"RoleInput");let T=Z;const Y=class Y{};f(Y,"UserInput");let G=Y;const ee=class ee{};f(ee,"RolesAndUsersInput");let F=ee;var fe=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(fe||{});const te=class te{};f(te,"ActionItemInput");let x=te;const re=class re{constructor(){this.Results=[]}};f(re,"SyncDataResult");let U=re;const se=class se{};f(se,"ActionItemOutput");let b=se;const ae=class ae{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new y.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
349
351
  GetData(input: $input) {
350
352
  Success
351
353
  ErrorMessages
@@ -721,7 +723,7 @@
721
723
  ResultData
722
724
  }
723
725
  }
724
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(le,"GraphQLActionClient");let k=le;const ce=class ce{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
726
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(le,"GraphQLActionClient");let B=le;const ce=class ce{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
725
727
  query GetRegistryComponent(
726
728
  $registryName: String!,
727
729
  $namespace: String!,
@@ -805,5 +807,5 @@
805
807
  error
806
808
  }
807
809
  }
808
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(ce,"GraphQLComponentRegistryClient");let B=ce;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return y.gql}}),exports.ActionItemInput=G,exports.ActionItemOutput=b,exports.FieldMapper=P,exports.GetDataOutput=q,exports.GraphQLAIClient=N,exports.GraphQLActionClient=k,exports.GraphQLComponentRegistryClient=B,exports.GraphQLDataProvider=v,exports.GraphQLProviderConfigData=C,exports.GraphQLSystemUserClient=M,exports.GraphQLTransactionGroup=$,exports.RoleInput=x,exports.RolesAndUsersInput=U,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=_,exports.SimpleRemoteEntityOutput=A,exports.SyncDataAction=ge,exports.SyncDataResult=Q,exports.SyncRolesAndUsersResult=F,exports.UserInput=T,exports.setupGraphQLClient=he;
810
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(ce,"GraphQLComponentRegistryClient");let k=ce;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return y.gql}}),exports.ActionItemInput=x,exports.ActionItemOutput=b,exports.FieldMapper=$,exports.GetDataOutput=q,exports.GraphQLAIClient=v,exports.GraphQLActionClient=B,exports.GraphQLComponentRegistryClient=k,exports.GraphQLDataProvider=pe,exports.GraphQLProviderConfigData=C,exports.GraphQLSystemUserClient=M,exports.GraphQLTransactionGroup=N,exports.RoleInput=T,exports.RolesAndUsersInput=F,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=_,exports.SimpleRemoteEntityOutput=A,exports.SyncDataAction=fe,exports.SyncDataResult=U,exports.SyncRolesAndUsersResult=Q,exports.UserInput=G,exports.setupGraphQLClient=Ie;
809
811
  //# sourceMappingURL=index.cjs.map