@memberjunction/graphql-dataprovider 5.13.0 → 5.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +192 -177
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +128 -149
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +128 -149
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +196 -181
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var V=Object.defineProperty;var g=(S,e)=>V(S,"name",{value:e,configurable:!0});var d=require("graphql-request"),u=require("@memberjunction/core"),
|
|
1
|
+
"use strict";var V=Object.defineProperty;var g=(S,e)=>V(S,"name",{value:e,configurable:!0});var d=require("graphql-request"),u=require("@memberjunction/core"),R=require("@memberjunction/global"),N=require("@memberjunction/core-entities"),b=require("rxjs"),G=require("graphql-ws"),q=require("uuid"),_=require("@tempfix/idb");class v{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(v.DB_PREFIX)?v.GQL_PREFIX+e.substring(v.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(v.GQL_PREFIX)?v.DB_PREFIX+e.substring(v.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class x extends u.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=d.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],c=R.SafeJSONParse(a),l=this.PendingTransactions[i];o.push(new u.TransactionResult(l,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class ${static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:o,reject:i}=$.createCompletionPromise();s=$.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=$.subscribeToPubSub(e,o,s);const a=await $.executeMutation(e);if(!e.validateAck(a)){s&&clearTimeout(s);const c=a?.errorMessage??"Server rejected the request";return u.LogError(`[FireAndForget:${t}] Server rejected: ${c}`),e.createErrorResult(c)}return u.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const o=n;throw u.LogError(`[FireAndForget:${t}] Error: ${o.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=r??"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))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(o=>{try{const i=JSON.parse(o);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),u.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class L{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=d.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
chatResult
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,
|
|
68
|
+
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await $.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:g(o=>o?.success===!0,"validateAck"),isCompletionEvent:g(o=>this.isAgentCompletionEvent(o),"isCompletionEvent"),extractResult:g(o=>this.extractAgentResult(o),"extractResult"),onMessage:e.onProgress?o=>this.forwardAgentProgress(o,e.onProgress):void 0,createErrorResult:g(o=>this.createAgentErrorResult(o),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return d.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -106,7 +106,7 @@
|
|
|
106
106
|
result
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
|
-
`}prepareAgentVariables(e,t,
|
|
109
|
+
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);u.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let o;return s?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=r,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:g(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,createErrorResult:g(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return d.gql`
|
|
110
110
|
mutation RunAIAgentFromConversationDetail(
|
|
111
111
|
$conversationDetailId: String!,
|
|
112
112
|
$agentId: String!,
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
result
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const
|
|
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 r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?R.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=d.gql`
|
|
149
149
|
mutation ExecuteSimplePrompt(
|
|
150
150
|
$systemPrompt: String!,
|
|
151
151
|
$messages: String,
|
|
@@ -168,7 +168,7 @@
|
|
|
168
168
|
executionTimeMs
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
|
-
`,
|
|
171
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=d.gql`
|
|
172
172
|
mutation EmbedText(
|
|
173
173
|
$textToEmbed: [String!]!,
|
|
174
174
|
$modelSize: String!
|
|
@@ -183,7 +183,7 @@
|
|
|
183
183
|
error
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
`,
|
|
186
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const P="default";class T{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||P;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||P).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Q="Metadata_KVPairs";class F extends T{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(Q)&&e.deleteObjectStore(Q);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||P;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const a=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends u.ProviderConfigDataBase{static{g(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,o,i,a,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:s},n,o,i)}}class h extends u.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
|
|
187
187
|
${this.userInfoString()}
|
|
188
188
|
MJUserRoles_UserIDArray {
|
|
189
189
|
${this.userRoleInfoString()}
|
|
@@ -192,7 +192,7 @@
|
|
|
192
192
|
`,this._currentUserQuery=d.gql`query CurrentUserAndRoles {
|
|
193
193
|
${this._innerCurrentUserQueryString}
|
|
194
194
|
CurrentUserTenantContext
|
|
195
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const
|
|
195
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new L(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return q.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.set(e,t),h.Instance._client&&h.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.delete(e),h.Instance._client&&h.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new u.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=d.gql`
|
|
196
196
|
query GetReportDataQuery ($ReportID: String!) {
|
|
197
197
|
GetReportData(ReportID: $ReportID) {
|
|
198
198
|
Success
|
|
@@ -201,31 +201,31 @@
|
|
|
201
201
|
ExecutionTime
|
|
202
202
|
ErrorMessage
|
|
203
203
|
}
|
|
204
|
-
}`,
|
|
204
|
+
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async 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,r){const s=d.gql`
|
|
205
205
|
query ExecuteAdhocQuery($input: AdhocQueryInput!) {
|
|
206
206
|
ExecuteAdhocQuery(input: $input) {
|
|
207
207
|
${this.QueryReturnFieldList}
|
|
208
208
|
}
|
|
209
209
|
}
|
|
210
|
-
`,n={SQL:e};
|
|
210
|
+
`,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const o=await this.ExecuteGQL(s,{input:n});return o?.ExecuteAdhocQuery?this.TransformQueryPayload(o.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 r=d.gql`
|
|
211
211
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
212
212
|
RunQueries(input: $input) {
|
|
213
213
|
${this.QueryReturnFieldList}
|
|
214
214
|
}
|
|
215
215
|
}
|
|
216
|
-
`,
|
|
216
|
+
`,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i){const a=d.gql`
|
|
217
217
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
218
218
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
219
219
|
${this.QueryReturnFieldList}
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
-
`,c={QueryID:e};t!==void 0&&(c.CategoryID=t),
|
|
222
|
+
`,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const l=await this.ExecuteGQL(a,c);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i){const a=d.gql`
|
|
223
223
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
224
224
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
225
225
|
${this.QueryReturnFieldList}
|
|
226
226
|
}
|
|
227
227
|
}
|
|
228
|
-
`,c={QueryName:e};t!==void 0&&(c.CategoryID=t),
|
|
228
|
+
`,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const l=await this.ExecuteGQL(a,c);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
229
229
|
Success
|
|
230
230
|
QueryID
|
|
231
231
|
QueryName
|
|
@@ -234,7 +234,7 @@
|
|
|
234
234
|
TotalRowCount
|
|
235
235
|
ExecutionTime
|
|
236
236
|
ErrorMessage
|
|
237
|
-
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const
|
|
237
|
+
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=d.gql`
|
|
238
238
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
239
239
|
RunQueriesWithCacheCheck(input: $input) {
|
|
240
240
|
success
|
|
@@ -250,7 +250,7 @@
|
|
|
250
250
|
}
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
-
`,o=(await this.ExecuteGQL(
|
|
253
|
+
`,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const c=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:c,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:p,v:I}=await this.getEntityNameAndUserView(e,t);i=I,o=p}const a=this.Entities.find(p=>p.Name===o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const l=u.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${l}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const f=this.getViewRunTimeFieldList(a,i,e,c),E=e.Aggregates&&e.Aggregates.length>0?`
|
|
254
254
|
AggregateResults {
|
|
255
255
|
alias
|
|
256
256
|
expression
|
|
@@ -258,8 +258,8 @@
|
|
|
258
258
|
error
|
|
259
259
|
}
|
|
260
260
|
AggregateExecutionTime`:"",y=d.gql`
|
|
261
|
-
query RunViewQuery ($input: ${
|
|
262
|
-
${
|
|
261
|
+
query RunViewQuery ($input: ${s}!) {
|
|
262
|
+
${r}(input: $input) {
|
|
263
263
|
Results {
|
|
264
264
|
${f.join(`
|
|
265
265
|
`)}
|
|
@@ -271,7 +271,7 @@
|
|
|
271
271
|
Success
|
|
272
272
|
ErrorMessage${E}
|
|
273
273
|
}
|
|
274
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:
|
|
274
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[r]){const p=m[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[r].AggregateExecutionTime});const I=m[r].Results;if(I&&I.length>0){const C=a.Fields.filter(w=>w.CodeName!==w.Name&&w.CodeName!==void 0);I.forEach(w=>{this.ConvertBackToMJFields(w),C.forEach(A=>{w[A.Name]=w[A.CodeName]})})}return m[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let f="",E="";const y={};let m=null,p=null;if(l.ViewEntity)p=l.ViewEntity,m=p.Get("Entity");else{const{entityName:w,v:A}=await this.getEntityNameAndUserView(l,t);p=A,m=w}const I=this.Entities.find(w=>w.Name===m);if(!I)throw new Error(`Entity ${m} not found in metadata`);s.push(I);let D=!1;const C=u.getGraphQLTypeNameBase(I);l.ViewID?(f=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=l.ViewID):l.ViewName?(f=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=l.ViewName):(D=!0,f=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=l.EntityName),y.ExtraFilter=l.ExtraFilter||"",y.OrderBy=l.OrderBy||"",y.UserSearchString=l.UserSearchString||"",y.Fields=l.Fields,y.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(y.MaxRows=l.MaxRows),l.StartRow!==void 0&&(y.StartRow=l.StartRow),y.ForceAuditLog=l.ForceAuditLog||!1,y.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(y.AuditLogDescription=l.AuditLogDescription),D||(y.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=l.OverrideExcludeFilter||"",y.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(y.Aggregates=l.Aggregates.map(w=>({expression:w.expression,alias:w.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(I,p,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
275
275
|
AggregateResults {
|
|
276
276
|
alias
|
|
277
277
|
expression
|
|
@@ -296,7 +296,7 @@
|
|
|
296
296
|
Success
|
|
297
297
|
ErrorMessage${i}
|
|
298
298
|
}
|
|
299
|
-
}`,c=await this.ExecuteGQL(a,{input:
|
|
299
|
+
}`,c=await this.ExecuteGQL(a,{input:r});if(c&&c.RunViews){const l=c.RunViews;for(const[f,E]of l.entries())E.Results=E.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return l}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=d.gql`
|
|
300
300
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
301
301
|
RunViewsWithCacheCheck(input: $input) {
|
|
302
302
|
success
|
|
@@ -329,7 +329,7 @@
|
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
331
|
}
|
|
332
|
-
`,o=(await this.ExecuteGQL(
|
|
332
|
+
`,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,c)=>{const l=e[c];if(a.status==="differential"&&a.differentialData){const f=a.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const f=a.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:f,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await N.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await N.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],o=new v;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(o.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=d.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
333
333
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
334
334
|
EntityName
|
|
335
335
|
RelatedEntityName
|
|
@@ -341,7 +341,7 @@
|
|
|
341
341
|
}
|
|
342
342
|
}
|
|
343
343
|
}
|
|
344
|
-
}`,
|
|
344
|
+
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=d.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
345
345
|
GetRecordDuplicates(params: $params) {
|
|
346
346
|
Status
|
|
347
347
|
ErrorMessage
|
|
@@ -363,7 +363,7 @@
|
|
|
363
363
|
}
|
|
364
364
|
}
|
|
365
365
|
}
|
|
366
|
-
}`;let
|
|
366
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=d.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
367
367
|
MergeRecords(request: $request) {
|
|
368
368
|
Success
|
|
369
369
|
OverallStatus
|
|
@@ -380,32 +380,32 @@
|
|
|
380
380
|
Message
|
|
381
381
|
}
|
|
382
382
|
}
|
|
383
|
-
}`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,
|
|
383
|
+
}`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=u.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),l=new v,f=` ${a}(input: $input) {
|
|
384
384
|
${e.Fields.map(y=>l.MapFieldName(y.CodeName)).join(`
|
|
385
385
|
`)}
|
|
386
386
|
}`,E=d.gql`mutation ${o}${i} ($input: ${a}Input!) {
|
|
387
387
|
${f}
|
|
388
388
|
}
|
|
389
|
-
`;for(let y=0;y<c.length;y++){const m=c[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:p=p.getTime();break;case u.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case u.EntityFieldTSType.Number:if(typeof p!="number"){const I=Number(p);isNaN(I)||(p=I)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===u.EntityFieldTSType.Number||m.FieldType===u.EntityFieldTSType.Boolean?p=0:p=""),n.input[l.MapFieldName(m.CodeName)]=p}if(o.trim().toLowerCase()==="update"&&
|
|
389
|
+
`;for(let y=0;y<c.length;y++){const m=c[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:p=p.getTime();break;case u.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case u.EntityFieldTSType.Number:if(typeof p!="number"){const I=Number(p);isNaN(I)||(p=I)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===u.EntityFieldTSType.Number||m.FieldType===u.EntityFieldTSType.Boolean?p=0:p=""),n.input[l.MapFieldName(m.CodeName)]=p}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:l.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:a,mutationInputTypes:y},(m,p)=>{s.EndedAt=new Date,p&&m?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(m)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),I=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${m.CodeName}: $${m.CodeName}`,m.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),l=new v,f=d.gql`query Single${c}${a.length>0?"Full":""} (${i}) {
|
|
390
390
|
${c}(${o}) {
|
|
391
391
|
${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
|
|
392
392
|
`)}
|
|
393
393
|
${a}
|
|
394
394
|
}
|
|
395
395
|
}
|
|
396
|
-
`,E=await this.ExecuteGQL(f,n);return E&&E[c]?this.ConvertBackToMJFields(E[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let
|
|
396
|
+
`,E=await this.ExecuteGQL(f,n);return E&&E[c]?this.ConvertBackToMJFields(E[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],o=this.Entities.find(a=>R.UUIDsEqual(a.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
397
397
|
${i} {
|
|
398
398
|
${o.Fields.map(a=>a.CodeName).join(`
|
|
399
399
|
`)}
|
|
400
400
|
}
|
|
401
|
-
`}return
|
|
401
|
+
`}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.ResultHistory.push(s);const n={},o=[];let i="",a="",c="";for(let m of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(I=>I.Name.trim().toLowerCase()===m.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,o.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,a.length>0&&(a+=", "),a+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
|
|
402
402
|
`),c+=`${p.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),E=d.gql`${f}(${i}, options___: $options___) {
|
|
403
403
|
${c}
|
|
404
404
|
}
|
|
405
405
|
`,y=d.gql`mutation ${f} (${a}, $options___: DeleteOptionsInput!) {
|
|
406
406
|
${E}
|
|
407
407
|
}
|
|
408
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",E,n,{mutationName:f,mutationInputTypes:o},(m,p)=>{if(
|
|
408
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",E,n,{mutationName:f,mutationInputTypes:o},(m,p)=>{if(s.EndedAt=new Date,p&&m){let I=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==m[D.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[f]){const p=m[f];for(let I of e.PrimaryKey.KeyValuePairs){let D=p[I.FieldName],C=I.Value;if(typeof C=="number"&&(C=C.toString()),typeof D=="number"&&(D=D.toString()),C!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=d.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
409
409
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
410
410
|
DatasetID
|
|
411
411
|
DatasetName
|
|
@@ -414,7 +414,7 @@
|
|
|
414
414
|
LatestUpdateDate
|
|
415
415
|
Results
|
|
416
416
|
}
|
|
417
|
-
}`,
|
|
417
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=d.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
418
418
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
419
419
|
DatasetID
|
|
420
420
|
DatasetName
|
|
@@ -423,22 +423,22 @@
|
|
|
423
423
|
LatestUpdateDate
|
|
424
424
|
EntityUpdateDates
|
|
425
425
|
}
|
|
426
|
-
}`,
|
|
426
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new x(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(a=>a.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=d.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
427
427
|
GetRecordFavoriteStatus(params: $params) {
|
|
428
428
|
Success
|
|
429
429
|
IsFavorite
|
|
430
430
|
}
|
|
431
|
-
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(
|
|
431
|
+
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=d.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
432
432
|
SetRecordFavoriteStatus(params: $params){
|
|
433
433
|
Success
|
|
434
434
|
}
|
|
435
|
-
}`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(
|
|
435
|
+
}`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(a&&a.SetRecordFavoriteStatus!==null)return a.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=d.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
436
436
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
437
437
|
Success
|
|
438
438
|
Status
|
|
439
439
|
RecordName
|
|
440
440
|
}
|
|
441
|
-
}`,
|
|
441
|
+
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async InternalGetEntityRecordNames(e){if(!e)return null;const t=d.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
442
442
|
GetEntityRecordNames(info: $info) {
|
|
443
443
|
Success
|
|
444
444
|
Status
|
|
@@ -451,28 +451,28 @@
|
|
|
451
451
|
EntityName
|
|
452
452
|
RecordName
|
|
453
453
|
}
|
|
454
|
-
}`,
|
|
454
|
+
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new u.CompositeKey(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=d.gql`query GetDataContextData ($DataContextID: String!) {
|
|
455
455
|
GetDataContextData(DataContextID: $DataContextID) {
|
|
456
456
|
Success
|
|
457
457
|
ErrorMessages
|
|
458
458
|
Results
|
|
459
459
|
}
|
|
460
|
-
}`,
|
|
460
|
+
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=d.gql`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
461
461
|
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
462
462
|
Success
|
|
463
463
|
ErrorMessage
|
|
464
464
|
Result
|
|
465
465
|
}
|
|
466
|
-
}`,
|
|
467
|
-
`:
|
|
468
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new
|
|
466
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n);const i=new d.GraphQLClient(e,{headers:o});for(const[a,c]of this._dynamicHeaders)i.setHeader(a,c);return i}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
467
|
+
`:s.startsWith("_")||(t+=s+`
|
|
468
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new F:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new b.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:g(o=>{r.next(o.data)},"next"),error:g(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},"error"),complete:g(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new b.Observable(a=>{r.activeSubscribers++;const c=r.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,c.unsubscribe()}});const s=d.gql`subscription StatusUpdates($sessionId: String!) {
|
|
469
469
|
statusUpdates(sessionId: $sessionId) {
|
|
470
470
|
date
|
|
471
471
|
message
|
|
472
472
|
sessionId
|
|
473
473
|
}
|
|
474
474
|
}
|
|
475
|
-
`,n=new b.Subject,o=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(a=>{const c=o.subscribe({query:
|
|
475
|
+
`,n=new b.Subject,o=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(a=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:g(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:g(async l=>{const f=l;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(l)},"error"),complete:g(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:g(a=>n.next(a),"next"),error:g(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(a=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const l=n.subscribe(a);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=d.gql`subscription CacheInvalidation {
|
|
476
476
|
cacheInvalidation {
|
|
477
477
|
EntityName
|
|
478
478
|
PrimaryKeyValues
|
|
@@ -482,26 +482,26 @@
|
|
|
482
482
|
OriginSessionID
|
|
483
483
|
RecordData
|
|
484
484
|
}
|
|
485
|
-
}`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(
|
|
485
|
+
}`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.ComponentEvent,eventCode:u.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),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,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
|
|
486
486
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
487
487
|
Success
|
|
488
488
|
ChildEntityName
|
|
489
489
|
ErrorMessage
|
|
490
490
|
}
|
|
491
|
-
}`;try{const n=await this.ExecuteGQL(
|
|
491
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return u.LogError(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
|
|
492
492
|
FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
|
|
493
493
|
Success
|
|
494
494
|
ChildEntityNames
|
|
495
495
|
ErrorMessage
|
|
496
496
|
}
|
|
497
|
-
}`;try{const n=await this.ExecuteGQL(
|
|
497
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(S){const e=new h;return u.SetProvider(e),await e.Config(S),await u.StartupManager.Instance.Startup(),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class H{static{g(this,"UserInput")}}class z{static{g(this,"RolesAndUsersInput")}}var U=(S=>(S.Create="Create",S.Update="Update",S.CreateOrUpdate="CreateOrUpdate",S.Delete="Delete",S.DeleteWithFilter="DeleteWithFilter",S))(U||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new d.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return u.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
498
498
|
GetData(input: $input) {
|
|
499
499
|
Success
|
|
500
500
|
ErrorMessages
|
|
501
501
|
Queries
|
|
502
502
|
Results
|
|
503
503
|
}
|
|
504
|
-
}`,{input:{Queries:e,Token:t}});return
|
|
504
|
+
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
505
505
|
GetAllEntities {
|
|
506
506
|
Success
|
|
507
507
|
ErrorMessage
|
|
@@ -524,7 +524,7 @@
|
|
|
524
524
|
}
|
|
525
525
|
}
|
|
526
526
|
}
|
|
527
|
-
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const
|
|
527
|
+
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
|
|
528
528
|
SyncData(items: $items) {
|
|
529
529
|
Success
|
|
530
530
|
Results {
|
|
@@ -548,11 +548,11 @@
|
|
|
548
548
|
RecordJSON
|
|
549
549
|
}
|
|
550
550
|
}
|
|
551
|
-
}`,{items:e});return
|
|
551
|
+
}`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
|
|
552
552
|
SyncRolesAndUsers(data: $data) {
|
|
553
553
|
Success
|
|
554
554
|
}
|
|
555
|
-
}`,{data:e});return
|
|
555
|
+
}`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
|
|
556
556
|
RunViewByNameSystemUser(input: $input) {
|
|
557
557
|
Results {
|
|
558
558
|
PrimaryKey {
|
|
@@ -569,7 +569,7 @@
|
|
|
569
569
|
ErrorMessage
|
|
570
570
|
Success
|
|
571
571
|
}
|
|
572
|
-
}`,
|
|
572
|
+
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
|
|
573
573
|
RunViewByIDSystemUser(input: $input) {
|
|
574
574
|
Results {
|
|
575
575
|
PrimaryKey {
|
|
@@ -586,7 +586,7 @@
|
|
|
586
586
|
ErrorMessage
|
|
587
587
|
Success
|
|
588
588
|
}
|
|
589
|
-
}`,
|
|
589
|
+
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
|
|
590
590
|
RunDynamicViewSystemUser(input: $input) {
|
|
591
591
|
Results {
|
|
592
592
|
PrimaryKey {
|
|
@@ -603,7 +603,7 @@
|
|
|
603
603
|
ErrorMessage
|
|
604
604
|
Success
|
|
605
605
|
}
|
|
606
|
-
}`,
|
|
606
|
+
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
|
|
607
607
|
RunViewsSystemUser(input: $input) {
|
|
608
608
|
Results {
|
|
609
609
|
PrimaryKey {
|
|
@@ -620,7 +620,7 @@
|
|
|
620
620
|
ErrorMessage
|
|
621
621
|
Success
|
|
622
622
|
}
|
|
623
|
-
}`,
|
|
623
|
+
}`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return u.LogError(`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) {
|
|
624
624
|
GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
625
625
|
QueryID
|
|
626
626
|
QueryName
|
|
@@ -632,7 +632,7 @@
|
|
|
632
632
|
ErrorMessage
|
|
633
633
|
AppliedParameters
|
|
634
634
|
}
|
|
635
|
-
}`,
|
|
635
|
+
}`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?R.SafeJSONParse(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
636
636
|
GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
637
637
|
QueryID
|
|
638
638
|
QueryName
|
|
@@ -644,126 +644,132 @@
|
|
|
644
644
|
ErrorMessage
|
|
645
645
|
AppliedParameters
|
|
646
646
|
}
|
|
647
|
-
}`,
|
|
647
|
+
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?R.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
|
|
648
648
|
CreateQuerySystemUser(input: $input) {
|
|
649
649
|
Success
|
|
650
650
|
ErrorMessage
|
|
651
|
-
|
|
652
|
-
Name
|
|
653
|
-
Description
|
|
654
|
-
CategoryID
|
|
655
|
-
Category
|
|
656
|
-
SQL
|
|
657
|
-
Status
|
|
658
|
-
QualityRank
|
|
659
|
-
EmbeddingVector
|
|
660
|
-
EmbeddingModelID
|
|
661
|
-
EmbeddingModelName
|
|
662
|
-
TechnicalDescription
|
|
663
|
-
Fields {
|
|
664
|
-
ID
|
|
665
|
-
QueryID
|
|
666
|
-
Name
|
|
667
|
-
Description
|
|
668
|
-
Sequence
|
|
669
|
-
SQLBaseType
|
|
670
|
-
SQLFullType
|
|
671
|
-
SourceEntityID
|
|
672
|
-
SourceEntity
|
|
673
|
-
SourceFieldName
|
|
674
|
-
IsComputed
|
|
675
|
-
ComputationDescription
|
|
676
|
-
IsSummary
|
|
677
|
-
SummaryDescription
|
|
678
|
-
}
|
|
679
|
-
Parameters {
|
|
651
|
+
Query {
|
|
680
652
|
ID
|
|
681
|
-
QueryID
|
|
682
653
|
Name
|
|
683
654
|
Description
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
655
|
+
CategoryID
|
|
656
|
+
Category
|
|
657
|
+
SQL
|
|
658
|
+
Status
|
|
659
|
+
QualityRank
|
|
660
|
+
EmbeddingVector
|
|
661
|
+
EmbeddingModelID
|
|
662
|
+
EmbeddingModel
|
|
663
|
+
TechnicalDescription
|
|
664
|
+
Reusable
|
|
665
|
+
MJQueryFields_QueryIDArray {
|
|
666
|
+
ID
|
|
667
|
+
QueryID
|
|
668
|
+
Name
|
|
669
|
+
Description
|
|
670
|
+
Sequence
|
|
671
|
+
SQLBaseType
|
|
672
|
+
SQLFullType
|
|
673
|
+
SourceEntityID
|
|
674
|
+
SourceEntity
|
|
675
|
+
SourceFieldName
|
|
676
|
+
IsComputed
|
|
677
|
+
ComputationDescription
|
|
678
|
+
IsSummary
|
|
679
|
+
SummaryDescription
|
|
680
|
+
}
|
|
681
|
+
MJQueryParameters_QueryIDArray {
|
|
682
|
+
ID
|
|
683
|
+
QueryID
|
|
684
|
+
Name
|
|
685
|
+
Description
|
|
686
|
+
Type
|
|
687
|
+
IsRequired
|
|
688
|
+
DefaultValue
|
|
689
|
+
SampleValue
|
|
690
|
+
ValidationFilters
|
|
691
|
+
}
|
|
692
|
+
MJQueryEntities_QueryIDArray {
|
|
693
|
+
ID
|
|
694
|
+
QueryID
|
|
695
|
+
EntityID
|
|
696
|
+
Entity
|
|
697
|
+
}
|
|
698
|
+
MJQueryPermissions_QueryIDArray {
|
|
699
|
+
ID
|
|
700
|
+
QueryID
|
|
701
|
+
RoleID
|
|
702
|
+
Role
|
|
703
|
+
}
|
|
701
704
|
}
|
|
702
705
|
}
|
|
703
|
-
}`,{input:e});return
|
|
706
|
+
}`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
|
|
704
707
|
UpdateQuerySystemUser(input: $input) {
|
|
705
708
|
Success
|
|
706
709
|
ErrorMessage
|
|
707
|
-
|
|
708
|
-
Name
|
|
709
|
-
Description
|
|
710
|
-
CategoryID
|
|
711
|
-
Category
|
|
712
|
-
SQL
|
|
713
|
-
Status
|
|
714
|
-
QualityRank
|
|
715
|
-
EmbeddingVector
|
|
716
|
-
EmbeddingModelID
|
|
717
|
-
EmbeddingModelName
|
|
718
|
-
TechnicalDescription
|
|
719
|
-
Fields {
|
|
710
|
+
Query {
|
|
720
711
|
ID
|
|
721
|
-
QueryID
|
|
722
712
|
Name
|
|
723
713
|
Description
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
714
|
+
CategoryID
|
|
715
|
+
Category
|
|
716
|
+
SQL
|
|
717
|
+
Status
|
|
718
|
+
QualityRank
|
|
719
|
+
EmbeddingVector
|
|
720
|
+
EmbeddingModelID
|
|
721
|
+
EmbeddingModel
|
|
722
|
+
TechnicalDescription
|
|
723
|
+
Reusable
|
|
724
|
+
MJQueryFields_QueryIDArray {
|
|
725
|
+
ID
|
|
726
|
+
QueryID
|
|
727
|
+
Name
|
|
728
|
+
Description
|
|
729
|
+
Sequence
|
|
730
|
+
SQLBaseType
|
|
731
|
+
SQLFullType
|
|
732
|
+
SourceEntityID
|
|
733
|
+
SourceEntity
|
|
734
|
+
SourceFieldName
|
|
735
|
+
IsComputed
|
|
736
|
+
ComputationDescription
|
|
737
|
+
IsSummary
|
|
738
|
+
SummaryDescription
|
|
739
|
+
}
|
|
740
|
+
MJQueryParameters_QueryIDArray {
|
|
741
|
+
ID
|
|
742
|
+
QueryID
|
|
743
|
+
Name
|
|
744
|
+
Description
|
|
745
|
+
Type
|
|
746
|
+
IsRequired
|
|
747
|
+
DefaultValue
|
|
748
|
+
SampleValue
|
|
749
|
+
ValidationFilters
|
|
750
|
+
}
|
|
751
|
+
MJQueryEntities_QueryIDArray {
|
|
752
|
+
ID
|
|
753
|
+
QueryID
|
|
754
|
+
EntityID
|
|
755
|
+
Entity
|
|
756
|
+
}
|
|
757
|
+
MJQueryPermissions_QueryIDArray {
|
|
758
|
+
ID
|
|
759
|
+
QueryID
|
|
760
|
+
RoleID
|
|
761
|
+
Role
|
|
762
|
+
}
|
|
757
763
|
}
|
|
758
764
|
}
|
|
759
|
-
}`,{input:e});return
|
|
765
|
+
}`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return u.LogError("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
|
|
760
766
|
DeleteQuerySystemResolver(ID: $ID, options: $options) {
|
|
761
767
|
Success
|
|
762
768
|
ErrorMessage
|
|
763
769
|
ID
|
|
764
770
|
Name
|
|
765
771
|
}
|
|
766
|
-
}`,
|
|
772
|
+
}`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=d.gql`
|
|
767
773
|
query RunAIPromptSystemUser(
|
|
768
774
|
$promptId: String!,
|
|
769
775
|
$data: String,
|
|
@@ -822,7 +828,7 @@
|
|
|
822
828
|
chatResult
|
|
823
829
|
}
|
|
824
830
|
}
|
|
825
|
-
`,
|
|
831
|
+
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=d.gql`
|
|
826
832
|
query RunAIAgentSystemUser(
|
|
827
833
|
$agentId: String!,
|
|
828
834
|
$messages: String!,
|
|
@@ -849,7 +855,16 @@
|
|
|
849
855
|
result
|
|
850
856
|
}
|
|
851
857
|
}
|
|
852
|
-
`,
|
|
858
|
+
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=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:r,chatResult:s}}processAgentResult(e){return R.SafeJSONParse(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
|
|
859
|
+
TestQuerySQL(input: $input) {
|
|
860
|
+
Success
|
|
861
|
+
Results
|
|
862
|
+
RowCount
|
|
863
|
+
ExecutionTime
|
|
864
|
+
ErrorMessage
|
|
865
|
+
AppliedParameters
|
|
866
|
+
}
|
|
867
|
+
}`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?R.SafeJSONParse(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?R.SafeJSONParse(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=d.gql`
|
|
853
868
|
query ExecuteSimplePromptSystemUser(
|
|
854
869
|
$systemPrompt: String!,
|
|
855
870
|
$messages: String,
|
|
@@ -872,7 +887,7 @@
|
|
|
872
887
|
executionTimeMs
|
|
873
888
|
}
|
|
874
889
|
}
|
|
875
|
-
`,
|
|
890
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=d.gql`
|
|
876
891
|
query EmbedTextSystemUser(
|
|
877
892
|
$textToEmbed: [String!]!,
|
|
878
893
|
$modelSize: String!
|
|
@@ -887,7 +902,7 @@
|
|
|
887
902
|
error
|
|
888
903
|
}
|
|
889
904
|
}
|
|
890
|
-
`,
|
|
905
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class te{static{g(this,"GetDataOutput")}}class re{static{g(this,"SimpleRemoteEntityOutput")}}class se{static{g(this,"SimpleRemoteEntity")}}class ne{static{g(this,"SimpleRemoteEntityField")}}class oe{static{g(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=d.gql`
|
|
891
906
|
mutation RunAction($input: RunActionInput!) {
|
|
892
907
|
RunAction(input: $input) {
|
|
893
908
|
Success
|
|
@@ -896,7 +911,7 @@
|
|
|
896
911
|
ResultData
|
|
897
912
|
}
|
|
898
913
|
}
|
|
899
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let
|
|
914
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}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 r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,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=d.gql`
|
|
900
915
|
mutation RunEntityAction($input: EntityActionInput!) {
|
|
901
916
|
RunEntityAction(input: $input) {
|
|
902
917
|
Success
|
|
@@ -904,7 +919,7 @@
|
|
|
904
919
|
ResultData
|
|
905
920
|
}
|
|
906
921
|
}
|
|
907
|
-
`;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(
|
|
922
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ae{static{g(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}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=d.gql`
|
|
908
923
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
909
924
|
CreateAPIKey(input: $input) {
|
|
910
925
|
Success
|
|
@@ -920,7 +935,7 @@
|
|
|
920
935
|
Error
|
|
921
936
|
}
|
|
922
937
|
}
|
|
923
|
-
`,
|
|
938
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ie{static{g(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isTestCompletionEvent(s,e.testId),"isCompletionEvent"),extractResult:g(s=>this.extractTestResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:g(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:g(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:g(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=d.gql`
|
|
924
939
|
query IsTestRunning($testId: String!) {
|
|
925
940
|
IsTestRunning(testId: $testId)
|
|
926
941
|
}
|
|
@@ -978,7 +993,7 @@
|
|
|
978
993
|
result
|
|
979
994
|
}
|
|
980
995
|
}
|
|
981
|
-
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,
|
|
996
|
+
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=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:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class ue{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=d.gql`
|
|
982
997
|
query GetRegistryComponent(
|
|
983
998
|
$registryName: String!,
|
|
984
999
|
$namespace: String!,
|
|
@@ -999,7 +1014,7 @@
|
|
|
999
1014
|
specification
|
|
1000
1015
|
}
|
|
1001
1016
|
}
|
|
1002
|
-
`,
|
|
1017
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.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(o){return u.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=d.gql`
|
|
1003
1018
|
query GetRegistryComponent(
|
|
1004
1019
|
$registryName: String!,
|
|
1005
1020
|
$namespace: String!,
|
|
@@ -1020,7 +1035,7 @@
|
|
|
1020
1035
|
specification
|
|
1021
1036
|
}
|
|
1022
1037
|
}
|
|
1023
|
-
`,
|
|
1038
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=d.gql`
|
|
1024
1039
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
1025
1040
|
SearchRegistryComponents(params: $params) {
|
|
1026
1041
|
components
|
|
@@ -1029,7 +1044,7 @@
|
|
|
1029
1044
|
limit
|
|
1030
1045
|
}
|
|
1031
1046
|
}
|
|
1032
|
-
`,
|
|
1047
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=d.gql`
|
|
1033
1048
|
query ResolveComponentDependencies(
|
|
1034
1049
|
$registryId: String!,
|
|
1035
1050
|
$componentId: String!
|
|
@@ -1054,7 +1069,7 @@
|
|
|
1054
1069
|
}
|
|
1055
1070
|
}
|
|
1056
1071
|
}
|
|
1057
|
-
`,
|
|
1072
|
+
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u.LogError(s),null}}async SendComponentFeedback(e){try{const t=d.gql`
|
|
1058
1073
|
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
1059
1074
|
SendComponentFeedback(feedback: $feedback) {
|
|
1060
1075
|
success
|
|
@@ -1062,7 +1077,7 @@
|
|
|
1062
1077
|
error
|
|
1063
1078
|
}
|
|
1064
1079
|
}
|
|
1065
|
-
`,
|
|
1080
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ce{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(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=d.gql`
|
|
1066
1081
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1067
1082
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1068
1083
|
Success
|
|
@@ -1078,7 +1093,7 @@
|
|
|
1078
1093
|
}
|
|
1079
1094
|
}
|
|
1080
1095
|
}
|
|
1081
|
-
`,
|
|
1096
|
+
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}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(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class le{static{g(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=d.gql`
|
|
1082
1097
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1083
1098
|
ListStorageObjects(input: $input) {
|
|
1084
1099
|
objects {
|
|
@@ -1095,34 +1110,34 @@
|
|
|
1095
1110
|
prefixes
|
|
1096
1111
|
}
|
|
1097
1112
|
}
|
|
1098
|
-
`,n={input:{AccountID:e,Prefix:t,Delimiter:
|
|
1113
|
+
`,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(s){const n=s;throw u.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return u.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=d.gql`
|
|
1099
1114
|
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1100
1115
|
CreateDirectory(input: $input)
|
|
1101
1116
|
}
|
|
1102
|
-
`,
|
|
1117
|
+
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return u.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(o=>o.name===s||o.fullPath===t)}catch(r){const s=r;return u.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=d.gql`
|
|
1103
1118
|
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1104
1119
|
CreatePreAuthUploadUrl(input: $input) {
|
|
1105
1120
|
UploadUrl
|
|
1106
1121
|
ProviderKey
|
|
1107
1122
|
}
|
|
1108
1123
|
}
|
|
1109
|
-
`,n={input:{AccountID:e,ObjectName:t,ContentType:
|
|
1124
|
+
`,n={input:{AccountID:e,ObjectName:t,ContentType:r}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw u.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=d.gql`
|
|
1110
1125
|
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1111
1126
|
CreatePreAuthDownloadUrl(input: $input)
|
|
1112
1127
|
}
|
|
1113
|
-
`,
|
|
1128
|
+
`,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw u.LogError(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=d.gql`
|
|
1114
1129
|
mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
|
|
1115
1130
|
DeleteStorageObject(input: $input)
|
|
1116
1131
|
}
|
|
1117
|
-
`,
|
|
1132
|
+
`,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return u.LogError(`Error deleting storage object: ${s}`),!1}}async MoveObject(e,t,r){try{const s=d.gql`
|
|
1118
1133
|
mutation MoveStorageObject($input: MoveStorageObjectInput!) {
|
|
1119
1134
|
MoveStorageObject(input: $input)
|
|
1120
1135
|
}
|
|
1121
|
-
`,n={input:{AccountID:e,OldName:t,NewName:
|
|
1136
|
+
`,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){const n=s;return u.LogError(`Error moving storage object: ${n}`),!1}}async CopyObject(e,t,r){try{const s=d.gql`
|
|
1122
1137
|
mutation CopyStorageObject($input: CopyStorageObjectInput!) {
|
|
1123
1138
|
CopyStorageObject(input: $input)
|
|
1124
1139
|
}
|
|
1125
|
-
`,n={input:{AccountID:e,SourceName:t,DestinationName:
|
|
1140
|
+
`,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){const n=s;return u.LogError(`Error copying storage object: ${n}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=d.gql`
|
|
1126
1141
|
mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
|
|
1127
1142
|
CopyObjectBetweenAccounts(input: $input) {
|
|
1128
1143
|
success
|
|
@@ -1134,7 +1149,7 @@
|
|
|
1134
1149
|
destinationPath
|
|
1135
1150
|
}
|
|
1136
1151
|
}
|
|
1137
|
-
`,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:
|
|
1152
|
+
`,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,o);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 o=n;return u.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=d.gql`
|
|
1138
1153
|
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1139
1154
|
SearchAcrossAccounts(input: $input) {
|
|
1140
1155
|
accountResults {
|
|
@@ -1162,7 +1177,7 @@
|
|
|
1162
1177
|
failedAccounts
|
|
1163
1178
|
}
|
|
1164
1179
|
}
|
|
1165
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:
|
|
1180
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class de{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=d.gql`
|
|
1166
1181
|
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1167
1182
|
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1168
1183
|
Success
|
|
@@ -1175,7 +1190,7 @@
|
|
|
1175
1190
|
}
|
|
1176
1191
|
}
|
|
1177
1192
|
}
|
|
1178
|
-
`,
|
|
1193
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationDiscoverObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async DiscoverFields(e,t){try{const r=d.gql`
|
|
1179
1194
|
query IntegrationDiscoverFields($companyIntegrationID: String!, $objectName: String!) {
|
|
1180
1195
|
IntegrationDiscoverFields(companyIntegrationID: $companyIntegrationID, objectName: $objectName) {
|
|
1181
1196
|
Success
|
|
@@ -1190,7 +1205,7 @@
|
|
|
1190
1205
|
}
|
|
1191
1206
|
}
|
|
1192
1207
|
}
|
|
1193
|
-
`,n=(await this._dataProvider.ExecuteGQL(
|
|
1208
|
+
`,n=(await this._dataProvider.ExecuteGQL(r,{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(r){return this.handleError(r,[])}}async TestConnection(e){try{const t=d.gql`
|
|
1194
1209
|
query IntegrationTestConnection($companyIntegrationID: String!) {
|
|
1195
1210
|
IntegrationTestConnection(companyIntegrationID: $companyIntegrationID) {
|
|
1196
1211
|
Success
|
|
@@ -1198,7 +1213,7 @@
|
|
|
1198
1213
|
ServerVersion
|
|
1199
1214
|
}
|
|
1200
1215
|
}
|
|
1201
|
-
`,
|
|
1216
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return u.LogError(`Error testing integration connection: ${r}`),{Success:!1,Message:`Error: ${r.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const s=d.gql`
|
|
1202
1217
|
query IntegrationSchemaPreview(
|
|
1203
1218
|
$companyIntegrationID: String!,
|
|
1204
1219
|
$objects: [SchemaPreviewObjectInput!]!,
|
|
@@ -1219,7 +1234,7 @@
|
|
|
1219
1234
|
Warnings
|
|
1220
1235
|
}
|
|
1221
1236
|
}
|
|
1222
|
-
`,o=(await this._dataProvider.ExecuteGQL(
|
|
1237
|
+
`,o=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Files:o.Files??[],Warnings:o.Warnings??[]}}catch(s){const n=s;return u.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=d.gql`
|
|
1223
1238
|
query IntegrationPreviewData(
|
|
1224
1239
|
$companyIntegrationID: String!,
|
|
1225
1240
|
$objectName: String!,
|
|
@@ -1237,7 +1252,7 @@
|
|
|
1237
1252
|
}
|
|
1238
1253
|
}
|
|
1239
1254
|
}
|
|
1240
|
-
`,o=(await this._dataProvider.ExecuteGQL(
|
|
1255
|
+
`,o=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Records:o.Records??[]}}catch(s){const n=s;return u.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=d.gql`
|
|
1241
1256
|
query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
|
|
1242
1257
|
IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
|
|
1243
1258
|
Success
|
|
@@ -1256,5 +1271,5 @@
|
|
|
1256
1271
|
}
|
|
1257
1272
|
}
|
|
1258
1273
|
}
|
|
1259
|
-
`,
|
|
1274
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return u.LogError(`Error getting default config: ${r}`),{Success:!1,Message:`Error: ${r.message}`}}}handleError(e,t){const r=e;return u.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return d.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=F,exports.BrowserStorageProviderBase=T,exports.FieldMapper=v,exports.FireAndForgetHelper=$,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=h,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=de,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=z,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=U,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=H,exports.setupGraphQLClient=j;
|
|
1260
1275
|
//# sourceMappingURL=index.cjs.map
|