@memberjunction/graphql-dataprovider 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +145 -61
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +314 -1
- package/dist/index.d.mts +314 -1
- package/dist/index.mjs +153 -69
- 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
|
|
1
|
+
"use strict";var Ee=Object.defineProperty;var f=(E,e)=>Ee(E,"name",{value:e,configurable:!0});var l=require("graphql-request"),c=require("@memberjunction/core"),fe=require("@memberjunction/core-entities"),$=require("rxjs"),De=require("graphql-ws"),we=require("uuid"),w=require("@memberjunction/global"),ve=require("@tempfix/idb");const z=class z{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(z,"FieldMapper");let P=z;const H=class H extends c.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=l.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 a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,
|
|
9
|
+
`,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,n=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=a.ResultsJSON[i],u=w.SafeJSONParse(o),p=this.PendingTransactions[i];n.push(new c.TransactionResult(p,u,u!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(H,"GraphQLTransactionGroup");let C=H;const X=class X{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=l.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
|
-
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(
|
|
68
|
+
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{c.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[o]});const u=JSON.parse(o);if(c.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){c.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const p={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(p)}else c.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",o)}}));const a=l.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
result
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,
|
|
107
|
+
`,n=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,n);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return w.SafeJSONParse(e)}handleAgentError(e){const t=e;return c.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{const i=JSON.parse(n);if(i.resolver==="RunAIAgentResolver"&&i.type==="ExecutionProgress"&&i.status==="ok"&&i.data?.progress){const o={...i.data.progress,metadata:{...i.data.progress.metadata||{},agentRunId:i.data.agentRunId}};e.onProgress(o)}}catch(i){console.error("[GraphQLAIClient] Failed to parse progress message:",i)}}));const r=l.gql`
|
|
108
108
|
mutation RunAIAgentFromConversationDetail(
|
|
109
109
|
$conversationDetailId: String!,
|
|
110
110
|
$agentId: String!,
|
|
@@ -141,7 +141,7 @@
|
|
|
141
141
|
result
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
|
-
`,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=
|
|
144
|
+
`,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=l.gql`
|
|
145
145
|
mutation ExecuteSimplePrompt(
|
|
146
146
|
$systemPrompt: String!,
|
|
147
147
|
$messages: String,
|
|
@@ -164,7 +164,7 @@
|
|
|
164
164
|
executionTimeMs
|
|
165
165
|
}
|
|
166
166
|
}
|
|
167
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let
|
|
167
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=l.gql`
|
|
168
168
|
mutation EmbedText(
|
|
169
169
|
$textToEmbed: [String!]!,
|
|
170
170
|
$modelSize: String!
|
|
@@ -179,15 +179,15 @@
|
|
|
179
179
|
error
|
|
180
180
|
}
|
|
181
181
|
}
|
|
182
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const
|
|
182
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(X,"GraphQLAIClient");let N=X;const v="default",Y=class Y{constructor(){this._storage=new Map}getCategoryMap(e){const t=e||v;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||v).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||v).set(e,t)}async Remove(e,t){this.getCategoryMap(t||v).delete(e)}async ClearCategory(e){const t=e||v;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||v);return t?Array.from(t.keys()):[]}};f(Y,"BrowserStorageProviderBase");let b=Y;const Pe="MJ_Metadata",$e=3,Se=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Ie="Metadata_KVPairs",Z=class Z extends b{constructor(){super(),this._dbReady=!1,this.dbPromise=ve.openDB(Pe,$e,{upgrade(e){try{e.objectStoreNames.contains(Ie)&&e.deleteObjectStore(Ie);for(const t of Se)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){c.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return Se.includes(t)}getStoreName(e){const t=e||v;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||v;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,n),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return c.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){c.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||v,s=this.getStoreName(e);if(this.isKnownCategory(r)){const a=t.transaction(s,"readwrite");await a.objectStore(s).clear(),await a.done}else{const a=`[${r}]:`,n=t.transaction("mj:default","readwrite"),i=n.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(a)&&await i.delete(u);await n.done}}catch(t){c.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||v,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(u=>String(u));const o=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};f(Z,"BrowserIndexedDBStorageProvider");let A=Z;const ee=class ee extends c.ProviderConfigDataBase{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 URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,i,o){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,RefreshTokenFunction:s},a,n,i)}};f(ee,"GraphQLProviderConfigData");let L=ee;const h=class h extends c.ProviderBase{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
|
|
183
183
|
${this.userInfoString()}
|
|
184
184
|
UserRoles_UserIDArray {
|
|
185
185
|
${this.userRoleInfoString()}
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
|
-
`,this._currentUserQuery=
|
|
188
|
+
`,this._currentUserQuery=l.gql`query CurrentUserAndRoles {
|
|
189
189
|
${this._innerCurrentUserQueryString}
|
|
190
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new N(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return
|
|
190
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new N(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return we.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(a){throw c.LogError(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new c.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=l.gql`
|
|
191
191
|
query GetReportDataQuery ($ReportID: String!) {
|
|
192
192
|
GetReportData(ReportID: $ReportID) {
|
|
193
193
|
Success
|
|
@@ -196,25 +196,25 @@
|
|
|
196
196
|
ExecutionTime
|
|
197
197
|
ErrorMessage
|
|
198
198
|
}
|
|
199
|
-
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.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 QueryID or QueryName provided to RunQuery")}async InternalRunQueries(e,t){const r=
|
|
199
|
+
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.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 QueryID or QueryName provided to RunQuery")}async InternalRunQueries(e,t){const r=l.gql`
|
|
200
200
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
201
201
|
RunQueries(input: $input) {
|
|
202
202
|
${this.QueryReturnFieldList}
|
|
203
203
|
}
|
|
204
204
|
}
|
|
205
|
-
`,s=e.map(
|
|
205
|
+
`,s=e.map(n=>({QueryID:n.QueryID,QueryName:n.QueryName,CategoryID:n.CategoryID,CategoryPath:n.CategoryPath,Parameters:n.Parameters,MaxRows:n.MaxRows,StartRow:n.StartRow,ForceAuditLog:n.ForceAuditLog,AuditLogDescription:n.AuditLogDescription})),a=await this.ExecuteGQL(r,{input:s});return a&&a.RunQueries?a.RunQueries.map(n=>this.TransformQueryPayload(n)):[]}async RunQueryByID(e,t,r,s,a,n,i){const o=l.gql`
|
|
206
206
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
207
207
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
208
208
|
${this.QueryReturnFieldList}
|
|
209
209
|
}
|
|
210
210
|
}
|
|
211
|
-
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),
|
|
211
|
+
`,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),n!==void 0&&(u.MaxRows=n),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(o,u);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,n,i){const o=l.gql`
|
|
212
212
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
213
213
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
214
214
|
${this.QueryReturnFieldList}
|
|
215
215
|
}
|
|
216
216
|
}
|
|
217
|
-
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),
|
|
217
|
+
`,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),n!==void 0&&(u.MaxRows=n),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(o,u);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
218
218
|
Success
|
|
219
219
|
QueryID
|
|
220
220
|
QueryName
|
|
@@ -223,7 +223,7 @@
|
|
|
223
223
|
TotalRowCount
|
|
224
224
|
ExecutionTime
|
|
225
225
|
ErrorMessage
|
|
226
|
-
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(
|
|
226
|
+
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=l.gql`
|
|
227
227
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
228
228
|
RunQueriesWithCacheCheck(input: $input) {
|
|
229
229
|
success
|
|
@@ -239,11 +239,11 @@
|
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
|
-
`,
|
|
242
|
+
`,n=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!n)return{success:!1,results:[],errorMessage:"No response from server"};const i=n.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:n.success,results:i,errorMessage:n.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const a={};let n,i;if(e.ViewEntity)i=e.ViewEntity,n=i.Entity;else{const{entityName:d,v:m}=await this.getEntityNameAndUserView(e,t);i=m,n=d}const o=this.Entities.find(d=>d.Name===n);if(!o)throw new Error(`Entity ${n} not found in metadata`);let u=!1;const p=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(u=!0,r=`Run${p}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),u||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(o,i,e,u),S=l.gql`
|
|
243
243
|
query RunViewQuery ($input: ${s}!) {
|
|
244
244
|
${r}(input: $input) {
|
|
245
245
|
Results {
|
|
246
|
-
${
|
|
246
|
+
${g.join(`
|
|
247
247
|
`)}
|
|
248
248
|
}
|
|
249
249
|
UserViewRunID
|
|
@@ -253,7 +253,7 @@
|
|
|
253
253
|
Success
|
|
254
254
|
ErrorMessage
|
|
255
255
|
}
|
|
256
|
-
}`,
|
|
256
|
+
}`,y=await this.ExecuteGQL(S,{input:a});if(y&&y[r]){const d=y[r].Results;if(d&&d.length>0){const R=o.Fields.filter(I=>I.CodeName!==I.Name&&I.CodeName!==void 0);d.forEach(I=>{this.ConvertBackToMJFields(I),R.forEach(D=>{I[D.Name]=I[D.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const o of e){let u="",p="";const g={};let S=null,y=null;if(o.ViewEntity)y=o.ViewEntity,S=y.Get("Entity");else{const{entityName:I,v:D}=await this.getEntityNameAndUserView(o,t);y=D,S=I}const d=this.Entities.find(I=>I.Name===S);if(!d)throw new Error(`Entity ${S} not found in metadata`);s.push(d);let m=!1;const R=c.getGraphQLTypeNameBase(d);o.ViewID?(u=`Run${R}ViewByID`,p="RunViewByIDInput",g.ViewID=o.ViewID):o.ViewName?(u=`Run${R}ViewByName`,p="RunViewByNameInput",g.ViewName=o.ViewName):(m=!0,u=`Run${R}DynamicView`,p="RunDynamicViewInput",g.EntityName=o.EntityName),g.ExtraFilter=o.ExtraFilter||"",g.OrderBy=o.OrderBy||"",g.UserSearchString=o.UserSearchString||"",g.Fields=o.Fields,g.IgnoreMaxRows=o.IgnoreMaxRows||!1,o.MaxRows!==void 0&&(g.MaxRows=o.MaxRows),o.StartRow!==void 0&&(g.StartRow=o.StartRow),g.ForceAuditLog=o.ForceAuditLog||!1,g.ResultType=o.ResultType||"simple",o.AuditLogDescription&&o.AuditLogDescription.length>0&&(g.AuditLogDescription=o.AuditLogDescription),m||(g.ExcludeUserViewRunID=o.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=o.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=o.OverrideExcludeFilter||"",g.SaveViewResults=o.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(d,y,o,m))}const n=l.gql`
|
|
257
257
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
258
258
|
RunViews(input: $input) {
|
|
259
259
|
Results {
|
|
@@ -271,7 +271,7 @@
|
|
|
271
271
|
Success
|
|
272
272
|
ErrorMessage
|
|
273
273
|
}
|
|
274
|
-
}`,i=await this.ExecuteGQL(
|
|
274
|
+
}`,i=await this.ExecuteGQL(n,{input:r});if(i&&i.RunViews){const o=i.RunViews;for(const[u,p]of o.entries())p.Results=p.Results.map(g=>{let S=JSON.parse(g.Data);return this.ConvertBackToMJFields(S),S});return o}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=l.gql`
|
|
275
275
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
276
276
|
RunViewsWithCacheCheck(input: $input) {
|
|
277
277
|
success
|
|
@@ -304,7 +304,7 @@
|
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
}
|
|
307
|
-
`,
|
|
307
|
+
`,n=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!n)return{success:!1,results:[],errorMessage:"No response from server"};const i=n.results.map((o,u)=>{const p=e[u];if(o.status==="differential"&&o.differentialData){const g=o.differentialData.updatedRows.map(S=>{const y=JSON.parse(S.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:g,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const g=o.Results.map(S=>{const y=JSON.parse(S.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:g,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:n.success,results:i,errorMessage:n.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await fe.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await fe.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],n=new P;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(n.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(n.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(n.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=l.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
308
308
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
309
309
|
EntityName
|
|
310
310
|
RelatedEntityName
|
|
@@ -316,7 +316,7 @@
|
|
|
316
316
|
}
|
|
317
317
|
}
|
|
318
318
|
}
|
|
319
|
-
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw c.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=
|
|
319
|
+
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw c.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=l.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
320
320
|
GetRecordDuplicates(params: $params) {
|
|
321
321
|
Status
|
|
322
322
|
ErrorMessage
|
|
@@ -338,7 +338,7 @@
|
|
|
338
338
|
}
|
|
339
339
|
}
|
|
340
340
|
}
|
|
341
|
-
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(
|
|
341
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(n=>n.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=l.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
342
342
|
MergeRecords(request: $request) {
|
|
343
343
|
Success
|
|
344
344
|
OverallStatus
|
|
@@ -355,32 +355,32 @@
|
|
|
355
355
|
Message
|
|
356
356
|
}
|
|
357
357
|
}
|
|
358
|
-
}`,
|
|
359
|
-
${e.Fields.map(
|
|
358
|
+
}`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.MergeRecords}catch(a){return c.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${n}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new P,g=` ${o}(input: $input) {
|
|
359
|
+
${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
|
|
360
360
|
`)}
|
|
361
|
-
}`,S=
|
|
362
|
-
${
|
|
361
|
+
}`,S=l.gql`mutation ${n}${i} ($input: ${o}Input!) {
|
|
362
|
+
${g}
|
|
363
363
|
}
|
|
364
|
-
`;for(let
|
|
365
|
-
${u}(${
|
|
366
|
-
${e.Fields.filter(
|
|
364
|
+
`;for(let y=0;y<u.length;y++){const d=u[y];let m=d.Value;if(m)switch(d.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:m=m.getTime();break;case c.EntityFieldTSType.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case c.EntityFieldTSType.Number:if(typeof m!="number"){const R=Number(m);isNaN(R)||(m=R)}break}m===null&&d.EntityFieldInfo.AllowsNull===!1&&(d.EntityFieldInfo.DefaultValue!==null?m=d.EntityFieldInfo.DefaultValue:d.FieldType===c.EntityFieldTSType.Number||d.FieldType===c.EntityFieldTSType.Boolean?m=0:m=""),a.input[d.CodeName]=m}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(d=>{let m=null;d.OldValue!==null&&d.OldValue!==void 0&&(d.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?m=d.OldValue.getTime().toString():d.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?m=d.OldValue===!0?"1":"0":typeof d.OldValue!="string"?m=d.OldValue.toString():m=d.OldValue),y.push({Key:d.CodeName,Value:m})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:o,mutationInputTypes:y},(d,m)=>{s.EndedAt=new Date,m&&d?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(d)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(S,a);if(y&&y[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,c.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let n="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const d=e.Fields.find(I=>I.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(y),R=d.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${d.CodeName}: ${R}!`,n.length>0&&(n+=", "),n+=`${d.CodeName}: $${d.CodeName}`,d.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${m} (${d.Name}) is not a valid number`);a[d.CodeName]=parseInt(m)}else a[d.CodeName]=m}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=c.getGraphQLTypeNameBase(e.EntityInfo),p=new P,g=l.gql`query Single${u}${o.length>0?"Full":""} (${i}) {
|
|
365
|
+
${u}(${n}) {
|
|
366
|
+
${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
|
|
367
367
|
`)}
|
|
368
|
-
${
|
|
368
|
+
${o}
|
|
369
369
|
}
|
|
370
370
|
}
|
|
371
|
-
`,S=await this.ExecuteGQL(
|
|
371
|
+
`,S=await this.ExecuteGQL(g,a);return S&&S[u]?this.ConvertBackToMJFields(S[u]):null}catch(a){return c.LogError(a),null}}ConvertBackToMJFields(e){return new P().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],n=this.Entities.find(o=>o.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
372
372
|
${i} {
|
|
373
|
-
${
|
|
373
|
+
${n.Fields.map(o=>o.CodeName).join(`
|
|
374
374
|
`)}
|
|
375
375
|
}
|
|
376
|
-
`}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(
|
|
377
|
-
`),u+=`${
|
|
376
|
+
`}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const a={},n=[];let i="",o="",u="";for(let d of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===d.FieldName.trim().toLowerCase());a[m.CodeName]=m.Value,n.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,o.length>0&&(o+=", "),o+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
|
|
377
|
+
`),u+=`${m.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),S=l.gql`${g}(${i}, options___: $options___) {
|
|
378
378
|
${u}
|
|
379
379
|
}
|
|
380
|
-
`,
|
|
380
|
+
`,y=l.gql`mutation ${g} (${o}, $options___: DeleteOptionsInput!) {
|
|
381
381
|
${S}
|
|
382
382
|
}
|
|
383
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",S,a,{mutationName:
|
|
383
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",S,a,{mutationName:g,mutationInputTypes:n},(d,m)=>{if(s.EndedAt=new Date,m&&d){let R=!0;for(const I of e.PrimaryKey.KeyValuePairs)I.Value!==d[I.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const d=await this.ExecuteGQL(y,a);if(d&&d[g]){const m=d[g];for(let R of e.PrimaryKey.KeyValuePairs){let I=m[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof I=="number"&&(I=I.toString()),D!==I)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, Returned: ${I}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,c.LogError(a),!1}}async GetDatasetByName(e,t){const r=l.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
384
384
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
385
385
|
DatasetID
|
|
386
386
|
DatasetName
|
|
@@ -389,7 +389,7 @@
|
|
|
389
389
|
LatestUpdateDate
|
|
390
390
|
Results
|
|
391
391
|
}
|
|
392
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=
|
|
392
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=l.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
393
393
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
394
394
|
DatasetID
|
|
395
395
|
DatasetName
|
|
@@ -398,22 +398,22 @@
|
|
|
398
398
|
LatestUpdateDate
|
|
399
399
|
EntityUpdateDates
|
|
400
400
|
}
|
|
401
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new C(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(
|
|
401
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new C(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(o=>o.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=l.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
402
402
|
GetRecordFavoriteStatus(params: $params) {
|
|
403
403
|
Success
|
|
404
404
|
IsFavorite
|
|
405
405
|
}
|
|
406
|
-
}`,i=await this.ExecuteGQL(
|
|
406
|
+
}`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const n=this.Entities.find(u=>u.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const i=l.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
407
407
|
SetRecordFavoriteStatus(params: $params){
|
|
408
408
|
Success
|
|
409
409
|
}
|
|
410
|
-
}`,
|
|
410
|
+
}`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=l.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
411
411
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
412
412
|
Success
|
|
413
413
|
Status
|
|
414
414
|
RecordName
|
|
415
415
|
}
|
|
416
|
-
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=
|
|
416
|
+
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=l.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
417
417
|
GetEntityRecordNames(info: $info) {
|
|
418
418
|
Success
|
|
419
419
|
Status
|
|
@@ -426,35 +426,35 @@
|
|
|
426
426
|
EntityName
|
|
427
427
|
RecordName
|
|
428
428
|
}
|
|
429
|
-
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=
|
|
429
|
+
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=l.gql`query GetDataContextData ($DataContextID: String!) {
|
|
430
430
|
GetDataContextData(DataContextID: $DataContextID) {
|
|
431
431
|
Success
|
|
432
432
|
ErrorMessages
|
|
433
433
|
Results
|
|
434
434
|
}
|
|
435
|
-
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}async GetDataContextItemData(e){try{const t=
|
|
435
|
+
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}async GetDataContextItemData(e){try{const t=l.gql`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
436
436
|
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
437
437
|
Success
|
|
438
438
|
ErrorMessage
|
|
439
439
|
Result
|
|
440
440
|
}
|
|
441
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._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,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new
|
|
441
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._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,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new l.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
442
442
|
`:s.startsWith("_")||(t+=s+`
|
|
443
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new
|
|
443
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new A),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=De.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([a,n])=>{const i=e-n.lastRequestedAt,o=e-n.lastEmissionAt;n.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${n.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(a))}),s.forEach(a=>{const n=this._pushStatusSubjects.get(a);if(n)try{n.subject.complete(),n.subscription.unsubscribe(),this._pushStatusSubjects.delete(a),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${a}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${a}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:n=>{r.next(n.data)},error:async n=>{const i=n;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(n)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(o=>{r.activeSubscribers++;const u=r.subject.subscribe(o);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,u.unsubscribe()}});const s=l.gql`subscription StatusUpdates($sessionId: String!) {
|
|
444
444
|
statusUpdates(sessionId: $sessionId) {
|
|
445
445
|
date
|
|
446
446
|
message
|
|
447
447
|
sessionId
|
|
448
448
|
}
|
|
449
449
|
}
|
|
450
|
-
`,a=new
|
|
450
|
+
`,a=new $.Subject,n=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(o=>{const u=n.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const g=this._pushStatusSubjects.get(e);g&&(g.lastEmissionAt=Date.now()),o.next(p.data.statusUpdates.message)},error:async p=>{const g=p;if(g?.extensions?.code==="JWT_EXPIRED"||g?.message?.includes("token has expired")||g?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),o.error(y)}}else o.error(p)},complete:()=>{o.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:o=>a.next(o),error:o=>{a.error(o),this._pushStatusSubjects.delete(e)},complete:()=>{a.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:a,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(o=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const p=a.subscribe(o);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};f(h,"GraphQLDataProvider");let x=h;async function Ce(E){const e=new x;return c.SetProvider(e),await e.Config(E),await c.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(Ce,"setupGraphQLClient");const te=class te{};f(te,"SyncRolesAndUsersResult");let T=te;const re=class re{};f(re,"RoleInput");let M=re;const se=class se{};f(se,"UserInput");let U=se;const ae=class ae{};f(ae,"RolesAndUsersInput");let V=ae;var Re=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(Re||{});const oe=class oe{};f(oe,"ActionItemInput");let Q=oe;const ne=class ne{constructor(){this.Results=[]}};f(ne,"SyncDataResult");let G=ne;const ie=class ie{};f(ie,"ActionItemOutput");let F=ie;const ue=class ue{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new l.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
451
451
|
GetData(input: $input) {
|
|
452
452
|
Success
|
|
453
453
|
ErrorMessages
|
|
454
454
|
Queries
|
|
455
455
|
Results
|
|
456
456
|
}
|
|
457
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?w.SafeJSONParse(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),c.IsVerboseLoggingEnabled()){const
|
|
457
|
+
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?w.SafeJSONParse(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),c.IsVerboseLoggingEnabled()){const n=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(n)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
458
458
|
GetAllEntities {
|
|
459
459
|
Success
|
|
460
460
|
ErrorMessage
|
|
@@ -714,7 +714,7 @@
|
|
|
714
714
|
ID
|
|
715
715
|
Name
|
|
716
716
|
}
|
|
717
|
-
}`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return c.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=
|
|
717
|
+
}`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return c.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=l.gql`
|
|
718
718
|
query RunAIPromptSystemUser(
|
|
719
719
|
$promptId: String!,
|
|
720
720
|
$data: String,
|
|
@@ -773,7 +773,7 @@
|
|
|
773
773
|
chatResult
|
|
774
774
|
}
|
|
775
775
|
}
|
|
776
|
-
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=
|
|
776
|
+
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=l.gql`
|
|
777
777
|
query RunAIAgentSystemUser(
|
|
778
778
|
$agentId: String!,
|
|
779
779
|
$messages: String!,
|
|
@@ -800,7 +800,7 @@
|
|
|
800
800
|
result
|
|
801
801
|
}
|
|
802
802
|
}
|
|
803
|
-
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=
|
|
803
|
+
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=l.gql`
|
|
804
804
|
query ExecuteSimplePromptSystemUser(
|
|
805
805
|
$systemPrompt: String!,
|
|
806
806
|
$messages: String,
|
|
@@ -823,7 +823,7 @@
|
|
|
823
823
|
executionTimeMs
|
|
824
824
|
}
|
|
825
825
|
}
|
|
826
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let
|
|
826
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=l.gql`
|
|
827
827
|
query EmbedTextSystemUser(
|
|
828
828
|
$textToEmbed: [String!]!,
|
|
829
829
|
$modelSize: String!
|
|
@@ -838,7 +838,7 @@
|
|
|
838
838
|
error
|
|
839
839
|
}
|
|
840
840
|
}
|
|
841
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const
|
|
841
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ue,"GraphQLSystemUserClient");let q=ue;const ce=class ce{};f(ce,"GetDataOutput");let _=ce;const le=class le{};f(le,"SimpleRemoteEntityOutput");let O=le;const de=class de{};f(de,"SimpleRemoteEntity");let k=de;const ye=class ye{};f(ye,"SimpleRemoteEntityField");let j=ye;const ge=class ge{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=l.gql`
|
|
842
842
|
mutation RunAction($input: RunActionInput!) {
|
|
843
843
|
RunAction(input: $input) {
|
|
844
844
|
Success
|
|
@@ -847,7 +847,7 @@
|
|
|
847
847
|
ResultData
|
|
848
848
|
}
|
|
849
849
|
}
|
|
850
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){c.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return c.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=
|
|
850
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){c.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return c.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=l.gql`
|
|
851
851
|
mutation RunEntityAction($input: EntityActionInput!) {
|
|
852
852
|
RunEntityAction(input: $input) {
|
|
853
853
|
Success
|
|
@@ -855,7 +855,7 @@
|
|
|
855
855
|
ResultData
|
|
856
856
|
}
|
|
857
857
|
}
|
|
858
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(
|
|
858
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(ge,"GraphQLActionClient");let B=ge;const me=class me{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const u=JSON.parse(o);u.resolver==="RunTestResolver"&&u.type==="TestExecutionProgress"&&u.status==="ok"&&u.data?.progress&&e.onProgress(u.data.progress)}catch(u){console.error("[GraphQLTestingClient] Failed to parse progress message:",u)}}));const r=l.gql`
|
|
859
859
|
mutation RunTest(
|
|
860
860
|
$testId: String!,
|
|
861
861
|
$verbose: Boolean,
|
|
@@ -876,7 +876,7 @@
|
|
|
876
876
|
result
|
|
877
877
|
}
|
|
878
878
|
}
|
|
879
|
-
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,
|
|
879
|
+
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,n={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s,variables:a},i=await this._dataProvider.ExecuteGQL(r,n);return this.processTestResult(i.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(u=>{try{const p=JSON.parse(u);p.resolver==="RunTestResolver"&&p.type==="TestExecutionProgress"&&p.status==="ok"&&p.data?.progress&&e.onProgress(p.data.progress)}catch(p){console.error("[GraphQLTestingClient] Failed to parse progress message:",p)}}));const r=l.gql`
|
|
880
880
|
mutation RunTestSuite(
|
|
881
881
|
$suiteId: String!,
|
|
882
882
|
$verbose: Boolean,
|
|
@@ -905,11 +905,11 @@
|
|
|
905
905
|
result
|
|
906
906
|
}
|
|
907
907
|
}
|
|
908
|
-
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,
|
|
908
|
+
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,n=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,i={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,variables:a,selectedTestIds:n,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},o=await this._dataProvider.ExecuteGQL(r,i);return this.processSuiteResult(o.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=l.gql`
|
|
909
909
|
query IsTestRunning($testId: String!) {
|
|
910
910
|
IsTestRunning(testId: $testId)
|
|
911
911
|
}
|
|
912
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return c.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};f(me,"GraphQLTestingClient");let
|
|
912
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return c.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};f(me,"GraphQLTestingClient");let K=me;const pe=class pe{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=l.gql`
|
|
913
913
|
query GetRegistryComponent(
|
|
914
914
|
$registryName: String!,
|
|
915
915
|
$namespace: String!,
|
|
@@ -930,7 +930,7 @@
|
|
|
930
930
|
specification
|
|
931
931
|
}
|
|
932
932
|
}
|
|
933
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(
|
|
933
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(n){return c.LogError(`Failed to parse component specification: ${n}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=l.gql`
|
|
934
934
|
query GetRegistryComponent(
|
|
935
935
|
$registryName: String!,
|
|
936
936
|
$namespace: String!,
|
|
@@ -951,7 +951,7 @@
|
|
|
951
951
|
specification
|
|
952
952
|
}
|
|
953
953
|
}
|
|
954
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let
|
|
954
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let n;if(a.specification)try{n=JSON.parse(a.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),n=void 0}return{specification:n,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=l.gql`
|
|
955
955
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
956
956
|
SearchRegistryComponents(params: $params) {
|
|
957
957
|
components
|
|
@@ -960,7 +960,7 @@
|
|
|
960
960
|
limit
|
|
961
961
|
}
|
|
962
962
|
}
|
|
963
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw c.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=
|
|
963
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw c.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=l.gql`
|
|
964
964
|
query ResolveComponentDependencies(
|
|
965
965
|
$registryId: String!,
|
|
966
966
|
$componentId: String!
|
|
@@ -985,7 +985,7 @@
|
|
|
985
985
|
}
|
|
986
986
|
}
|
|
987
987
|
}
|
|
988
|
-
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw c.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return c.LogError(s),null}}async SendComponentFeedback(e){try{const t=
|
|
988
|
+
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw c.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return c.LogError(s),null}}async SendComponentFeedback(e){try{const t=l.gql`
|
|
989
989
|
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
990
990
|
SendComponentFeedback(feedback: $feedback) {
|
|
991
991
|
success
|
|
@@ -993,5 +993,89 @@
|
|
|
993
993
|
error
|
|
994
994
|
}
|
|
995
995
|
}
|
|
996
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(
|
|
996
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(pe,"GraphQLComponentRegistryClient");let J=pe;const he=class he{constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=l.gql`
|
|
997
|
+
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
998
|
+
ListStorageObjects(input: $input) {
|
|
999
|
+
objects {
|
|
1000
|
+
name
|
|
1001
|
+
path
|
|
1002
|
+
fullPath
|
|
1003
|
+
size
|
|
1004
|
+
contentType
|
|
1005
|
+
lastModified
|
|
1006
|
+
isDirectory
|
|
1007
|
+
etag
|
|
1008
|
+
cacheControl
|
|
1009
|
+
}
|
|
1010
|
+
prefixes
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
`,a={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},n=await this._dataProvider.ExecuteGQL(s,a);if(!n?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:n.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:n.ListStorageObjects.prefixes}}catch(s){const a=s;throw c.LogError(`Error listing storage objects: ${a}`),a}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return c.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=l.gql`
|
|
1014
|
+
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1015
|
+
CreateDirectory(input: $input)
|
|
1016
|
+
}
|
|
1017
|
+
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return c.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(n=>n.name===s||n.fullPath===t)}catch(r){const s=r;return c.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=l.gql`
|
|
1018
|
+
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1019
|
+
CreatePreAuthUploadUrl(input: $input) {
|
|
1020
|
+
UploadUrl
|
|
1021
|
+
ProviderKey
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
`,a={input:{AccountID:e,ObjectName:t,ContentType:r}},n=await this._dataProvider.ExecuteGQL(s,a);if(!n?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:n.CreatePreAuthUploadUrl.UploadUrl,providerKey:n.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const a=s;throw c.LogError(`Error creating pre-auth upload URL: ${a}`),a}}async CreatePreAuthDownloadUrl(e,t){try{const r=l.gql`
|
|
1025
|
+
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1026
|
+
CreatePreAuthDownloadUrl(input: $input)
|
|
1027
|
+
}
|
|
1028
|
+
`,s={input:{AccountID:e,ObjectName:t}},a=await this._dataProvider.ExecuteGQL(r,s);if(a?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return a.CreatePreAuthDownloadUrl}catch(r){const s=r;throw c.LogError(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=l.gql`
|
|
1029
|
+
mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
|
|
1030
|
+
DeleteStorageObject(input: $input)
|
|
1031
|
+
}
|
|
1032
|
+
`,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return c.LogError(`Error deleting storage object: ${s}`),!1}}async MoveObject(e,t,r){try{const s=l.gql`
|
|
1033
|
+
mutation MoveStorageObject($input: MoveStorageObjectInput!) {
|
|
1034
|
+
MoveStorageObject(input: $input)
|
|
1035
|
+
}
|
|
1036
|
+
`,a={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.MoveStorageObject??!1}catch(s){const a=s;return c.LogError(`Error moving storage object: ${a}`),!1}}async CopyObject(e,t,r){try{const s=l.gql`
|
|
1037
|
+
mutation CopyStorageObject($input: CopyStorageObjectInput!) {
|
|
1038
|
+
CopyStorageObject(input: $input)
|
|
1039
|
+
}
|
|
1040
|
+
`,a={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.CopyStorageObject??!1}catch(s){const a=s;return c.LogError(`Error copying storage object: ${a}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const a=l.gql`
|
|
1041
|
+
mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
|
|
1042
|
+
CopyObjectBetweenAccounts(input: $input) {
|
|
1043
|
+
success
|
|
1044
|
+
message
|
|
1045
|
+
bytesTransferred
|
|
1046
|
+
sourceAccount
|
|
1047
|
+
destinationAccount
|
|
1048
|
+
sourcePath
|
|
1049
|
+
destinationPath
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
`,n={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(a,n);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(a){const n=a;return c.LogError(`Error copying object between accounts: ${n}`),{success:!1,message:n.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=l.gql`
|
|
1053
|
+
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1054
|
+
SearchAcrossAccounts(input: $input) {
|
|
1055
|
+
accountResults {
|
|
1056
|
+
accountID
|
|
1057
|
+
accountName
|
|
1058
|
+
success
|
|
1059
|
+
errorMessage
|
|
1060
|
+
results {
|
|
1061
|
+
path
|
|
1062
|
+
name
|
|
1063
|
+
size
|
|
1064
|
+
contentType
|
|
1065
|
+
lastModified
|
|
1066
|
+
relevance
|
|
1067
|
+
excerpt
|
|
1068
|
+
matchInFilename
|
|
1069
|
+
objectId
|
|
1070
|
+
}
|
|
1071
|
+
totalMatches
|
|
1072
|
+
hasMore
|
|
1073
|
+
nextPageToken
|
|
1074
|
+
}
|
|
1075
|
+
totalResultsReturned
|
|
1076
|
+
successfulAccounts
|
|
1077
|
+
failedAccounts
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
`,a={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},n=await this._dataProvider.ExecuteGQL(s,a);if(!n?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=n.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const a=s;return c.LogError(`Error searching across accounts: ${a}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}};f(he,"GraphQLFileStorageClient");let W=he;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return l.gql}}),exports.ActionItemInput=Q,exports.ActionItemOutput=F,exports.BrowserIndexedDBStorageProvider=A,exports.BrowserStorageProviderBase=b,exports.FieldMapper=P,exports.GetDataOutput=_,exports.GraphQLAIClient=N,exports.GraphQLActionClient=B,exports.GraphQLComponentRegistryClient=J,exports.GraphQLDataProvider=x,exports.GraphQLFileStorageClient=W,exports.GraphQLProviderConfigData=L,exports.GraphQLSystemUserClient=q,exports.GraphQLTestingClient=K,exports.GraphQLTransactionGroup=C,exports.RoleInput=M,exports.RolesAndUsersInput=V,exports.SimpleRemoteEntity=k,exports.SimpleRemoteEntityField=j,exports.SimpleRemoteEntityOutput=O,exports.SyncDataAction=Re,exports.SyncDataResult=G,exports.SyncRolesAndUsersResult=T,exports.UserInput=U,exports.setupGraphQLClient=Ce;
|
|
997
1081
|
//# sourceMappingURL=index.cjs.map
|