@memberjunction/graphql-dataprovider 5.9.0 → 5.10.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 V=Object.defineProperty;var g=(h,e)=>V(h,"name",{value:e,configurable:!0});var d=require("graphql-request"),u=require("@memberjunction/core"),v=require("@memberjunction/global"),N=require("@memberjunction/core-entities"),b=require("rxjs"),G=require("graphql-ws"),q=require("uuid"),_=require("@tempfix/idb");class w{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const s=this.MapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(w.DB_PREFIX)?w.GQL_PREFIX+e.substring(w.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(w.GQL_PREFIX)?w.DB_PREFIX+e.substring(w.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const s=this.ReverseMapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}}class x extends u.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=d.gql`
1
+ "use strict";var V=Object.defineProperty;var g=(S,e)=>V(S,"name",{value:e,configurable:!0});var d=require("graphql-request"),u=require("@memberjunction/core"),w=require("@memberjunction/global"),N=require("@memberjunction/core-entities"),b=require("rxjs"),G=require("graphql-ws"),q=require("uuid"),_=require("@tempfix/idb");class v{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const s=this.MapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(v.DB_PREFIX)?v.GQL_PREFIX+e.substring(v.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(v.GQL_PREFIX)?v.DB_PREFIX+e.substring(v.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const s=this.ReverseMapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}}class x extends u.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=d.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const s={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},r=await this._provider.ExecuteGQL(e,s);if(r&&r.ExecuteTransactionGroup){const n=r.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],c=v.SafeJSONParse(a),l=this.PendingTransactions[i];o.push(new u.TransactionResult(l,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class ${static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let s,r;try{const{promise:n,resolve:o,reject:i}=$.createCompletionPromise();r=$.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),s=$.subscribeToPubSub(e,o,r);const a=await $.executeMutation(e);if(!e.validateAck(a)){r&&clearTimeout(r);const c=a?.errorMessage??"Server rejected the request";return u.LogError(`[FireAndForget:${t}] Server rejected: ${c}`),e.createErrorResult(c)}return u.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){r&&clearTimeout(r);const o=n;throw u.LogError(`[FireAndForget:${t}] Error: ${o.message}`),n}finally{r&&clearTimeout(r),s&&s.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,s){const r=t??O,n=s??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},r)}static subscribeToPubSub(e,t,s){const r=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe(o=>{try{const i=JSON.parse(o);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(s),u.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class L{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=d.gql`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const s={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},r=await this._provider.ExecuteGQL(e,s);if(r&&r.ExecuteTransactionGroup){const n=r.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],c=w.SafeJSONParse(a),l=this.PendingTransactions[i];o.push(new u.TransactionResult(l,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class ${static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let s,r;try{const{promise:n,resolve:o,reject:i}=$.createCompletionPromise();r=$.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),s=$.subscribeToPubSub(e,o,r);const a=await $.executeMutation(e);if(!e.validateAck(a)){r&&clearTimeout(r);const c=a?.errorMessage??"Server rejected the request";return u.LogError(`[FireAndForget:${t}] Server rejected: ${c}`),e.createErrorResult(c)}return u.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){r&&clearTimeout(r);const o=n;throw u.LogError(`[FireAndForget:${t}] Error: ${o.message}`),n}finally{r&&clearTimeout(r),s&&s.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,s){const r=t??O,n=s??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},r)}static subscribeToPubSub(e,t,s){const r=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe(o=>{try{const i=JSON.parse(o);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(s),u.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class L{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=d.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -106,7 +106,7 @@
106
106
  result
107
107
  }
108
108
  }
109
- `}prepareAgentVariables(e,t,s){const r={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(r.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(r.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(r.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(r.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(r.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(r.conversationDetailId=e.conversationDetailId,r.createArtifacts=!0,r.createNotification=!0),t!==void 0&&(r.sourceArtifactId=t),s!==void 0&&(r.sourceArtifactVersionId=s),r}processAgentResult(e){return v.SafeJSONParse(e)}handleAgentError(e){const s=e?.message||String(e);u.LogError(`Error running AI agent: ${s}`);const r=s.includes("Failed to fetch")||s.includes("NetworkError"),n=s.includes("timed out")||s.includes("timeout");let o;return r?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=s,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isConversationDetailCompletionEvent(r,e.conversationDetailId),"isCompletionEvent"),extractResult:g(r=>this.extractAgentResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardConversationDetailProgress(r,e.onProgress):void 0,createErrorResult:g(r=>this.createAgentErrorResult(r),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return d.gql`
109
+ `}prepareAgentVariables(e,t,s){const r={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(r.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(r.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(r.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(r.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(r.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(r.conversationDetailId=e.conversationDetailId,r.createArtifacts=!0,r.createNotification=!0),t!==void 0&&(r.sourceArtifactId=t),s!==void 0&&(r.sourceArtifactVersionId=s),r}processAgentResult(e){return w.SafeJSONParse(e)}handleAgentError(e){const s=e?.message||String(e);u.LogError(`Error running AI agent: ${s}`);const r=s.includes("Failed to fetch")||s.includes("NetworkError"),n=s.includes("timed out")||s.includes("timeout");let o;return r?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=s,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isConversationDetailCompletionEvent(r,e.conversationDetailId),"isCompletionEvent"),extractResult:g(r=>this.extractAgentResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardConversationDetailProgress(r,e.onProgress):void 0,createErrorResult:g(r=>this.createAgentErrorResult(r),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return d.gql`
110
110
  mutation RunAIAgentFromConversationDetail(
111
111
  $conversationDetailId: String!,
112
112
  $agentId: String!,
@@ -145,7 +145,7 @@
145
145
  result
146
146
  }
147
147
  }
148
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const s=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&s?.type==="complete"&&s?.conversationDetailId===t}extractAgentResult(e){const t=e.data,s=t.result;return s?v.SafeJSONParse(s):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data,r=s?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:{...r,agentRun:s?.agentRun,agentRunId:s?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=d.gql`
148
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const s=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&s?.type==="complete"&&s?.conversationDetailId===t}extractAgentResult(e){const t=e.data,s=t.result;return s?w.SafeJSONParse(s):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data,r=s?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:{...r,agentRun:s?.agentRun,agentRunId:s?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=d.gql`
149
149
  mutation ExecuteSimplePrompt(
150
150
  $systemPrompt: String!,
151
151
  $messages: String,
@@ -183,7 +183,7 @@
183
183
  error
184
184
  }
185
185
  }
186
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,r);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const s=t;return u.LogError(`Error generating embeddings: ${s}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:s.message||"Unknown error occurred"}}}}const P="default";class T{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||P;let s=this._storage.get(t);return s||(s=new Map,this._storage.set(t,s)),s}async GetItem(e,t){return this.getCategoryMap(t||P).get(e)??null}async SetItem(e,t,s){this.getCategoryMap(s||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class Q extends T{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const s=t||P;return this.isKnownCategory(s)?e:`[${s}]:${e}`}async SetItem(e,t,s){try{const r=await this.dbPromise,n=this.getStoreName(s),o=this.getStoreKey(e,s),i=r.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.SetItem(e,t,s)}}async GetItem(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t);return await s.transaction(r).objectStore(r).get(n)??null}catch(s){return u.LogErrorEx({error:s,message:s?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t),o=s.transaction(r,"readwrite");await o.objectStore(r).delete(n),await o.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,s=e||P,r=this.getStoreName(e);if(this.isKnownCategory(s)){const n=t.transaction(r,"readwrite");await n.objectStore(r).clear(),await n.done}else{const n=`[${s}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,s=e||P,r=this.getStoreName(e),i=await t.transaction(r,"readonly").objectStore(r).getAllKeys();if(this.isKnownCategory(s))return i.map(c=>String(c));const a=`[${s}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends u.ProviderConfigDataBase{static{g(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,s,r,n,o,i,a,c){super({Token:e,URL:t,WSURL:s,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:r},n,o,i)}}class f extends u.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
186
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,r);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const s=t;return u.LogError(`Error generating embeddings: ${s}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:s.message||"Unknown error occurred"}}}}const P="default";class T{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||P;let s=this._storage.get(t);return s||(s=new Map,this._storage.set(t,s)),s}async GetItem(e,t){return this.getCategoryMap(t||P).get(e)??null}async SetItem(e,t,s){this.getCategoryMap(s||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class U extends T{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const s=t||P;return this.isKnownCategory(s)?e:`[${s}]:${e}`}async SetItem(e,t,s){try{const r=await this.dbPromise,n=this.getStoreName(s),o=this.getStoreKey(e,s),i=r.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.SetItem(e,t,s)}}async GetItem(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t);return await s.transaction(r).objectStore(r).get(n)??null}catch(s){return u.LogErrorEx({error:s,message:s?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t),o=s.transaction(r,"readwrite");await o.objectStore(r).delete(n),await o.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,s=e||P,r=this.getStoreName(e);if(this.isKnownCategory(s)){const n=t.transaction(r,"readwrite");await n.objectStore(r).clear(),await n.done}else{const n=`[${s}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,s=e||P,r=this.getStoreName(e),i=await t.transaction(r,"readonly").objectStore(r).getAllKeys();if(this.isKnownCategory(s))return i.map(c=>String(c));const a=`[${s}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends u.ProviderConfigDataBase{static{g(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,s,r,n,o,i,a,c){super({Token:e,URL:t,WSURL:s,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:r},n,o,i)}}class h extends u.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
187
187
  ${this.userInfoString()}
188
188
  MJUserRoles_UserIDArray {
189
189
  ${this.userRoleInfoString()}
@@ -191,7 +191,8 @@
191
191
  }
192
192
  `,this._currentUserQuery=d.gql`query CurrentUserAndRoles {
193
193
  ${this._innerCurrentUserQueryString}
194
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null,f._instance||(f._instance=this)}static get Instance(){return f._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const s=this.LocalStoragePrefix+"sessionId";await t.SetItem(s,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,s,r){try{return this._configData=e,s?(this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(f.Instance._configData=e,f.Instance._sessionId===void 0&&(f.Instance._sessionId=await this.GetPreferredUUID(r)),f.Instance._client||(f.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,f.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),s=t.MJUserRoles_UserIDArray.map(r=>this.ConvertBackToMJFields(r));return t.MJUserRoles_UserIDArray=s,new u.UserInfo(this,{...t,UserRoles:s})}}async RunReport(e,t){const s=d.gql`
194
+ CurrentUserTenantContext
195
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const s=this.LocalStoragePrefix+"sessionId";await t.SetItem(s,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,s,r){try{return this._configData=e,s?(this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(r)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.set(e,t),h.Instance._client&&h.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.delete(e),h.Instance._client&&h.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),s=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=s;const r=new u.UserInfo(this,{...t,UserRoles:s});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(r.TenantContext=e.CurrentUserTenantContext),r}}async RunReport(e,t){const s=d.gql`
195
196
  query GetReportDataQuery ($ReportID: String!) {
196
197
  GetReportData(ReportID: $ReportID) {
197
198
  Success
@@ -249,7 +250,7 @@
249
250
  }
250
251
  }
251
252
  }
252
- `,o=(await this.ExecuteGQL(r,{input:s}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const c=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:c,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(s){return u.LogError(`Error in RunQueriesWithCacheCheck: ${s}`),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async InternalRunView(e,t){try{let s="",r="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:p,v:I}=await this.getEntityNameAndUserView(e,t);i=I,o=p}const a=this.Entities.find(p=>p.Name===o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const l=u.getGraphQLTypeNameBase(a);e.ViewID?(s=`Run${l}ViewByID`,r="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(s=`Run${l}ViewByName`,r="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,s=`Run${l}DynamicView`,r="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const S=this.getViewRunTimeFieldList(a,i,e,c),E=e.Aggregates&&e.Aggregates.length>0?`
253
+ `,o=(await this.ExecuteGQL(r,{input:s}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const c=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:c,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(s){return u.LogError(`Error in RunQueriesWithCacheCheck: ${s}`),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async InternalRunView(e,t){try{let s="",r="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:p,v:I}=await this.getEntityNameAndUserView(e,t);i=I,o=p}const a=this.Entities.find(p=>p.Name===o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const l=u.getGraphQLTypeNameBase(a);e.ViewID?(s=`Run${l}ViewByID`,r="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(s=`Run${l}ViewByName`,r="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,s=`Run${l}DynamicView`,r="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const f=this.getViewRunTimeFieldList(a,i,e,c),E=e.Aggregates&&e.Aggregates.length>0?`
253
254
  AggregateResults {
254
255
  alias
255
256
  expression
@@ -260,7 +261,7 @@
260
261
  query RunViewQuery ($input: ${r}!) {
261
262
  ${s}(input: $input) {
262
263
  Results {
263
- ${S.join(`
264
+ ${f.join(`
264
265
  `)}
265
266
  }
266
267
  UserViewRunID
@@ -270,7 +271,7 @@
270
271
  Success
271
272
  ErrorMessage${E}
272
273
  }
273
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:s,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[s]){const p=m[s].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[s].AggregateExecutionTime});const I=m[s].Results;if(I&&I.length>0){const C=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),C.forEach(A=>{D[A.Name]=D[A.CodeName]})})}return m[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw u.LogError(s),s}}async InternalRunViews(e,t){try{let s=[],r=[],n=[];for(const l of e){let S="",E="";const y={};let m=null,p=null;if(l.ViewEntity)p=l.ViewEntity,m=p.Get("Entity");else{const{entityName:D,v:A}=await this.getEntityNameAndUserView(l,t);p=A,m=D}const I=this.Entities.find(D=>D.Name===m);if(!I)throw new Error(`Entity ${m} not found in metadata`);r.push(I);let R=!1;const C=u.getGraphQLTypeNameBase(I);l.ViewID?(S=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=l.ViewID):l.ViewName?(S=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=l.ViewName):(R=!0,S=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=l.EntityName),y.ExtraFilter=l.ExtraFilter||"",y.OrderBy=l.OrderBy||"",y.UserSearchString=l.UserSearchString||"",y.Fields=l.Fields,y.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(y.MaxRows=l.MaxRows),l.StartRow!==void 0&&(y.StartRow=l.StartRow),y.ForceAuditLog=l.ForceAuditLog||!1,y.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(y.AuditLogDescription=l.AuditLogDescription),R||(y.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=l.OverrideExcludeFilter||"",y.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(y.Aggregates=l.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),s.push(y),n.push(...this.getViewRunTimeFieldList(I,p,l,R))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
274
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:s,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[s]){const p=m[s].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[s].AggregateExecutionTime});const I=m[s].Results;if(I&&I.length>0){const C=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),C.forEach(A=>{D[A.Name]=D[A.CodeName]})})}return m[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw u.LogError(s),s}}async InternalRunViews(e,t){try{let s=[],r=[],n=[];for(const l of e){let f="",E="";const y={};let m=null,p=null;if(l.ViewEntity)p=l.ViewEntity,m=p.Get("Entity");else{const{entityName:D,v:A}=await this.getEntityNameAndUserView(l,t);p=A,m=D}const I=this.Entities.find(D=>D.Name===m);if(!I)throw new Error(`Entity ${m} not found in metadata`);r.push(I);let R=!1;const C=u.getGraphQLTypeNameBase(I);l.ViewID?(f=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=l.ViewID):l.ViewName?(f=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=l.ViewName):(R=!0,f=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=l.EntityName),y.ExtraFilter=l.ExtraFilter||"",y.OrderBy=l.OrderBy||"",y.UserSearchString=l.UserSearchString||"",y.Fields=l.Fields,y.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(y.MaxRows=l.MaxRows),l.StartRow!==void 0&&(y.StartRow=l.StartRow),y.ForceAuditLog=l.ForceAuditLog||!1,y.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(y.AuditLogDescription=l.AuditLogDescription),R||(y.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=l.OverrideExcludeFilter||"",y.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(y.Aggregates=l.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),s.push(y),n.push(...this.getViewRunTimeFieldList(I,p,l,R))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
274
275
  AggregateResults {
275
276
  alias
276
277
  expression
@@ -295,7 +296,7 @@
295
296
  Success
296
297
  ErrorMessage${i}
297
298
  }
298
- }`,c=await this.ExecuteGQL(a,{input:s});if(c&&c.RunViews){const l=c.RunViews;for(const[S,E]of l.entries())E.Results=E.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return l}return null}catch(s){throw u.LogError(s),s}}async RunViewsWithCacheCheck(e,t){try{const s=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),r=d.gql`
299
+ }`,c=await this.ExecuteGQL(a,{input:s});if(c&&c.RunViews){const l=c.RunViews;for(const[f,E]of l.entries())E.Results=E.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return l}return null}catch(s){throw u.LogError(s),s}}async RunViewsWithCacheCheck(e,t){try{const s=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),r=d.gql`
299
300
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
300
301
  RunViewsWithCacheCheck(input: $input) {
301
302
  success
@@ -328,7 +329,7 @@
328
329
  }
329
330
  }
330
331
  }
331
- `,o=(await this.ExecuteGQL(r,{input:s}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,c)=>{const l=e[c];if(a.status==="differential"&&a.differentialData){const S=a.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:S,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const S=a.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:S,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(s){return u.LogError(s),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async getEntityNameAndUserView(e,t){let s,r;if(e.EntityName)s=e.EntityName;else if(e.ViewID)r=await N.ViewInfo.GetViewEntity(e.ViewID,t),s=r.Entity;else if(e.ViewName)r=await N.ViewInfo.GetViewEntityByName(e.ViewName,t),s=r.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:r}}getViewRunTimeFieldList(e,t,s,r){const n=[],o=new w;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);s.Fields.forEach(i=>{n.push(o.MapFieldName(i))})}else if(r)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(o.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const s={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},r=await this.RunView(s);return r?r.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(s){throw u.LogError(s),s}}async GetRecordDependencies(e,t){try{const s=d.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
332
+ `,o=(await this.ExecuteGQL(r,{input:s}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,c)=>{const l=e[c];if(a.status==="differential"&&a.differentialData){const f=a.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const f=a.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:f,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(s){return u.LogError(s),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async getEntityNameAndUserView(e,t){let s,r;if(e.EntityName)s=e.EntityName;else if(e.ViewID)r=await N.ViewInfo.GetViewEntity(e.ViewID,t),s=r.Entity;else if(e.ViewName)r=await N.ViewInfo.GetViewEntityByName(e.ViewName,t),s=r.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:r}}getViewRunTimeFieldList(e,t,s,r){const n=[],o=new v;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);s.Fields.forEach(i=>{n.push(o.MapFieldName(i))})}else if(r)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(o.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const s={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},r=await this.RunView(s);return r?r.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(s){throw u.LogError(s),s}}async GetRecordDependencies(e,t){try{const s=d.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
332
333
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
333
334
  EntityName
334
335
  RelatedEntityName
@@ -379,32 +380,32 @@
379
380
  Message
380
381
  }
381
382
  }
382
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,s){if(s?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const r=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";r.StartedAt=new Date,r.Type=e.IsSaved?"update":"create",r.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(r);const i=u.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),l=new w,S=` ${a}(input: $input) {
383
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,s){if(s?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const r=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";r.StartedAt=new Date,r.Type=e.IsSaved?"update":"create",r.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(r);const i=u.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),l=new v,f=` ${a}(input: $input) {
383
384
  ${e.Fields.map(y=>l.MapFieldName(y.CodeName)).join(`
384
385
  `)}
385
386
  }`,E=d.gql`mutation ${o}${i} ($input: ${a}Input!) {
386
- ${S}
387
+ ${f}
387
388
  }
388
- `;for(let y=0;y<c.length;y++){const m=c[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:p=p.getTime();break;case u.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case u.EntityFieldTSType.Number:if(typeof p!="number"){const I=Number(p);isNaN(I)||(p=I)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===u.EntityFieldTSType.Number||m.FieldType===u.EntityFieldTSType.Boolean?p=0:p=""),n.input[l.MapFieldName(m.CodeName)]=p}if(o.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:l.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,r.Type==="create"?"Create":"Update",S,n,{mutationName:a,mutationInputTypes:y},(m,p)=>{r.EndedAt=new Date,p&&m?(r.Success=!0,r.NewValues=this.ConvertBackToMJFields(m)):(r.Success=!1,r.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[a])return r.Success=!0,r.EndedAt=new Date,r.NewValues=this.ConvertBackToMJFields(y[a]),r.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return r.Success=!1,r.EndedAt=new Date,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,s=null,r){try{const n={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),I=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${m.CodeName}: $${m.CodeName}`,m.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const a=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),l=new w,S=d.gql`query Single${c}${a.length>0?"Full":""} (${i}) {
389
+ `;for(let y=0;y<c.length;y++){const m=c[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:p=p.getTime();break;case u.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case u.EntityFieldTSType.Number:if(typeof p!="number"){const I=Number(p);isNaN(I)||(p=I)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===u.EntityFieldTSType.Number||m.FieldType===u.EntityFieldTSType.Boolean?p=0:p=""),n.input[l.MapFieldName(m.CodeName)]=p}if(o.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:l.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,r.Type==="create"?"Create":"Update",f,n,{mutationName:a,mutationInputTypes:y},(m,p)=>{r.EndedAt=new Date,p&&m?(r.Success=!0,r.NewValues=this.ConvertBackToMJFields(m)):(r.Success=!1,r.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[a])return r.Success=!0,r.EndedAt=new Date,r.NewValues=this.ConvertBackToMJFields(y[a]),r.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return r.Success=!1,r.EndedAt=new Date,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,s=null,r){try{const n={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),I=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${m.CodeName}: $${m.CodeName}`,m.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const a=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),l=new v,f=d.gql`query Single${c}${a.length>0?"Full":""} (${i}) {
389
390
  ${c}(${o}) {
390
391
  ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
391
392
  `)}
392
393
  ${a}
393
394
  }
394
395
  }
395
- `,E=await this.ExecuteGQL(S,n);return E&&E[c]?this.ConvertBackToMJFields(E[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new w().ReverseMapFields(e),e}getRelatedEntityString(e,t){let s="";for(let r=0;r<e.RelatedEntities.length;r++)if(t.indexOf(e.RelatedEntities[r].RelatedEntity)>=0){const n=e.RelatedEntities[r],o=this.Entities.find(a=>v.UUIDsEqual(a.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
396
+ `,E=await this.ExecuteGQL(f,n);return E&&E[c]?this.ConvertBackToMJFields(E[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let s="";for(let r=0;r<e.RelatedEntities.length;r++)if(t.indexOf(e.RelatedEntities[r].RelatedEntity)>=0){const n=e.RelatedEntities[r],o=this.Entities.find(a=>w.UUIDsEqual(a.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
396
397
  ${i} {
397
398
  ${o.Fields.map(a=>a.CodeName).join(`
398
399
  `)}
399
400
  }
400
401
  `}return s}async Delete(e,t,s){const r=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),r.StartedAt=new Date,r.Type="delete",r.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.ResultHistory.push(r);const n={},o=[];let i="",a="",c="";for(let m of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(I=>I.Name.trim().toLowerCase()===m.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,o.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,a.length>0&&(a+=", "),a+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
401
- `),c+=`${p.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const S="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),E=d.gql`${S}(${i}, options___: $options___) {
402
+ `),c+=`${p.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),E=d.gql`${f}(${i}, options___: $options___) {
402
403
  ${c}
403
404
  }
404
- `,y=d.gql`mutation ${S} (${a}, $options___: DeleteOptionsInput!) {
405
+ `,y=d.gql`mutation ${f} (${a}, $options___: DeleteOptionsInput!) {
405
406
  ${E}
406
407
  }
407
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",E,n,{mutationName:S,mutationInputTypes:o},(m,p)=>{if(r.EndedAt=new Date,p&&m){let I=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==m[R.FieldName]&&(I=!1);I?r.Success=!0:(r.Success=!1,r.Message="Transaction failed to commit")}else r.Success=!1,r.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[S]){const p=m[S];for(let I of e.PrimaryKey.KeyValuePairs){let R=p[I.FieldName],C=I.Value;if(typeof C=="number"&&(C=C.toString()),typeof R=="number"&&(R=R.toString()),C!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${C}, Returned: ${R}`)}return r.Success=!0,r.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return r.EndedAt=new Date,r.Success=!1,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const s=d.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
408
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",E,n,{mutationName:f,mutationInputTypes:o},(m,p)=>{if(r.EndedAt=new Date,p&&m){let I=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==m[R.FieldName]&&(I=!1);I?r.Success=!0:(r.Success=!1,r.Message="Transaction failed to commit")}else r.Success=!1,r.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[f]){const p=m[f];for(let I of e.PrimaryKey.KeyValuePairs){let R=p[I.FieldName],C=I.Value;if(typeof C=="number"&&(C=C.toString()),typeof R=="number"&&(R=R.toString()),C!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${C}, Returned: ${R}`)}return r.Success=!0,r.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return r.EndedAt=new Date,r.Success=!1,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const s=d.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
408
409
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
409
410
  DatasetID
410
411
  DatasetName
@@ -462,16 +463,16 @@
462
463
  ErrorMessage
463
464
  Result
464
465
  }
465
- }`,s=await this.ExecuteGQL(t,{DataContextItemID:e});if(s&&s.GetDataContextItemData){if(s.GetDataContextItemData.Success)return JSON.parse(s.GetDataContextItemData.Result);throw new Error(s.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,s=!0){return f.Instance.ExecuteGQL(e,t,s)}async ExecuteGQL(e,t,s=!0){try{return await this._client.request(e,t)}catch(r){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!r?.response,hasErrors:!!r?.response?.errors,errorCount:r?.response?.errors?.length,firstError:r?.response?.errors?.[0],errorCode:r?.response?.errors?.[0]?.extensions?.code,errorMessage:r?.response?.errors?.[0]?.message,fullError:r}),r&&r.response&&r.response.errors?.length>0)if(r.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),r}else throw r;else throw u.LogError(r),r}}async RefreshToken(){const e=f.Instance&&f.Instance._configData===this._configData;if(e&&f.Instance._refreshPromise)return f.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(f.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&f.Instance&&(f.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,f.Instance&&f.Instance._configData===this._configData&&(f.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return f.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,s,r,n){const o={"x-session-id":s};return t&&(o.authorization="Bearer "+t),r&&(o["x-mj-api-key"]=r),n&&(o["x-api-key"]=n),new d.GraphQLClient(e,{headers:o})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const s=Object.keys(e);for(const r of s)r.startsWith("__mj_")?t+=r.replace("__mj_","_mj__")+`
466
+ }`,s=await this.ExecuteGQL(t,{DataContextItemID:e});if(s&&s.GetDataContextItemData){if(s.GetDataContextItemData.Success)return JSON.parse(s.GetDataContextItemData.Result);throw new Error(s.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,s=!0){return h.Instance.ExecuteGQL(e,t,s)}async ExecuteGQL(e,t,s=!0){try{return await this._client.request(e,t)}catch(r){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!r?.response,hasErrors:!!r?.response?.errors,errorCount:r?.response?.errors?.length,firstError:r?.response?.errors?.[0],errorCode:r?.response?.errors?.[0]?.extensions?.code,errorMessage:r?.response?.errors?.[0]?.message,fullError:r}),r&&r.response&&r.response.errors?.length>0)if(r.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),r}else throw r;else throw u.LogError(r),r}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,s,r,n){const o={"x-session-id":s};t&&(o.authorization="Bearer "+t),r&&(o["x-mj-api-key"]=r),n&&(o["x-api-key"]=n);const i=new d.GraphQLClient(e,{headers:o});for(const[a,c]of this._dynamicHeaders)i.setHeader(a,c);return i}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const s=Object.keys(e);for(const r of s)r.startsWith("__mj_")?t+=r.replace("__mj_","_mj__")+`
466
467
  `:r.startsWith("_")||(t+=r+`
467
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(s){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,s)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,s=Array.from(this._pushStatusSubjects.entries()),r=[];s.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),r.push(n))}),r.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new b.Observable(s=>{const r=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=r.subscribe({query:e,variables:t},{next:g(o=>{s.next(o.data)},"next"),error:g(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),s.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),s.error(c)}}else s.error(o)},"error"),complete:g(()=>{s.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),s=this._pushStatusSubjects.get(e);if(s)return s.lastRequestedAt=t,new b.Observable(a=>{s.activeSubscribers++;const c=s.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,c.unsubscribe()}});const r=d.gql`subscription StatusUpdates($sessionId: String!) {
468
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new U:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(s){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,s)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,s=Array.from(this._pushStatusSubjects.entries()),r=[];s.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),r.push(n))}),r.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new b.Observable(s=>{const r=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=r.subscribe({query:e,variables:t},{next:g(o=>{s.next(o.data)},"next"),error:g(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),s.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),s.error(c)}}else s.error(o)},"error"),complete:g(()=>{s.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),s=this._pushStatusSubjects.get(e);if(s)return s.lastRequestedAt=t,new b.Observable(a=>{s.activeSubscribers++;const c=s.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,c.unsubscribe()}});const r=d.gql`subscription StatusUpdates($sessionId: String!) {
468
469
  statusUpdates(sessionId: $sessionId) {
469
470
  date
470
471
  message
471
472
  sessionId
472
473
  }
473
474
  }
474
- `,n=new b.Subject,o=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(a=>{const c=o.subscribe({query:r,variables:{sessionId:e}},{next:g(l=>{const S=this._pushStatusSubjects.get(e);S&&(S.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:g(async l=>{const S=l;if(S?.extensions?.code==="JWT_EXPIRED"||S?.message?.includes("token has expired")||S?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(l)},"error"),complete:g(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:g(a=>n.next(a),"next"),error:g(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(a=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const l=n.subscribe(a);return()=>{const S=this._pushStatusSubjects.get(e);S&&S.activeSubscribers>0&&S.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=d.gql`subscription CacheInvalidation {
475
+ `,n=new b.Subject,o=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(a=>{const c=o.subscribe({query:r,variables:{sessionId:e}},{next:g(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:g(async l=>{const f=l;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(l)},"error"),complete:g(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:g(a=>n.next(a),"next"),error:g(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(a=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const l=n.subscribe(a);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=d.gql`subscription CacheInvalidation {
475
476
  cacheInvalidation {
476
477
  EntityName
477
478
  PrimaryKeyValues
@@ -481,7 +482,7 @@
481
482
  OriginSessionID
482
483
  RecordData
483
484
  }
484
- }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(s=>{const r=s?.cacheInvalidation;if(!r)return;if(r.OriginSessionID&&r.OriginSessionID===this.sessionId){console.log(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${r.EntityName}" (action: ${r.Action})`);return}console.log(`[GraphQLDataProvider] Cache invalidation received: ${r.Action} for "${r.EntityName}" from server ${r.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:r.EntityName,baseEntity:null,payload:{primaryKeyValues:r.PrimaryKeyValues,action:r.Action,sourceServerId:r.SourceServerID,timestamp:r.Timestamp,recordData:r.RecordData}};v.MJGlobal.Instance.RaiseEvent({event:v.MJEventType.ComponentEvent,eventCode:u.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(s=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",s),this._cacheInvalidationSubscription=null},"error"),complete:g(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,s){if(!e.IsParentType)return null;const r=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
485
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(s=>{const r=s?.cacheInvalidation;if(!r)return;if(r.OriginSessionID&&r.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${r.EntityName}" (action: ${r.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${r.Action} for "${r.EntityName}" from server ${r.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:r.EntityName,baseEntity:null,payload:{primaryKeyValues:r.PrimaryKeyValues,action:r.Action,sourceServerId:r.SourceServerID,timestamp:r.Timestamp,recordData:r.RecordData}};w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.ComponentEvent,eventCode:u.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(s=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",s),this._cacheInvalidationSubscription=null},"error"),complete:g(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,s){if(!e.IsParentType)return null;const r=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
485
486
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
486
487
  Success
487
488
  ChildEntityName
@@ -493,14 +494,14 @@
493
494
  ChildEntityNames
494
495
  ErrorMessage
495
496
  }
496
- }`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new f;return u.SetProvider(e),await e.Config(h),await u.StartupManager.Instance.Startup(),v.MJGlobal.Instance.RaiseEvent({event:v.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class z{static{g(this,"UserInput")}}class H{static{g(this,"RolesAndUsersInput")}}var U=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(U||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,s,r){const n={"x-session-id":s};this._sessionId=s,t&&(n.authorization="Bearer "+t),r&&(n["x-mj-api-key"]=r),this._client=new d.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return u.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request(`query GetData($input: GetDataInputType!) {
497
+ }`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(S){const e=new h;return u.SetProvider(e),await e.Config(S),await u.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class H{static{g(this,"UserInput")}}class z{static{g(this,"RolesAndUsersInput")}}var Q=(S=>(S.Create="Create",S.Update="Update",S.CreateOrUpdate="CreateOrUpdate",S.Delete="Delete",S.DeleteWithFilter="DeleteWithFilter",S))(Q||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,s,r){const n={"x-session-id":s};this._sessionId=s,t&&(n.authorization="Bearer "+t),r&&(n["x-mj-api-key"]=r),this._client=new d.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return u.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request(`query GetData($input: GetDataInputType!) {
497
498
  GetData(input: $input) {
498
499
  Success
499
500
  ErrorMessages
500
501
  Queries
501
502
  Results
502
503
  }
503
- }`,{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(n=>n?v.SafeJSONParse(n):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(s){let r=s instanceof Error?s.message:String(s);const n=r.match(/Error: ([^:]+)\./);if(n&&(r=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${s}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
504
+ }`,{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(n=>n?w.SafeJSONParse(n):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(s){let r=s instanceof Error?s.message:String(s);const n=r.match(/Error: ([^:]+)\./);if(n&&(r=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${s}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
504
505
  GetAllEntities {
505
506
  Success
506
507
  ErrorMessage
@@ -631,7 +632,7 @@
631
632
  ErrorMessage
632
633
  AppliedParameters
633
634
  }
634
- }`,s={QueryID:e.QueryID};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataSystemUser?{...r.GetQueryDataSystemUser,Results:r.GetQueryDataSystemUser.Results?v.SafeJSONParse(r.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
635
+ }`,s={QueryID:e.QueryID};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataSystemUser?{...r.GetQueryDataSystemUser,Results:r.GetQueryDataSystemUser.Results?w.SafeJSONParse(r.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
635
636
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
636
637
  QueryID
637
638
  QueryName
@@ -643,7 +644,7 @@
643
644
  ErrorMessage
644
645
  AppliedParameters
645
646
  }
646
- }`,s={QueryName:e.QueryName};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataByNameSystemUser?{...r.GetQueryDataByNameSystemUser,Results:r.GetQueryDataByNameSystemUser.Results?v.SafeJSONParse(r.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const s=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
647
+ }`,s={QueryName:e.QueryName};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataByNameSystemUser?{...r.GetQueryDataByNameSystemUser,Results:r.GetQueryDataByNameSystemUser.Results?w.SafeJSONParse(r.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const s=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
647
648
  CreateQuerySystemUser(input: $input) {
648
649
  Success
649
650
  ErrorMessage
@@ -846,7 +847,7 @@
846
847
  result
847
848
  }
848
849
  }
849
- `,s=this.prepareAgentVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIAgentSystemUser?this.processAgentResult(r.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,s,r;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(s=JSON.parse(e.validationResult))}catch{s=e.validationResult}try{e.chatResult&&(r=JSON.parse(e.chatResult))}catch{r=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:s,chatResult:r}}processAgentResult(e){return v.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=d.gql`
850
+ `,s=this.prepareAgentVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIAgentSystemUser?this.processAgentResult(r.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,s,r;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(s=JSON.parse(e.validationResult))}catch{s=e.validationResult}try{e.chatResult&&(r=JSON.parse(e.chatResult))}catch{r=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:s,chatResult:r}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=d.gql`
850
851
  query ExecuteSimplePromptSystemUser(
851
852
  $systemPrompt: String!,
852
853
  $messages: String,
@@ -975,7 +976,7 @@
975
976
  result
976
977
  }
977
978
  }
978
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:s,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0,r=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:s,selectedTestIds:r,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&s?.type==="complete"&&s?.testId===t}isSuiteCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&s?.type==="complete"&&s?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const s=e.message;return u.LogError(`${t} failed: ${s}`),{success:!1,errorMessage:s.includes("Failed to fetch")||s.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":s,result:null}}}class ue{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=d.gql`
979
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:s,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0,r=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:s,selectedTestIds:r,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&s?.type==="complete"&&s?.testId===t}isSuiteCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&s?.type==="complete"&&s?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?w.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?w.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const s=e.message;return u.LogError(`${t} failed: ${s}`),{success:!1,errorMessage:s.includes("Failed to fetch")||s.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":s,result:null}}}class ue{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=d.gql`
979
980
  query GetRegistryComponent(
980
981
  $registryName: String!,
981
982
  $namespace: String!,
@@ -1253,5 +1254,5 @@
1253
1254
  }
1254
1255
  }
1255
1256
  }
1256
- `,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,DefaultSchemaName:r.DefaultSchemaName,DefaultObjects:r.DefaultObjects??[]}}catch(t){const s=t;return u.LogError(`Error getting default config: ${s}`),{Success:!1,Message:`Error: ${s.message}`}}}handleError(e,t){const s=e;return u.LogError(`Error in integration discovery: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return d.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=Q,exports.BrowserStorageProviderBase=T,exports.FieldMapper=w,exports.FireAndForgetHelper=$,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=de,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=U,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1257
+ `,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,DefaultSchemaName:r.DefaultSchemaName,DefaultObjects:r.DefaultObjects??[]}}catch(t){const s=t;return u.LogError(`Error getting default config: ${s}`),{Success:!1,Message:`Error: ${s.message}`}}}handleError(e,t){const s=e;return u.LogError(`Error in integration discovery: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return d.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=U,exports.BrowserStorageProviderBase=T,exports.FieldMapper=v,exports.FireAndForgetHelper=$,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=h,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=de,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=z,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=Q,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=H,exports.setupGraphQLClient=j;
1257
1258
  //# sourceMappingURL=index.cjs.map