@memberjunction/react-runtime 5.2.0 → 5.3.1

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.
@@ -1,32 +1,32 @@
1
1
 
2
- > @memberjunction/react-runtime@5.2.0 build
2
+ > @memberjunction/react-runtime@5.3.1 build
3
3
  > npm run build:node && npm run build:umd
4
4
 
5
5
 
6
- > @memberjunction/react-runtime@5.2.0 build:node
6
+ > @memberjunction/react-runtime@5.3.1 build:node
7
7
  > tsc
8
8
 
9
9
 
10
- > @memberjunction/react-runtime@5.2.0 build:umd
10
+ > @memberjunction/react-runtime@5.3.1 build:umd
11
11
  > webpack --config webpack.umd.config.cjs
12
12
 
13
13
  [BABEL] Note: The code generator has deoptimised the styling of /home/runner/work/MJ/MJ/packages/MJCoreEntities/dist/generated/entity_subclasses.js as it exceeds the max of 500KB.
14
- asset runtime.umd.js 2.23 MiB [emitted] [minimized] [big] (name: main) 1 related asset
15
- asset 324.runtime.umd.js 114 KiB [emitted] [minimized]
14
+ asset runtime.umd.js 2.24 MiB [emitted] [minimized] [big] (name: main) 1 related asset
15
+ asset 324.runtime.umd.js 115 KiB [emitted] [minimized]
16
16
  asset 490.runtime.umd.js 61.7 KiB [emitted] [minimized] (id hint: vendors)
17
- orphan modules 5.46 MiB [orphan] 487 modules
17
+ orphan modules 5.48 MiB [orphan] 487 modules
18
18
  runtime modules 6.94 KiB 10 modules
19
- built modules 5.57 MiB [built]
19
+ built modules 5.59 MiB [built]
20
20
  modules by path ../../../node_modules/ 780 KiB 23 modules
21
- modules by path ../../MJCoreEntities/dist/ 3.14 MiB
22
- ../../MJCoreEntities/dist/index.js + 23 modules 3.12 MiB [built] [code generated]
21
+ modules by path ../../MJCoreEntities/dist/ 3.16 MiB
22
+ ../../MJCoreEntities/dist/index.js + 23 modules 3.14 MiB [built] [code generated]
23
23
  ../../MJCoreEntities/dist/engines/UserViewEngine.js 18.7 KiB [built] [code generated]
24
24
  modules by path ../../MJGlobal/dist/ 193 KiB
25
25
  ../../MJGlobal/dist/index.js + 16 modules 193 KiB [built] [code generated]
26
26
  ../../MJGlobal/dist/ lazy strict namespace object 160 bytes [built] [code generated]
27
- ./dist/index.js + 27 modules 420 KiB [built] [code generated]
27
+ ./dist/index.js + 27 modules 423 KiB [built] [code generated]
28
28
  ../../MJCore/dist/index.js + 71 modules 985 KiB [built] [code generated]
29
- ../../GraphQLDataProvider/dist/index.mjs 114 KiB [built] [code generated]
29
+ ../../GraphQLDataProvider/dist/index.mjs 115 KiB [built] [code generated]
30
30
 
31
31
  WARNING in ../../MJGlobal/dist/DynamicPackageLoader.js 80:21-44
32
32
  Critical dependency: the request of a dependency is an expression
@@ -39,4 +39,4 @@ built modules 5.57 MiB [built]
39
39
  1 warning has detailed information that is not shown.
40
40
  Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
41
41
 
42
- webpack 5.105.0 compiled with 1 warning in 129986 ms
42
+ webpack 5.105.0 compiled with 1 warning in 131837 ms
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @memberjunction/react-runtime
2
2
 
