@memberjunction/graphql-dataprovider 5.7.0 → 5.9.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/README.md +4 -0
- package/dist/index.cjs +193 -89
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +187 -9
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +187 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +193 -89
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var W=Object.defineProperty;var g=(h,e)=>W(h,"name",{value:e,configurable:!0});import{gql as y,GraphQLClient as F}from"graphql-request";import{gql as ze}from"graphql-request";import{TransactionGroupBase as z,TransactionResult as X,LogError as c,LogStatus as L,LogErrorEx as A,ProviderBase as H,UserInfo as Q,getGraphQLTypeNameBase as N,ProviderType as Y,BaseEntityResult as T,EntityFieldTSType as b,TransactionItem as U,CompositeKey as Z,UserRoleInfo as ee,InMemoryLocalStorageProvider as te,BaseEntity as re,ProviderConfigDataBase as se,SetProvider as ne,StartupManager as ae,IsPlatformSQL as oe,IsVerboseLoggingEnabled as ie}from"@memberjunction/core";import{SafeJSONParse as $,UUIDsEqual as ue,MJGlobal as V,MJEventType as G}from"@memberjunction/global";import{ViewInfo as _}from"@memberjunction/core-entities";import{Observable as M,Subject as ce,Subscription as le}from"rxjs";import{createClient as de}from"graphql-ws";import{v4 as ye}from"uuid";import{openDB as me}from"@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 O extends z{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
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
|
|
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,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],u=$(o),l=this.PendingTransactions[i];a.push(new X(l,u,u!==null))}return a}else throw new Error("Failed to execute transaction group")}}const ge=900*1e3;class P{static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let s,r;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();r=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),s=P.subscribeToPubSub(e,a,r);const o=await P.executeMutation(e);if(!e.validateAck(o)){r&&clearTimeout(r);const u=o?.errorMessage??"Server rejected the request";return c(`[FireAndForget:${t}] Server rejected: ${u}`),e.createErrorResult(u)}return L(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){throw r&&clearTimeout(r),c(`[FireAndForget:${t}] Error: ${n.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??ge,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(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(s),L(`[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 q{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -65,7 +65,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
65
65
|
chatResult
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,
|
|
68
|
+
`,s=this.preparePromptVariables(e),r=await this._dataProvider.ExecuteGQL(t,s);return this.processPromptResult(r)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let s,r,n;try{t.parsedResult&&(s=JSON.parse(t.parsedResult))}catch{s=t.parsedResult}try{t.validationResult&&(r=JSON.parse(t.validationResult))}catch{r=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:s,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:r,chatResult:n}}handlePromptError(e){const t=e;return c(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,s){try{const r=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,s);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:r,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:g(a=>a?.success===!0,"validateAck"),isCompletionEvent:g(a=>this.isAgentCompletionEvent(a),"isCompletionEvent"),extractResult:g(a=>this.extractAgentResult(a),"extractResult"),onMessage:e.onProgress?a=>this.forwardAgentProgress(a,e.onProgress):void 0,createErrorResult:g(a=>this.createAgentErrorResult(a),"createErrorResult")})}catch(r){return this.handleAgentError(r)}}buildRunAIAgentMutation(){return y`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -106,7 +106,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
106
106
|
result
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
|
-
`}prepareAgentVariables(e,t,
|
|
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 $(e)}handleAgentError(e){const s=e?.message||String(e);c(`Error running AI agent: ${s}`);const r=s.includes("Failed to fetch")||s.includes("NetworkError"),n=s.includes("timed out")||s.includes("timeout");let a;return r?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=s,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await P.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 y`
|
|
110
110
|
mutation RunAIAgentFromConversationDetail(
|
|
111
111
|
$conversationDetailId: String!,
|
|
112
112
|
$agentId: String!,
|
|
@@ -145,7 +145,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
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
|
|
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?$(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=y`
|
|
149
149
|
mutation ExecuteSimplePrompt(
|
|
150
150
|
$systemPrompt: String!,
|
|
151
151
|
$messages: String,
|
|
@@ -168,7 +168,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
168
168
|
executionTimeMs
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
|
-
`,
|
|
171
|
+
`,s={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(s.messages=JSON.stringify(e.messages)),e.preferredModels&&(s.preferredModels=e.preferredModels),e.modelPower&&(s.modelPower=e.modelPower),e.responseFormat&&(s.responseFormat=e.responseFormat);const r=await this._dataProvider.ExecuteGQL(t,s);if(!r?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=r.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const s=t;return c(`Error executing simple prompt: ${s}`),{success:!1,modelName:"Unknown",error:s.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=y`
|
|
172
172
|
mutation EmbedText(
|
|
173
173
|
$textToEmbed: [String!]!,
|
|
174
174
|
$modelSize: String!
|
|
@@ -183,15 +183,15 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
183
183
|
error
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
`,
|
|
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 a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const s=t;return c(`Error generating embeddings: ${s}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:s.message||"Unknown error occurred"}}}}const C="default";class k{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||C;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||C).get(e)??null}async SetItem(e,t,s){this.getCategoryMap(s||C).set(e,t)}async Remove(e,t){this.getCategoryMap(t||C).delete(e)}async ClearCategory(e){const t=e||C;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||C);return t?Array.from(t.keys()):[]}}const pe="MJ_Metadata",he=3,K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],B="Metadata_KVPairs";class j extends k{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=me(pe,he,{upgrade(e){try{e.objectStoreNames.contains(B)&&e.deleteObjectStore(B);for(const t of K)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){A({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return K.includes(t)}getStoreName(e){const t=e||C;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const s=t||C;return this.isKnownCategory(s)?e:`[${s}]:${e}`}async SetItem(e,t,s){try{const r=await this.dbPromise,n=this.getStoreName(s),a=this.getStoreKey(e,s),i=r.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(r){A({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 A({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),a=s.transaction(r,"readwrite");await a.objectStore(r).delete(n),await a.done}catch(s){A({error:s,message:s?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,s=e||C,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}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(n)&&await i.delete(u);await a.done}}catch(t){A({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,s=e||C,r=this.getStoreName(e),i=await t.transaction(r,"readonly").objectStore(r).getAllKeys();if(this.isKnownCategory(s))return i.map(u=>String(u));const o=`[${s}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return A({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class Se extends se{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,a,i,o,u){super({Token:e,URL:t,WSURL:s,MJAPIKey:o,UserAPIKey:u,RefreshTokenFunction:r},n,a,i)}}class f extends H{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
|
|
187
187
|
${this.userInfoString()}
|
|
188
188
|
MJUserRoles_UserIDArray {
|
|
189
189
|
${this.userRoleInfoString()}
|
|
190
190
|
}
|
|
191
191
|
}
|
|
192
|
-
`,this._currentUserQuery=
|
|
192
|
+
`,this._currentUserQuery=y`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,
|
|
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 q(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return ye()}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 c(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 Q(this,{...t,UserRoles:s})}}async RunReport(e,t){const s=y`
|
|
195
195
|
query GetReportDataQuery ($ReportID: String!) {
|
|
196
196
|
GetReportData(ReportID: $ReportID) {
|
|
197
197
|
Success
|
|
@@ -200,31 +200,31 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
200
200
|
ExecutionTime
|
|
201
201
|
ErrorMessage
|
|
202
202
|
}
|
|
203
|
-
}`,
|
|
203
|
+
}`,r=await this.ExecuteGQL(s,{ReportID:e.ReportID});if(r&&r.GetReportData)return{ReportID:e.ReportID,Success:r.GetReportData.Success,Results:JSON.parse(r.GetReportData.Results),RowCount:r.GetReportData.RowCount,ExecutionTime:r.GetReportData.ExecutionTime,ErrorMessage:r.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,s){const r=y`
|
|
204
204
|
query ExecuteAdhocQuery($input: AdhocQueryInput!) {
|
|
205
205
|
ExecuteAdhocQuery(input: $input) {
|
|
206
206
|
${this.QueryReturnFieldList}
|
|
207
207
|
}
|
|
208
208
|
}
|
|
209
|
-
`,n={SQL:e};
|
|
209
|
+
`,n={SQL:e};s!==void 0&&(n.TimeoutSeconds=s);const a=await this.ExecuteGQL(r,{input:n});return a?.ExecuteAdhocQuery?this.TransformQueryPayload(a.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const s=y`
|
|
210
210
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
211
211
|
RunQueries(input: $input) {
|
|
212
212
|
${this.QueryReturnFieldList}
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
|
-
`,
|
|
215
|
+
`,r=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription})),n=await this.ExecuteGQL(s,{input:r});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,s,r,n,a,i){const o=y`
|
|
216
216
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
217
217
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
218
218
|
${this.QueryReturnFieldList}
|
|
219
219
|
}
|
|
220
220
|
}
|
|
221
|
-
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),
|
|
221
|
+
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),s!==void 0&&(u.CategoryPath=s),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i);const l=await this.ExecuteGQL(o,u);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,s,r,n,a,i){const o=y`
|
|
222
222
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
223
223
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
224
224
|
${this.QueryReturnFieldList}
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),
|
|
227
|
+
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),s!==void 0&&(u.CategoryPath=s),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i);const l=await this.ExecuteGQL(o,u);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
228
228
|
Success
|
|
229
229
|
QueryID
|
|
230
230
|
QueryName
|
|
@@ -233,7 +233,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
233
233
|
TotalRowCount
|
|
234
234
|
ExecutionTime
|
|
235
235
|
ErrorMessage
|
|
236
|
-
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const
|
|
236
|
+
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const s=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),r=y`
|
|
237
237
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
238
238
|
RunQueriesWithCacheCheck(input: $input) {
|
|
239
239
|
success
|
|
@@ -249,18 +249,18 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
251
|
}
|
|
252
|
-
`,a=(await this.ExecuteGQL(
|
|
252
|
+
`,a=(await this.ExecuteGQL(r,{input:s}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(s){return c(`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 a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:p,v:I}=await this.getEntityNameAndUserView(e,t);i=I,a=p}const o=this.Entities.find(p=>p.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let u=!1;const l=N(o);e.ViewID?(s=`Run${l}ViewByID`,r="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(s=`Run${l}ViewByName`,r="RunViewByNameInput",n.ViewName=e.ViewName):(u=!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),u||(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(o,i,e,u),R=e.Aggregates&&e.Aggregates.length>0?`
|
|
253
253
|
AggregateResults {
|
|
254
254
|
alias
|
|
255
255
|
expression
|
|
256
256
|
value
|
|
257
257
|
error
|
|
258
258
|
}
|
|
259
|
-
AggregateExecutionTime`:"",
|
|
260
|
-
query RunViewQuery ($input: ${
|
|
261
|
-
${
|
|
259
|
+
AggregateExecutionTime`:"",d=y`
|
|
260
|
+
query RunViewQuery ($input: ${r}!) {
|
|
261
|
+
${s}(input: $input) {
|
|
262
262
|
Results {
|
|
263
|
-
${
|
|
263
|
+
${S.join(`
|
|
264
264
|
`)}
|
|
265
265
|
}
|
|
266
266
|
UserViewRunID
|
|
@@ -270,14 +270,14 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
270
270
|
Success
|
|
271
271
|
ErrorMessage${R}
|
|
272
272
|
}
|
|
273
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:
|
|
273
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:s,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(d,{input:n});if(m&&m[s]){const p=m[s].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[s].AggregateExecutionTime});const I=m[s].Results;if(I&&I.length>0){const v=o.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),v.forEach(x=>{D[x.Name]=D[x.CodeName]})})}return m[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw c(s),s}}async InternalRunViews(e,t){try{let s=[],r=[],n=[];for(const l of e){let S="",R="";const d={};let m=null,p=null;if(l.ViewEntity)p=l.ViewEntity,m=p.Get("Entity");else{const{entityName:D,v:x}=await this.getEntityNameAndUserView(l,t);p=x,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 E=!1;const v=N(I);l.ViewID?(S=`Run${v}ViewByID`,R="RunViewByIDInput",d.ViewID=l.ViewID):l.ViewName?(S=`Run${v}ViewByName`,R="RunViewByNameInput",d.ViewName=l.ViewName):(E=!0,S=`Run${v}DynamicView`,R="RunDynamicViewInput",d.EntityName=l.EntityName),d.ExtraFilter=l.ExtraFilter||"",d.OrderBy=l.OrderBy||"",d.UserSearchString=l.UserSearchString||"",d.Fields=l.Fields,d.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(d.MaxRows=l.MaxRows),l.StartRow!==void 0&&(d.StartRow=l.StartRow),d.ForceAuditLog=l.ForceAuditLog||!1,d.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(d.AuditLogDescription=l.AuditLogDescription),E||(d.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=l.OverrideExcludeFilter||"",d.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(d.Aggregates=l.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),s.push(d),n.push(...this.getViewRunTimeFieldList(I,p,l,E))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
274
274
|
AggregateResults {
|
|
275
275
|
alias
|
|
276
276
|
expression
|
|
277
277
|
value
|
|
278
278
|
error
|
|
279
279
|
}
|
|
280
|
-
AggregateExecutionTime`:"",o=
|
|
280
|
+
AggregateExecutionTime`:"",o=y`
|
|
281
281
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
282
282
|
RunViews(input: $input) {
|
|
283
283
|
Results {
|
|
@@ -295,7 +295,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
295
295
|
Success
|
|
296
296
|
ErrorMessage${i}
|
|
297
297
|
}
|
|
298
|
-
}`,u=await this.ExecuteGQL(o,{input:
|
|
298
|
+
}`,u=await this.ExecuteGQL(o,{input:s});if(u&&u.RunViews){const l=u.RunViews;for(const[S,R]of l.entries())R.Results=R.Results.map(d=>{let m=JSON.parse(d.Data);return this.ConvertBackToMJFields(m),m});return l}return null}catch(s){throw c(s),s}}async RunViewsWithCacheCheck(e,t){try{const s=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),r=y`
|
|
299
299
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
300
300
|
RunViewsWithCacheCheck(input: $input) {
|
|
301
301
|
success
|
|
@@ -328,7 +328,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
328
328
|
}
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
|
-
`,a=(await this.ExecuteGQL(
|
|
331
|
+
`,a=(await this.ExecuteGQL(r,{input:s}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,u)=>{const l=e[u];if(o.status==="differential"&&o.differentialData){const S=o.differentialData.updatedRows.map(R=>{const d=JSON.parse(R.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:S,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const S=o.Results.map(R=>{const d=JSON.parse(R.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:o.viewIndex,status:o.status,results:S,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(s){return c(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 _.GetViewEntity(e.ViewID,t),s=r.Entity;else if(e.ViewName)r=await _.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=[],a=new w;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);s.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(r)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return Y.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,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(s){throw c(s),s}}async GetRecordDependencies(e,t){try{const s=y`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
332
332
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
333
333
|
EntityName
|
|
334
334
|
RelatedEntityName
|
|
@@ -340,7 +340,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
340
340
|
}
|
|
341
341
|
}
|
|
342
342
|
}
|
|
343
|
-
}`,
|
|
343
|
+
}`,r={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(s,r))?.GetRecordDependencies}catch(s){throw c(s),s}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const s=y`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
344
344
|
GetRecordDuplicates(params: $params) {
|
|
345
345
|
Status
|
|
346
346
|
ErrorMessage
|
|
@@ -362,7 +362,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
362
362
|
}
|
|
363
363
|
}
|
|
364
364
|
}
|
|
365
|
-
}`;let
|
|
365
|
+
}`;let r={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.Copy())};const n=await this.ExecuteGQL(s,{params:r});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,s){const r=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!r||!r.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=y`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
366
366
|
MergeRecords(request: $request) {
|
|
367
367
|
Success
|
|
368
368
|
OverallStatus
|
|
@@ -379,32 +379,32 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
379
379
|
Message
|
|
380
380
|
}
|
|
381
381
|
}
|
|
382
|
-
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,
|
|
383
|
-
${e.Fields.map(l
|
|
382
|
+
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c(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 T;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 T;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";r.StartedAt=new Date,r.Type=e.IsSaved?"update":"create",r.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(r);const i=N(e.EntityInfo),o=`${a}${i}`,u=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),l=new w,S=` ${o}(input: $input) {
|
|
383
|
+
${e.Fields.map(d=>l.MapFieldName(d.CodeName)).join(`
|
|
384
384
|
`)}
|
|
385
|
-
}`,R=
|
|
386
|
-
${
|
|
385
|
+
}`,R=y`mutation ${a}${i} ($input: ${o}Input!) {
|
|
386
|
+
${S}
|
|
387
387
|
}
|
|
388
|
-
`;for(let
|
|
388
|
+
`;for(let d=0;d<u.length;d++){const m=u[d];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case b.Date:p=p.getTime();break;case b.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case b.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===b.Number||m.FieldType===b.Boolean?p=0:p=""),n.input[l.MapFieldName(m.CodeName)]=p}if(a.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===b.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===b.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),d.push({Key:l.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new U(e,r.Type==="create"?"Create":"Update",S,n,{mutationName:o,mutationInputTypes:d},(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 d=await this.ExecuteGQL(R,n);if(d&&d[o])return r.Success=!0,r.EndedAt=new Date,r.NewValues=this.ConvertBackToMJFields(d[o]),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,c(n),null}}async Load(e,t,s=null,r){try{const n={};let a="",i="";for(let d=0;d<t.KeyValuePairs.length;d++){const m=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(d),I=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${I}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===b.Number){if(isNaN(t.GetValueByIndex(d)))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 o=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",u=N(e.EntityInfo),l=new w,S=y`query Single${u}${o.length>0?"Full":""} (${i}) {
|
|
389
389
|
${u}(${a}) {
|
|
390
|
-
${e.Fields.filter(
|
|
390
|
+
${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
|
|
391
391
|
`)}
|
|
392
392
|
${o}
|
|
393
393
|
}
|
|
394
394
|
}
|
|
395
|
-
`,R=await this.ExecuteGQL(
|
|
395
|
+
`,R=await this.ExecuteGQL(S,n);return R&&R[u]?this.ConvertBackToMJFields(R[u]):null}catch(n){return c(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],a=this.Entities.find(o=>ue(o.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
396
|
${i} {
|
|
397
397
|
${a.Fields.map(o=>o.CodeName).join(`
|
|
398
398
|
`)}
|
|
399
399
|
}
|
|
400
|
-
`}return
|
|
401
|
-
`),u+=`${
|
|
400
|
+
`}return s}async Delete(e,t,s){const r=new T;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={},a=[];let i="",o="",u="";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,a.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,o.length>0&&(o+=", "),o+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
|
|
401
|
+
`),u+=`${p.CodeName}`}a.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"+N(e.EntityInfo),R=y`${S}(${i}, options___: $options___) {
|
|
402
402
|
${u}
|
|
403
403
|
}
|
|
404
|
-
`,
|
|
404
|
+
`,d=y`mutation ${S} (${o}, $options___: DeleteOptionsInput!) {
|
|
405
405
|
${R}
|
|
406
406
|
}
|
|
407
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new
|
|
407
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new U(e,"Delete",R,n,{mutationName:S,mutationInputTypes:a},(m,p)=>{if(r.EndedAt=new Date,p&&m){let I=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==m[E.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(d,n);if(m&&m[S]){const p=m[S];for(let I of e.PrimaryKey.KeyValuePairs){let E=p[I.FieldName],v=I.Value;if(typeof v=="number"&&(v=v.toString()),typeof E=="number"&&(E=E.toString()),v!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${v}, Returned: ${E}`)}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,c(n),!1}}async GetDatasetByName(e,t){const s=y`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
408
408
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
409
409
|
DatasetID
|
|
410
410
|
DatasetName
|
|
@@ -413,7 +413,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
413
413
|
LatestUpdateDate
|
|
414
414
|
Results
|
|
415
415
|
}
|
|
416
|
-
}`,
|
|
416
|
+
}`,r=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:t});return r&&r.GetDatasetByName&&r.GetDatasetByName.Success?{DatasetID:r.GetDatasetByName.DatasetID,DatasetName:r.GetDatasetByName.DatasetName,Success:r.GetDatasetByName.Success,Status:r.GetDatasetByName.Status,LatestUpdateDate:new Date(r.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(r.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const s=y`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
417
417
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
418
418
|
DatasetID
|
|
419
419
|
DatasetName
|
|
@@ -422,22 +422,22 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
422
422
|
LatestUpdateDate
|
|
423
423
|
EntityUpdateDates
|
|
424
424
|
}
|
|
425
|
-
}`,
|
|
425
|
+
}`,r=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:t});return r&&r.GetDatasetStatusByName&&r.GetDatasetStatusByName.Success?{DatasetID:r.GetDatasetStatusByName.DatasetID,DatasetName:r.GetDatasetStatusByName.DatasetName,Success:r.GetDatasetStatusByName.Success,Status:r.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(r.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(r.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new O(this)}async GetRecordFavoriteStatus(e,t,s){if(!s.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=y`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
426
426
|
GetRecordFavoriteStatus(params: $params) {
|
|
427
427
|
Success
|
|
428
428
|
IsFavorite
|
|
429
429
|
}
|
|
430
|
-
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(
|
|
430
|
+
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,s,r,n){const a=this.Entities.find(u=>u.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=y`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
431
431
|
SetRecordFavoriteStatus(params: $params){
|
|
432
432
|
Success
|
|
433
433
|
}
|
|
434
|
-
}`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(
|
|
434
|
+
}`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:r}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const s=y`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
435
435
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
436
436
|
Success
|
|
437
437
|
Status
|
|
438
438
|
RecordName
|
|
439
439
|
}
|
|
440
|
-
}`,
|
|
440
|
+
}`,r=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(r&&r.GetEntityRecordName&&r.GetEntityRecordName.Success)return r.GetEntityRecordName.RecordName}async InternalGetEntityRecordNames(e){if(!e)return null;const t=y`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
441
441
|
GetEntityRecordNames(info: $info) {
|
|
442
442
|
Success
|
|
443
443
|
Status
|
|
@@ -450,47 +450,57 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
450
450
|
EntityName
|
|
451
451
|
RecordName
|
|
452
452
|
}
|
|
453
|
-
}`,
|
|
453
|
+
}`,s=await this.ExecuteGQL(t,{info:e.map(r=>({EntityName:r.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames.map(r=>({...r,CompositeKey:new Z(r.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=y`query GetDataContextData ($DataContextID: String!) {
|
|
454
454
|
GetDataContextData(DataContextID: $DataContextID) {
|
|
455
455
|
Success
|
|
456
456
|
ErrorMessages
|
|
457
457
|
Results
|
|
458
458
|
}
|
|
459
|
-
}`,
|
|
459
|
+
}`,s=await this.ExecuteGQL(t,{DataContextID:e});if(s&&s.GetDataContextData){if(s.GetDataContextData.Success)return s.GetDataContextData.Results.map(r=>JSON.parse(r));throw new Error(s.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw c(t),t}}async GetDataContextItemData(e){try{const t=y`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
460
460
|
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
461
461
|
Success
|
|
462
462
|
ErrorMessage
|
|
463
463
|
Result
|
|
464
464
|
}
|
|
465
|
-
}`,
|
|
466
|
-
`:
|
|
467
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new
|
|
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 c(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 c("JWT_EXPIRED and refreshTokenIfNeeded is false"),r}else throw r;else throw c(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 a={"x-session-id":s};return t&&(a.authorization="Bearer "+t),r&&(a["x-mj-api-key"]=r),n&&(a["x-api-key"]=n),new F(e,{headers:a})}userInfoString(){return this.infoString(new Q(null,null))}userRoleInfoString(){return this.infoString(new ee(null))}infoString(e){let t="";const s=Object.keys(e);for(const r of s)r.startsWith("__mj_")?t+=r.replace("__mj_","_mj__")+`
|
|
466
|
+
`:r.startsWith("_")||(t+=r+`
|
|
467
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new j:this._localStorageProvider=new te),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=de({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,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),r.push(n))}),r.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(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 M(s=>{const r=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=r.subscribe({query:e,variables:t},{next:g(a=>{s.next(a.data)},"next"),error:g(async a=>{const i=a;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(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),s.error(u)}}else s.error(a)},"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 M(o=>{s.activeSubscribers++;const u=s.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,u.unsubscribe()}});const r=y`subscription StatusUpdates($sessionId: String!) {
|
|
468
468
|
statusUpdates(sessionId: $sessionId) {
|
|
469
469
|
date
|
|
470
470
|
message
|
|
471
471
|
sessionId
|
|
472
472
|
}
|
|
473
473
|
}
|
|
474
|
-
`,n=new
|
|
474
|
+
`,n=new ce,a=this.getOrCreateWSClient(),i=new le;return i.add(new M(o=>{const u=a.subscribe({query:r,variables:{sessionId:e}},{next:g(l=>{const S=this._pushStatusSubjects.get(e);S&&(S.lastEmissionAt=Date.now()),o.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(),o.complete()}catch(d){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",d),o.error(d)}}else o.error(l)},"error"),complete:g(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:g(o=>n.next(o),"next"),error:g(o=>{n.error(o),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 M(o=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const l=n.subscribe(o);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=y`subscription CacheInvalidation {
|
|
475
|
+
cacheInvalidation {
|
|
476
|
+
EntityName
|
|
477
|
+
PrimaryKeyValues
|
|
478
|
+
Action
|
|
479
|
+
SourceServerID
|
|
480
|
+
Timestamp
|
|
481
|
+
OriginSessionID
|
|
482
|
+
RecordData
|
|
483
|
+
}
|
|
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.Instance.RaiseEvent({event:G.ComponentEvent,eventCode:re.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!) {
|
|
475
485
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
476
486
|
Success
|
|
477
487
|
ChildEntityName
|
|
478
488
|
ErrorMessage
|
|
479
489
|
}
|
|
480
|
-
}`;try{const n=await this.ExecuteGQL(
|
|
490
|
+
}`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return c(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,s){if(!e.IsParentType)return[];const r=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
|
|
481
491
|
FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
|
|
482
492
|
Success
|
|
483
493
|
ChildEntityNames
|
|
484
494
|
ErrorMessage
|
|
485
495
|
}
|
|
486
|
-
}`;try{const n=await this.ExecuteGQL(
|
|
496
|
+
}`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return c(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function fe(h){const e=new f;return ne(e),await e.Config(h),await ae.Instance.Startup(),V.Instance.RaiseEvent({event:G.LoggedIn,eventCode:null,component:this,args:null}),e}g(fe,"setupGraphQLClient");class Ie{static{g(this,"SyncRolesAndUsersResult")}}class Re{static{g(this,"RoleInput")}}class Ee{static{g(this,"UserInput")}}class De{static{g(this,"RolesAndUsersInput")}}var J=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(J||{});class we{static{g(this,"ActionItemInput")}}class ve{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ce{static{g(this,"ActionItemOutput")}}class Pe{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 F(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return oe(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
487
497
|
GetData(input: $input) {
|
|
488
498
|
Success
|
|
489
499
|
ErrorMessages
|
|
490
500
|
Queries
|
|
491
501
|
Results
|
|
492
502
|
}
|
|
493
|
-
}`,{input:{Queries:e,Token:t}});return
|
|
503
|
+
}`,{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(n=>n?$(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]+"."),ie()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${s}`;c(a)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
494
504
|
GetAllEntities {
|
|
495
505
|
Success
|
|
496
506
|
ErrorMessage
|
|
@@ -513,7 +523,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
513
523
|
}
|
|
514
524
|
}
|
|
515
525
|
}
|
|
516
|
-
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return c(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const
|
|
526
|
+
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return c(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const s=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
|
|
517
527
|
SyncData(items: $items) {
|
|
518
528
|
Success
|
|
519
529
|
Results {
|
|
@@ -537,11 +547,11 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
537
547
|
RecordJSON
|
|
538
548
|
}
|
|
539
549
|
}
|
|
540
|
-
}`,{items:e});return
|
|
550
|
+
}`,{items:e});return s&&s.SyncData?s.SyncData:{Success:!1,Results:[]}}catch(t){return c(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const s=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
|
|
541
551
|
SyncRolesAndUsers(data: $data) {
|
|
542
552
|
Success
|
|
543
553
|
}
|
|
544
|
-
}`,{data:e});return
|
|
554
|
+
}`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(t){return c(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
|
|
545
555
|
RunViewByNameSystemUser(input: $input) {
|
|
546
556
|
Results {
|
|
547
557
|
PrimaryKey {
|
|
@@ -558,7 +568,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
558
568
|
ErrorMessage
|
|
559
569
|
Success
|
|
560
570
|
}
|
|
561
|
-
}`,
|
|
571
|
+
}`,s={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},r=await this.Client.request(t,{input:s});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return c(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
|
|
562
572
|
RunViewByIDSystemUser(input: $input) {
|
|
563
573
|
Results {
|
|
564
574
|
PrimaryKey {
|
|
@@ -575,7 +585,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
575
585
|
ErrorMessage
|
|
576
586
|
Success
|
|
577
587
|
}
|
|
578
|
-
}`,
|
|
588
|
+
}`,s={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},r=await this.Client.request(t,{input:s});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return c(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
|
|
579
589
|
RunDynamicViewSystemUser(input: $input) {
|
|
580
590
|
Results {
|
|
581
591
|
PrimaryKey {
|
|
@@ -592,7 +602,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
592
602
|
ErrorMessage
|
|
593
603
|
Success
|
|
594
604
|
}
|
|
595
|
-
}`,
|
|
605
|
+
}`,s={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},r=await this.Client.request(t,{input:s});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return c(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
|
|
596
606
|
RunViewsSystemUser(input: $input) {
|
|
597
607
|
Results {
|
|
598
608
|
PrimaryKey {
|
|
@@ -609,7 +619,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
609
619
|
ErrorMessage
|
|
610
620
|
Success
|
|
611
621
|
}
|
|
612
|
-
}`,
|
|
622
|
+
}`,s=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),r=await this.Client.request(t,{input:s});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return c(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(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 GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
613
623
|
GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
614
624
|
QueryID
|
|
615
625
|
QueryName
|
|
@@ -621,7 +631,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
621
631
|
ErrorMessage
|
|
622
632
|
AppliedParameters
|
|
623
633
|
}
|
|
624
|
-
}`,
|
|
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?$(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 c(`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) {
|
|
625
635
|
GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
626
636
|
QueryID
|
|
627
637
|
QueryName
|
|
@@ -633,7 +643,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
633
643
|
ErrorMessage
|
|
634
644
|
AppliedParameters
|
|
635
645
|
}
|
|
636
|
-
}`,
|
|
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?$(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 c(`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!) {
|
|
637
647
|
CreateQuerySystemUser(input: $input) {
|
|
638
648
|
Success
|
|
639
649
|
ErrorMessage
|
|
@@ -688,7 +698,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
688
698
|
Role
|
|
689
699
|
}
|
|
690
700
|
}
|
|
691
|
-
}`,{input:e});return
|
|
701
|
+
}`,{input:e});return s&&s.CreateQuerySystemUser?s.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return c(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const s=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
|
|
692
702
|
UpdateQuerySystemUser(input: $input) {
|
|
693
703
|
Success
|
|
694
704
|
ErrorMessage
|
|
@@ -743,14 +753,14 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
743
753
|
Role
|
|
744
754
|
}
|
|
745
755
|
}
|
|
746
|
-
}`,{input:e});return
|
|
756
|
+
}`,{input:e});return s&&s.UpdateQuerySystemUser?s.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return c(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return c("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const s=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
|
|
747
757
|
DeleteQuerySystemResolver(ID: $ID, options: $options) {
|
|
748
758
|
Success
|
|
749
759
|
ErrorMessage
|
|
750
760
|
ID
|
|
751
761
|
Name
|
|
752
762
|
}
|
|
753
|
-
}`,
|
|
763
|
+
}`,r={ID:e};t!==void 0&&(r.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(s,r);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(s){let r="";if(s instanceof Error){if(r=s.message,"cause"in s&&s.cause){const n=s.cause;r+=` | Cause: ${n.message||n}`,"code"in n&&(r+=` | Code: ${n.code}`)}if("response"in s){const n=s.response;n?.status&&(r+=` | HTTP Status: ${n.status}`),n?.errors&&(r+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}s.stack&&console.error("DeleteQuery stack trace:",s.stack)}else r=String(s);return c(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r}}}async RunAIPrompt(e){try{const t=y`
|
|
754
764
|
query RunAIPromptSystemUser(
|
|
755
765
|
$promptId: String!,
|
|
756
766
|
$data: String,
|
|
@@ -809,7 +819,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
809
819
|
chatResult
|
|
810
820
|
}
|
|
811
821
|
}
|
|
812
|
-
`,
|
|
822
|
+
`,s=this.preparePromptVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIPromptSystemUser?this.processPromptResult(r.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return c(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=y`
|
|
813
823
|
query RunAIAgentSystemUser(
|
|
814
824
|
$agentId: String!,
|
|
815
825
|
$messages: String!,
|
|
@@ -836,7 +846,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
836
846
|
result
|
|
837
847
|
}
|
|
838
848
|
}
|
|
839
|
-
`,
|
|
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 c(`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 $(e)}async ExecuteSimplePrompt(e){try{const t=y`
|
|
840
850
|
query ExecuteSimplePromptSystemUser(
|
|
841
851
|
$systemPrompt: String!,
|
|
842
852
|
$messages: String,
|
|
@@ -859,7 +869,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
859
869
|
executionTimeMs
|
|
860
870
|
}
|
|
861
871
|
}
|
|
862
|
-
`,
|
|
872
|
+
`,s={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(s.messages=JSON.stringify(e.messages)),e.preferredModels&&(s.preferredModels=e.preferredModels),e.modelPower&&(s.modelPower=e.modelPower),e.responseFormat&&(s.responseFormat=e.responseFormat);const r=await this.Client.request(t,s);if(!r?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=r.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return c(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=y`
|
|
863
873
|
query EmbedTextSystemUser(
|
|
864
874
|
$textToEmbed: [String!]!,
|
|
865
875
|
$modelSize: String!
|
|
@@ -874,7 +884,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
874
884
|
error
|
|
875
885
|
}
|
|
876
886
|
}
|
|
877
|
-
`,
|
|
887
|
+
`,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,r);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return c(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class $e{static{g(this,"GetDataOutput")}}class be{static{g(this,"SimpleRemoteEntityOutput")}}class Ae{static{g(this,"SimpleRemoteEntity")}}class Ne{static{g(this,"SimpleRemoteEntityField")}}class xe{static{g(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,s=!1){try{const r=this.serializeActionParameters(t),n=this.createActionVariables(e,r,s),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(r){return this.handleActionError(r,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let s=t.Value;return s!=null&&typeof s=="object"&&(s=JSON.stringify(s)),{...t,Value:s}})}createActionVariables(e,t,s=!1){return{input:{ActionID:e,Params:t,SkipActionLog:s}}}async executeActionMutation(e){const t=y`
|
|
878
888
|
mutation RunAction($input: RunActionInput!) {
|
|
879
889
|
RunAction(input: $input) {
|
|
880
890
|
Success
|
|
@@ -883,7 +893,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
883
893
|
ResultData
|
|
884
894
|
}
|
|
885
895
|
}
|
|
886
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let
|
|
896
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let s;try{e.RunAction.ResultData&&(s=JSON.parse(e.RunAction.ResultData))}catch(r){c(`Failed to parse action result data: ${r}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:s,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const s=e;return c(`Error running action: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),s=await this.executeEntityActionMutation(t);return this.processEntityActionResult(s)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let s=t.Value;return s!=null&&typeof s=="object"&&(s=JSON.stringify(s)),{Name:t.Name,Value:s,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=y`
|
|
887
897
|
mutation RunEntityAction($input: EntityActionInput!) {
|
|
888
898
|
RunEntityAction(input: $input) {
|
|
889
899
|
Success
|
|
@@ -891,7 +901,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
891
901
|
ResultData
|
|
892
902
|
}
|
|
893
903
|
}
|
|
894
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(
|
|
904
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(s){c(`Failed to parse entity action result data: ${s}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Me{static{g(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),s=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(s)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=y`
|
|
895
905
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
896
906
|
CreateAPIKey(input: $input) {
|
|
897
907
|
Success
|
|
@@ -900,18 +910,18 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
900
910
|
Error
|
|
901
911
|
}
|
|
902
912
|
}
|
|
903
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return c(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=
|
|
913
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return c(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=y`
|
|
904
914
|
mutation RevokeAPIKey($apiKeyId: String!) {
|
|
905
915
|
RevokeAPIKey(apiKeyId: $apiKeyId) {
|
|
906
916
|
Success
|
|
907
917
|
Error
|
|
908
918
|
}
|
|
909
919
|
}
|
|
910
|
-
`,
|
|
920
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return r?.RevokeAPIKey?{Success:r.RevokeAPIKey.Success,Error:r.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const s=t;return c(`Error revoking API key: ${s.message}`),{Success:!1,Error:`Error: ${s.message}`}}}}class Te{static{g(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),s=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isTestCompletionEvent(r,e.testId),"isCompletionEvent"),extractResult:g(r=>this.extractTestResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),s=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isSuiteCompletionEvent(r,e.suiteId),"isCompletionEvent"),extractResult:g(r=>this.extractSuiteResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=y`
|
|
911
921
|
query IsTestRunning($testId: String!) {
|
|
912
922
|
IsTestRunning(testId: $testId)
|
|
913
923
|
}
|
|
914
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return c(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return
|
|
924
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return c(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return y`
|
|
915
925
|
mutation RunTest(
|
|
916
926
|
$testId: String!,
|
|
917
927
|
$verbose: Boolean,
|
|
@@ -934,7 +944,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
934
944
|
result
|
|
935
945
|
}
|
|
936
946
|
}
|
|
937
|
-
`}buildRunTestSuiteMutation(){return
|
|
947
|
+
`}buildRunTestSuiteMutation(){return y`
|
|
938
948
|
mutation RunTestSuite(
|
|
939
949
|
$suiteId: String!,
|
|
940
950
|
$verbose: Boolean,
|
|
@@ -965,7 +975,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
965
975
|
result
|
|
966
976
|
}
|
|
967
977
|
}
|
|
968
|
-
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,
|
|
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?$(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?$(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 c(`${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 Fe{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y`
|
|
969
979
|
query GetRegistryComponent(
|
|
970
980
|
$registryName: String!,
|
|
971
981
|
$namespace: String!,
|
|
@@ -986,7 +996,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
986
996
|
specification
|
|
987
997
|
}
|
|
988
998
|
}
|
|
989
|
-
`,
|
|
999
|
+
`,s={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(s.version=e.version),e.hash!==void 0&&(s.hash=e.hash);const r=await this._dataProvider.ExecuteGQL(t,s);if(r&&r.GetRegistryComponent){const n=r.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return c(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw c(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=y`
|
|
990
1000
|
query GetRegistryComponent(
|
|
991
1001
|
$registryName: String!,
|
|
992
1002
|
$namespace: String!,
|
|
@@ -1007,7 +1017,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1007
1017
|
specification
|
|
1008
1018
|
}
|
|
1009
1019
|
}
|
|
1010
|
-
`,
|
|
1020
|
+
`,s={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(s.version=e.version),e.hash!==void 0&&(s.hash=e.hash);const r=await this._dataProvider.ExecuteGQL(t,s);if(r&&r.GetRegistryComponent){const n=r.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){c(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=y`
|
|
1011
1021
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
1012
1022
|
SearchRegistryComponents(params: $params) {
|
|
1013
1023
|
components
|
|
@@ -1016,7 +1026,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1016
1026
|
limit
|
|
1017
1027
|
}
|
|
1018
1028
|
}
|
|
1019
|
-
`,
|
|
1029
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{params:e});if(s&&s.SearchRegistryComponents){const r=s.SearchRegistryComponents;return{components:r.components.map(n=>JSON.parse(n)),total:r.total,offset:r.offset,limit:r.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw c(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const s=y`
|
|
1020
1030
|
query ResolveComponentDependencies(
|
|
1021
1031
|
$registryId: String!,
|
|
1022
1032
|
$componentId: String!
|
|
@@ -1041,7 +1051,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1041
1051
|
}
|
|
1042
1052
|
}
|
|
1043
1053
|
}
|
|
1044
|
-
`,
|
|
1054
|
+
`,r=await this._dataProvider.ExecuteGQL(s,{registryId:e,componentId:t});return r&&r.ResolveComponentDependencies?r.ResolveComponentDependencies:null}catch(s){throw c(s),new Error(`Failed to resolve component dependencies: ${s instanceof Error?s.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,s){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:s,version:"latest"}))?.version||null}catch(r){return c(r),null}}async SendComponentFeedback(e){try{const t=y`
|
|
1045
1055
|
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
1046
1056
|
SendComponentFeedback(feedback: $feedback) {
|
|
1047
1057
|
success
|
|
@@ -1049,7 +1059,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1049
1059
|
error
|
|
1050
1060
|
}
|
|
1051
1061
|
}
|
|
1052
|
-
`,
|
|
1062
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{feedback:e});return s&&s.SendComponentFeedback?s.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Le{static{g(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const s=y`
|
|
1053
1063
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1054
1064
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1055
1065
|
Success
|
|
@@ -1065,7 +1075,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1065
1075
|
}
|
|
1066
1076
|
}
|
|
1067
1077
|
}
|
|
1068
|
-
`,
|
|
1078
|
+
`,r={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(s,r);return this.processResult(n)}catch(s){const r=s instanceof Error?s.message:String(s);return c(`GraphQLVersionHistoryClient.CreateLabel error: ${r}`),{Success:!1,Error:r}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(s=>({Key:s.Key,Value:s.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const s=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(r=>({EntityName:r.EntityName??"",RecordID:r.RecordID??"",ErrorMessage:r.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:s}}}class Qe{static{g(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",s){try{const r=y`
|
|
1069
1079
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1070
1080
|
ListStorageObjects(input: $input) {
|
|
1071
1081
|
objects {
|
|
@@ -1082,34 +1092,34 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1082
1092
|
prefixes
|
|
1083
1093
|
}
|
|
1084
1094
|
}
|
|
1085
|
-
`,n={input:{AccountID:e,Prefix:t,Delimiter:
|
|
1095
|
+
`,n={input:{AccountID:e,Prefix:t,Delimiter:s||"/"}},a=await this._dataProvider.ExecuteGQL(r,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(r){const n=r;throw c(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const s=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return s.objects.length>0||s.prefixes.length>0}catch(s){return c(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const s=y`
|
|
1086
1096
|
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1087
1097
|
CreateDirectory(input: $input)
|
|
1088
1098
|
}
|
|
1089
|
-
`,
|
|
1099
|
+
`,r={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(s,r))?.CreateDirectory??!1}catch(s){return c(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const s=t.substring(0,t.lastIndexOf("/")+1),r=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,s,"/")).objects.some(a=>a.name===r||a.fullPath===t)}catch(s){return c(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,s){try{const r=y`
|
|
1090
1100
|
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1091
1101
|
CreatePreAuthUploadUrl(input: $input) {
|
|
1092
1102
|
UploadUrl
|
|
1093
1103
|
ProviderKey
|
|
1094
1104
|
}
|
|
1095
1105
|
}
|
|
1096
|
-
`,n={input:{AccountID:e,ObjectName:t,ContentType:
|
|
1106
|
+
`,n={input:{AccountID:e,ObjectName:t,ContentType:s}},a=await this._dataProvider.ExecuteGQL(r,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(r){const n=r;throw c(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const s=y`
|
|
1097
1107
|
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1098
1108
|
CreatePreAuthDownloadUrl(input: $input)
|
|
1099
1109
|
}
|
|
1100
|
-
`,
|
|
1110
|
+
`,r={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(s,r);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(s){const r=s;throw c(`Error creating pre-auth download URL: ${r}`),r}}async DeleteObject(e,t){try{const s=y`
|
|
1101
1111
|
mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
|
|
1102
1112
|
DeleteStorageObject(input: $input)
|
|
1103
1113
|
}
|
|
1104
|
-
`,
|
|
1114
|
+
`,r={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(s,r))?.DeleteStorageObject??!1}catch(s){return c(`Error deleting storage object: ${s}`),!1}}async MoveObject(e,t,s){try{const r=y`
|
|
1105
1115
|
mutation MoveStorageObject($input: MoveStorageObjectInput!) {
|
|
1106
1116
|
MoveStorageObject(input: $input)
|
|
1107
1117
|
}
|
|
1108
|
-
`,n={input:{AccountID:e,OldName:t,NewName:
|
|
1118
|
+
`,n={input:{AccountID:e,OldName:t,NewName:s}};return(await this._dataProvider.ExecuteGQL(r,n))?.MoveStorageObject??!1}catch(r){return c(`Error moving storage object: ${r}`),!1}}async CopyObject(e,t,s){try{const r=y`
|
|
1109
1119
|
mutation CopyStorageObject($input: CopyStorageObjectInput!) {
|
|
1110
1120
|
CopyStorageObject(input: $input)
|
|
1111
1121
|
}
|
|
1112
|
-
`,n={input:{AccountID:e,SourceName:t,DestinationName:
|
|
1122
|
+
`,n={input:{AccountID:e,SourceName:t,DestinationName:s}};return(await this._dataProvider.ExecuteGQL(r,n))?.CopyStorageObject??!1}catch(r){return c(`Error copying storage object: ${r}`),!1}}async CopyObjectBetweenAccounts(e,t,s,r){try{const n=y`
|
|
1113
1123
|
mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
|
|
1114
1124
|
CopyObjectBetweenAccounts(input: $input) {
|
|
1115
1125
|
success
|
|
@@ -1121,7 +1131,7 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1121
1131
|
destinationPath
|
|
1122
1132
|
}
|
|
1123
1133
|
}
|
|
1124
|
-
`,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:
|
|
1134
|
+
`,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:s,DestinationPath:r}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return c(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:s,destinationPath:r}}}async SearchFiles(e,t,s){try{const r=y`
|
|
1125
1135
|
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1126
1136
|
SearchAcrossAccounts(input: $input) {
|
|
1127
1137
|
accountResults {
|
|
@@ -1149,5 +1159,99 @@ var j=Object.defineProperty;var p=(h,e)=>j(h,"name",{value:e,configurable:!0});i
|
|
|
1149
1159
|
failedAccounts
|
|
1150
1160
|
}
|
|
1151
1161
|
}
|
|
1152
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:
|
|
1162
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:s?.maxResultsPerAccount,FileTypes:s?.fileTypes,SearchContent:s?.searchContent}},a=await this._dataProvider.ExecuteGQL(r,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(r){return c(`Error searching across accounts: ${r}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ue{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=y`
|
|
1163
|
+
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1164
|
+
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1165
|
+
Success
|
|
1166
|
+
Message
|
|
1167
|
+
Objects {
|
|
1168
|
+
Name
|
|
1169
|
+
Label
|
|
1170
|
+
SupportsIncrementalSync
|
|
1171
|
+
SupportsWrite
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
`,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationDiscoverObjects;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,Data:r.Objects??[]}}catch(t){return this.handleError(t,[])}}async DiscoverFields(e,t){try{const s=y`
|
|
1176
|
+
query IntegrationDiscoverFields($companyIntegrationID: String!, $objectName: String!) {
|
|
1177
|
+
IntegrationDiscoverFields(companyIntegrationID: $companyIntegrationID, objectName: $objectName) {
|
|
1178
|
+
Success
|
|
1179
|
+
Message
|
|
1180
|
+
Fields {
|
|
1181
|
+
Name
|
|
1182
|
+
Label
|
|
1183
|
+
DataType
|
|
1184
|
+
IsRequired
|
|
1185
|
+
IsUniqueKey
|
|
1186
|
+
IsReadOnly
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
`,n=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t}))?.IntegrationDiscoverFields;if(!n)throw new Error("Invalid response from server");return{Success:n.Success,Message:n.Message,Data:n.Fields??[]}}catch(s){return this.handleError(s,[])}}async TestConnection(e){try{const t=y`
|
|
1191
|
+
query IntegrationTestConnection($companyIntegrationID: String!) {
|
|
1192
|
+
IntegrationTestConnection(companyIntegrationID: $companyIntegrationID) {
|
|
1193
|
+
Success
|
|
1194
|
+
Message
|
|
1195
|
+
ServerVersion
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
`,r=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!r)throw new Error("Invalid response from server");return{Success:r.Success,Message:r.Message,ServerVersion:r.ServerVersion??null}}catch(t){const s=t;return c(`Error testing integration connection: ${s}`),{Success:!1,Message:`Error: ${s.message}`,ServerVersion:null}}}async SchemaPreview(e,t,s="sqlserver"){try{const r=y`
|
|
1199
|
+
query IntegrationSchemaPreview(
|
|
1200
|
+
$companyIntegrationID: String!,
|
|
1201
|
+
$objects: [SchemaPreviewObjectInput!]!,
|
|
1202
|
+
$platform: String!
|
|
1203
|
+
) {
|
|
1204
|
+
IntegrationSchemaPreview(
|
|
1205
|
+
companyIntegrationID: $companyIntegrationID,
|
|
1206
|
+
objects: $objects,
|
|
1207
|
+
platform: $platform
|
|
1208
|
+
) {
|
|
1209
|
+
Success
|
|
1210
|
+
Message
|
|
1211
|
+
Files {
|
|
1212
|
+
FilePath
|
|
1213
|
+
Content
|
|
1214
|
+
Description
|
|
1215
|
+
}
|
|
1216
|
+
Warnings
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
`,a=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objects:t,platform:s}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(r){const n=r;return c(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,s=5){try{const r=y`
|
|
1220
|
+
query IntegrationPreviewData(
|
|
1221
|
+
$companyIntegrationID: String!,
|
|
1222
|
+
$objectName: String!,
|
|
1223
|
+
$limit: Float!
|
|
1224
|
+
) {
|
|
1225
|
+
IntegrationPreviewData(
|
|
1226
|
+
companyIntegrationID: $companyIntegrationID,
|
|
1227
|
+
objectName: $objectName,
|
|
1228
|
+
limit: $limit
|
|
1229
|
+
) {
|
|
1230
|
+
Success
|
|
1231
|
+
Message
|
|
1232
|
+
Records {
|
|
1233
|
+
Data
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
`,a=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objectName:t,limit:s}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(r){const n=r;return c(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=y`
|
|
1238
|
+
query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
|
|
1239
|
+
IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
|
|
1240
|
+
Success
|
|
1241
|
+
Message
|
|
1242
|
+
DefaultSchemaName
|
|
1243
|
+
DefaultObjects {
|
|
1244
|
+
SourceObjectName
|
|
1245
|
+
TargetTableName
|
|
1246
|
+
TargetEntityName
|
|
1247
|
+
SyncEnabled
|
|
1248
|
+
FieldMappings {
|
|
1249
|
+
SourceFieldName
|
|
1250
|
+
DestinationFieldName
|
|
1251
|
+
IsKeyField
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
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 c(`Error getting default config: ${s}`),{Success:!1,Message:`Error: ${s.message}`}}}handleError(e,t){const s=e;return c(`Error in integration discovery: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Data:t}}}export{we as ActionItemInput,Ce as ActionItemOutput,j as BrowserIndexedDBStorageProvider,k as BrowserStorageProviderBase,w as FieldMapper,P as FireAndForgetHelper,$e as GetDataOutput,q as GraphQLAIClient,xe as GraphQLActionClient,Fe as GraphQLComponentRegistryClient,f as GraphQLDataProvider,Me as GraphQLEncryptionClient,Qe as GraphQLFileStorageClient,Ue as GraphQLIntegrationClient,Se as GraphQLProviderConfigData,Pe as GraphQLSystemUserClient,Te as GraphQLTestingClient,O as GraphQLTransactionGroup,Le as GraphQLVersionHistoryClient,Re as RoleInput,De as RolesAndUsersInput,Ae as SimpleRemoteEntity,Ne as SimpleRemoteEntityField,be as SimpleRemoteEntityOutput,J as SyncDataAction,ve as SyncDataResult,Ie as SyncRolesAndUsersResult,Ee as UserInput,ze as gql,fe as setupGraphQLClient};
|
|
1153
1257
|
//# sourceMappingURL=index.mjs.map
|