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