3
+ ## 5.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - @memberjunction/graphql-dataprovider@5.3.1
8
+ - @memberjunction/interactive-component-types@5.3.1
9
+ - @memberjunction/core@5.3.1
10
+ - @memberjunction/core-entities@5.3.1
11
+ - @memberjunction/global@5.3.1
12
+
13
+ ## 5.3.0
14
+
15
+ ### Patch Changes
16
+
17
+ - a6aea29: Fix artifact auto-open for delegated sub-agent completions, add SSE-aware request method and fire-and-forget GraphQL mutation to prevent Azure proxy timeouts, fix WebSocket reconnection catch-up check, and remove crossOrigin CORS enforcement with fallback CDN support in React runtime
18
+ - Updated dependencies [a6aea29]
19
+ - Updated dependencies [1692c53]
20
+ - @memberjunction/graphql-dataprovider@5.3.0
21
+ - @memberjunction/core-entities@5.3.0
22
+ - @memberjunction/interactive-component-types@5.3.0
23
+ - @memberjunction/core@5.3.0
24
+ - @memberjunction/global@5.3.0
25
+
3
26
  ## 5.2.0
4
27
 
5
28
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- "use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>M,ActionItemOutput:()=>L,BrowserIndexedDBStorageProvider:()=>w,BrowserStorageProviderBase:()=>R,FieldMapper:()=>g,GetDataOutput:()=>T,GraphQLAIClient:()=>I,GraphQLActionClient:()=>_,GraphQLComponentRegistryClient:()=>k,GraphQLDataProvider:()=>f,GraphQLEncryptionClient:()=>O,GraphQLFileStorageClient:()=>j,GraphQLProviderConfigData:()=>P,GraphQLSystemUserClient:()=>G,GraphQLTestingClient:()=>K,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>v,RolesAndUsersInput:()=>N,SimpleRemoteEntity:()=>V,SimpleRemoteEntityField:()=>F,SimpleRemoteEntityOutput:()=>U,SyncDataAction:()=>x,SyncDataResult:()=>Q,SyncRolesAndUsersResult:()=>$,UserInput:()=>A,gql:()=>s.J1,setupGraphQLClient:()=>C});var s=r(215),a=r(454),n=r(429),o=r(600),i=r(49),u=r(226),c=r(497),l=r(718),d=r(292),m=r(196),y=Object.defineProperty,p=(e,t)=>y(e,"name",{value:t,configurable:!0});class g{static{p(this,"FieldMapper")}constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([e,t])=>[t,e]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}}class h extends a.VH{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
1
+ "use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>M,ActionItemOutput:()=>G,BrowserIndexedDBStorageProvider:()=>w,BrowserStorageProviderBase:()=>R,FieldMapper:()=>g,GetDataOutput:()=>T,GraphQLAIClient:()=>I,GraphQLActionClient:()=>_,GraphQLComponentRegistryClient:()=>k,GraphQLDataProvider:()=>P,GraphQLEncryptionClient:()=>O,GraphQLFileStorageClient:()=>j,GraphQLProviderConfigData:()=>f,GraphQLSystemUserClient:()=>L,GraphQLTestingClient:()=>K,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>v,RolesAndUsersInput:()=>N,SimpleRemoteEntity:()=>F,SimpleRemoteEntityField:()=>V,SimpleRemoteEntityOutput:()=>U,SyncDataAction:()=>x,SyncDataResult:()=>Q,SyncRolesAndUsersResult:()=>$,UserInput:()=>A,gql:()=>s.J1,setupGraphQLClient:()=>C});var s=r(215),a=r(454),n=r(429),o=r(600),i=r(49),u=r(226),c=r(497),l=r(718),d=r(292),m=r(196),y=Object.defineProperty,p=(e,t)=>y(e,"name",{value:t,configurable:!0});class g{static{p(this,"FieldMapper")}constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([e,t])=>[t,e]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}}class h extends a.VH{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
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 e of this.PendingTransactions)t.push({EntityName:e.BaseEntity.EntityInfo.Name,EntityObjectJSON:await e.BaseEntity.GetDataObjectJSON(),OperationType:e.OperationType});const r={group:{Items:t,Variables:this.Variables.map(e=>({Name:e.Name,ItemIndex:this.MapVariableEntityObjectToPosition(e),FieldName:e.FieldName,Type:e.Type}))}},n=await this._provider.ExecuteGQL(e,r);if(n&&n.ExecuteTransactionGroup){const e=n.ExecuteTransactionGroup,t=[];for(let r=0;r<this.PendingTransactions.length;r++){const s=e.ResultsJSON[r],n=(0,d.NG)(s),o=this.PendingTransactions[r];t.push(new a.qT(o,n,null!==n))}return t}throw new Error("Failed to execute transaction group")}}class I{static{p(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=s.J1`
9
+ `,t=[];for(const e of this.PendingTransactions)t.push({EntityName:e.BaseEntity.EntityInfo.Name,EntityObjectJSON:await e.BaseEntity.GetDataObjectJSON(),OperationType:e.OperationType});const r={group:{Items:t,Variables:this.Variables.map(e=>({Name:e.Name,ItemIndex:this.MapVariableEntityObjectToPosition(e),FieldName:e.FieldName,Type:e.Type}))}},n=await this._provider.ExecuteGQL(e,r);if(n&&n.ExecuteTransactionGroup){const e=n.ExecuteTransactionGroup,t=[];for(let r=0;r<this.PendingTransactions.length;r++){const s=e.ResultsJSON[r],n=(0,d.NG)(s),o=this.PendingTransactions[r];t.push(new a.qT(o,n,null!==n))}return t}throw new Error("Failed to execute transaction group")}}class I{static{p(this,"GraphQLAIClient")}static{this.FIRE_AND_FORGET_TIMEOUT_MS=9e5}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=s.J1`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -104,7 +104,7 @@
104
104
  result
105
105
  }
106
106
  }
107
- `,i=this.prepareAgentVariables(e,t,r),u=await this._dataProvider.ExecuteGQL(o,i);return this.processAgentResult(u.RunAIAgent?.result)}catch(e){return this.handleAgentError(e)}finally{n&&n.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return void 0!==e.data&&(s.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(s.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(s.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(s.configurationId=e.configurationId),void 0!==e.conversationDetailId&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),void 0!==t&&(s.sourceArtifactId=t),void 0!==r&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return(0,d.NG)(e)}handleAgentError(e){return(0,a.ZI)(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const r=JSON.parse(t);if("RunAIAgentResolver"===r.resolver&&"ExecutionProgress"===r.type&&"ok"===r.status&&r.data?.progress){const t={...r.data.progress,metadata:{...r.data.progress.metadata||{},agentRunId:r.data.agentRunId}};e.onProgress(t)}}catch(e){console.error("[GraphQLAIClient] Failed to parse progress message:",e)}}));const r=s.J1`
107
+ `,i=this.prepareAgentVariables(e,t,r),u=await this._dataProvider.ExecuteGQL(o,i);return this.processAgentResult(u.RunAIAgent?.result)}catch(e){return this.handleAgentError(e)}finally{n&&n.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return void 0!==e.data&&(s.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(s.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(s.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(s.configurationId=e.configurationId),void 0!==e.conversationDetailId&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),void 0!==t&&(s.sourceArtifactId=t),void 0!==r&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return(0,d.NG)(e)}handleAgentError(e){const t=e?.message||String(e);(0,a.ZI)(`Error running AI agent: ${t}`);const r=t.includes("Failed to fetch")||t.includes("NetworkError");let s;return t.includes("timed out")||t.includes("timeout"),s=r?"Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":t,{success:!1,agentRun:void 0,errorMessage:s}}async RunAIAgentFromConversationDetail(e){let t,r;try{let a,n;const o=new Promise((e,t)=>{a=e,n=t});r=setTimeout(()=>{n(new Error("The agent may still be running on the server but the connection timed out after 15 minutes. Please refresh the page to check the latest status."))},I.FIRE_AND_FORGET_TIMEOUT_MS),t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const s=JSON.parse(t);if(e.onProgress&&"RunAIAgentResolver"===s.resolver&&"ExecutionProgress"===s.type&&"ok"===s.status&&s.data?.progress){const t={...s.data.progress,metadata:{...s.data.progress.metadata||{},agentRunId:s.data.agentRunId}};e.onProgress(t)}"RunAIAgentResolver"===s.resolver&&"StreamingContent"===s.type&&"ok"===s.status&&"complete"===s.data?.type&&s.data?.conversationDetailId===e.conversationDetailId&&(r&&clearTimeout(r),s.data.result?a((0,d.NG)(s.data.result)):a({success:!1!==s.data.success,agentRun:void 0}))}catch(e){console.error("[GraphQLAIClient] Failed to parse progress message:",e)}});const i=s.J1`
108
108
  mutation RunAIAgentFromConversationDetail(
109
109
  $conversationDetailId: String!,
110
110
  $agentId: String!,
@@ -118,7 +118,8 @@
118
118
  $createArtifacts: Boolean,
119
119
  $createNotification: Boolean,
120
120
  $sourceArtifactId: String,
121
- $sourceArtifactVersionId: String
121
+ $sourceArtifactVersionId: String,
122
+ $fireAndForget: Boolean
122
123
  ) {
123
124
  RunAIAgentFromConversationDetail(
124
125
  conversationDetailId: $conversationDetailId,
@@ -133,7 +134,8 @@
133
134
  createArtifacts: $createArtifacts,
134
135
  createNotification: $createNotification,
135
136
  sourceArtifactId: $sourceArtifactId,
136
- sourceArtifactVersionId: $sourceArtifactVersionId
137
+ sourceArtifactVersionId: $sourceArtifactVersionId,
138
+ fireAndForget: $fireAndForget
137
139
  ) {
138
140
  success
139
141
  errorMessage
@@ -141,7 +143,7 @@
141
143
  result
142
144
  }
143
145
  }
144
- `,a={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};void 0!==e.maxHistoryMessages&&(a.maxHistoryMessages=e.maxHistoryMessages),void 0!==e.data&&(a.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(a.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(a.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(a.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(a.configurationId=e.configurationId),void 0!==e.createArtifacts&&(a.createArtifacts=e.createArtifacts),void 0!==e.createNotification&&(a.createNotification=e.createNotification),void 0!==e.sourceArtifactId&&(a.sourceArtifactId=e.sourceArtifactId),void 0!==e.sourceArtifactVersionId&&(a.sourceArtifactVersionId=e.sourceArtifactVersionId);const n=await this._dataProvider.ExecuteGQL(r,a);return this.processAgentResult(n.RunAIAgentFromConversationDetail?.result)}catch(e){return this.handleAgentError(e)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=s.J1`
146
+ `,u={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};void 0!==e.maxHistoryMessages&&(u.maxHistoryMessages=e.maxHistoryMessages),void 0!==e.data&&(u.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(u.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(u.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(u.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(u.configurationId=e.configurationId),void 0!==e.createArtifacts&&(u.createArtifacts=e.createArtifacts),void 0!==e.createNotification&&(u.createNotification=e.createNotification),void 0!==e.sourceArtifactId&&(u.sourceArtifactId=e.sourceArtifactId),void 0!==e.sourceArtifactVersionId&&(u.sourceArtifactVersionId=e.sourceArtifactVersionId);const c=(await this._dataProvider.ExecuteGQL(i,u)).RunAIAgentFromConversationDetail;return c?.success?await o:(r&&clearTimeout(r),{success:!1,agentRun:void 0,errorMessage:c?.errorMessage||"Server rejected the agent execution request"})}catch(e){return r&&clearTimeout(r),this.handleAgentError(e)}finally{r&&clearTimeout(r),t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=s.J1`
145
147
  mutation ExecuteSimplePrompt(
146
148
  $systemPrompt: String!,
147
149
  $messages: String,
@@ -179,9 +181,9 @@
179
181
  error
180
182
  }
181
183
  }
182
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const S="default";class R{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||S;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||S).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||S).set(e,t)}async Remove(e,t){this.getCategoryMap(t||S).delete(e)}async ClearCategory(e){const t=e||S;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||S);return t?Array.from(t.keys()):[]}}const D=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],E="Metadata_KVPairs";class w extends R{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(E)&&e.deleteObjectStore(E);for(const t of D)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return D.includes(t)}getStoreName(e){const t=e||S;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||S;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class P extends a.dZ{static{p(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,r,s,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class f extends a.Dn{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
184
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const S="default";class R{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||S;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||S).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||S).set(e,t)}async Remove(e,t){this.getCategoryMap(t||S).delete(e)}async ClearCategory(e){const t=e||S;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||S);return t?Array.from(t.keys()):[]}}const D=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],E="Metadata_KVPairs";class w extends R{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(E)&&e.deleteObjectStore(E);for(const t of D)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return D.includes(t)}getStoreName(e){const t=e||S;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||S;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class f extends a.dZ{static{p(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,r,s,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class P extends a.Dn{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
183
185
  ${this._innerCurrentUserQueryString}
184
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,f._instance||(f._instance=this)}static get Instance(){return f._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new I(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,l.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(f.Instance._configData=e,void 0===f.Instance._sessionId&&(f.Instance._sessionId=await this.GetPreferredUUID(s)),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(e){throw(0,a.ZI)(e),e}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
186
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,P._instance||(P._instance=this)}static get Instance(){return P._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new I(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,l.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(P.Instance._configData=e,void 0===P.Instance._sessionId&&(P.Instance._sessionId=await this.GetPreferredUUID(s)),P.Instance._client||(P.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,P.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await P.Instance.SaveStoredSessionID(P.Instance._sessionId),this._sessionId=P.Instance._sessionId,this._client=P.Instance._client),super.Config(e)}catch(e){throw(0,a.ZI)(e),e}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
185
187
  query GetReportDataQuery ($ReportID: String!) {
186
188
  GetReportData(ReportID: $ReportID) {
187
189
  Success
@@ -418,14 +420,14 @@
418
420
  ErrorMessage
419
421
  Result
420
422
  }
421
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return f.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0){if("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}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)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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)}}}static async RefreshToken(){return f.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new w:this._localStorageProvider=new a.KW),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&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,c.UU)({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!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(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 o.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:p(e=>{r.next(e.data)},"next"),error:p(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new o.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
423
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return P.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0){if("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}async RefreshToken(){const e=P.Instance&&P.Instance._configData===this._configData;if(e&&P.Instance._refreshPromise)return P.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(P.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&P.Instance&&(P.Instance._refreshPromise=null)}}async performTokenRefresh(){if(!this._configData.Data.RefreshTokenFunction)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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,P.Instance&&P.Instance._configData===this._configData&&(P.Instance._client=t)}}}static async RefreshToken(){return P.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new w:this._localStorageProvider=new a.KW),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&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,c.UU)({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!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(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 o.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:p(e=>{r.next(e.data)},"next"),error:p(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new o.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
422
424
  statusUpdates(sessionId: $sessionId) {
423
425
  date
424
426
  message
425
427
  sessionId
426
428
  }
427
429
  }
428
- `,n=new i.B,c=this.getOrCreateWSClient(),l=new u.yU;return l.add(new o.c(t=>{const r=c.subscribe({query:a,variables:{sessionId:e}},{next:p(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:p(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:p(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:p(e=>n.next(e),"next"),error:p(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new o.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function C(e){const t=new f;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),d.rt.Instance.RaiseEvent({event:d.UK.LoggedIn,eventCode:null,component:this,args:null}),t}p(C,"setupGraphQLClient");class ${static{p(this,"SyncRolesAndUsersResult")}}class v{static{p(this,"RoleInput")}}class A{static{p(this,"UserInput")}}class N{static{p(this,"RolesAndUsersInput")}}var b,x=((b=x||{}).Create="Create",b.Update="Update",b.CreateOrUpdate="CreateOrUpdate",b.Delete="Delete",b.DeleteWithFilter="DeleteWithFilter",b);class M{static{p(this,"ActionItemInput")}}class Q{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class L{static{p(this,"ActionItemOutput")}}class G{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,d.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t=await this.Client.request("query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByNameSystemUser?t.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t=await this.Client.request("query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByIDSystemUser?t.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t=await this.Client.request("query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunDynamicViewSystemUser?t.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t=await this.Client.request("query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewsSystemUser?t.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&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 GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,d.NG)(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return(0,a.ZI)(`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(void 0!==e.Parameters&&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) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,d.NG)(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return(0,a.ZI)(`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 t=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r="mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
430
+ `,n=new i.B,c=this.getOrCreateWSClient(),l=new u.yU;return l.add(new o.c(t=>{const r=c.subscribe({query:a,variables:{sessionId:e}},{next:p(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:p(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:p(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:p(e=>n.next(e),"next"),error:p(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new o.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function C(e){const t=new P;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),d.rt.Instance.RaiseEvent({event:d.UK.LoggedIn,eventCode:null,component:this,args:null}),t}p(C,"setupGraphQLClient");class ${static{p(this,"SyncRolesAndUsersResult")}}class v{static{p(this,"RoleInput")}}class A{static{p(this,"UserInput")}}class N{static{p(this,"RolesAndUsersInput")}}var b,x=((b=x||{}).Create="Create",b.Update="Update",b.CreateOrUpdate="CreateOrUpdate",b.Delete="Delete",b.DeleteWithFilter="DeleteWithFilter",b);class M{static{p(this,"ActionItemInput")}}class Q{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class G{static{p(this,"ActionItemOutput")}}class L{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,d.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t=await this.Client.request("query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByNameSystemUser?t.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t=await this.Client.request("query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByIDSystemUser?t.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t=await this.Client.request("query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunDynamicViewSystemUser?t.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t=await this.Client.request("query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewsSystemUser?t.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&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 GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,d.NG)(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return(0,a.ZI)(`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(void 0!==e.Parameters&&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) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,d.NG)(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return(0,a.ZI)(`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 t=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r="mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
429
431
  query RunAIPromptSystemUser(
430
432
  $promptId: String!,
431
433
  $data: String,
@@ -549,7 +551,7 @@
549
551
  error
550
552
  }
551
553
  }
552
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,r);if(!a?.EmbedTextSystemUser)return{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class T{static{p(this,"GetDataOutput")}}class U{static{p(this,"SimpleRemoteEntityOutput")}}class V{static{p(this,"SimpleRemoteEntity")}}class F{static{p(this,"SimpleRemoteEntityField")}}class _{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(e){return this.handleActionError(e,t)}}serializeActionParameters(e){if(e)return e.map(e=>{let t=e.Value;return null!=t&&"object"==typeof t&&(t=JSON.stringify(t)),{...e,Value:t}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=s.J1`
554
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,r);if(!a?.EmbedTextSystemUser)return{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class T{static{p(this,"GetDataOutput")}}class U{static{p(this,"SimpleRemoteEntityOutput")}}class F{static{p(this,"SimpleRemoteEntity")}}class V{static{p(this,"SimpleRemoteEntityField")}}class _{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(e){return this.handleActionError(e,t)}}serializeActionParameters(e){if(e)return e.map(e=>{let t=e.Value;return null!=t&&"object"==typeof t&&(t=JSON.stringify(t)),{...e,Value:t}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=s.J1`
553
555
  mutation RunAction($input: RunActionInput!) {
554
556
  RunAction(input: $input) {
555
557
  Success