@memberjunction/graphql-dataprovider 5.34.1 → 5.35.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 +27 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +27 -27
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],d=R.SafeJSONParse(o),l=this.PendingTransactions[i];a.push(new c.TransactionResult(l,d,d!==null))}return a}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class P{static{y(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,a,s);const o=await P.executeMutation(e);if(!e.validateAck(o)){s&&clearTimeout(s);const d=o?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${d}`),e.createErrorResult(d)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const a=n;throw c.LogError(`[FireAndForget:${t}] Error: ${a.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),c.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class T{static{y(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -297,7 +297,7 @@
|
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
299
|
}
|
|
300
|
-
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const A="5.
|
|
300
|
+
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const A="5.35.0",$="default";class L{static{y(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||$).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||$);for(const n of new Set(e)){const a=s.get(n);r.set(n,a===void 0?null:a)}return r}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=0;function K(){try{const I=A.split("."),e=parseInt(I[0],10),t=parseInt(I[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${A}"`);return e*1e3+t+B}catch(I){return c.LogErrorEx({error:I,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}y(K,"computeIdbVersion");const j=K(),F=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Q extends L{static{y(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,j,{upgrade:y((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${A}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of F)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:y((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return F.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=await r.transaction(s).objectStore(s).get(n);return a===void 0?null:a}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),a=Array.from(new Set(e)),i=a.map(E=>this.getStoreKey(E,t)),o=s.transaction(n,"readonly"),d=o.objectStore(n),l=i.map(E=>d.get(E)),f=await Promise.all(l);await o.done;for(let E=0;E<a.length;E++){const m=f[E];r.set(a[E],m===void 0?null:m)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const d of o)typeof d=="string"&&d.startsWith(n)&&await i.delete(d);await a.done}}catch(t){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(d=>String(d));const o=`[${r}]:`;return i.map(d=>String(d)).filter(d=>d.startsWith(o)).map(d=>d.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}class J extends c.ProviderConfigDataBase{static{y(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,d,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:d,RefreshTokenFunction:s,OnAuthenticationError:l},n,a,i)}}class p extends c.ProviderBase{static{y(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
|
|
301
301
|
${this.userInfoString()}
|
|
302
302
|
MJUserRoles_UserIDArray {
|
|
303
303
|
${this.userRoleInfoString()}
|
|
@@ -333,13 +333,13 @@
|
|
|
333
333
|
${this.QueryReturnFieldList}
|
|
334
334
|
}
|
|
335
335
|
}
|
|
336
|
-
`,
|
|
336
|
+
`,d={QueryID:e};t!==void 0&&(d.CategoryID=t),r!==void 0&&(d.CategoryPath=r),n!==void 0&&(d.Parameters=n),a!==void 0&&(d.MaxRows=a),i!==void 0&&(d.StartRow=i);const l=await this.ExecuteGQL(o,d);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=u.gql`
|
|
337
337
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
338
338
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
339
339
|
${this.QueryReturnFieldList}
|
|
340
340
|
}
|
|
341
341
|
}
|
|
342
|
-
`,
|
|
342
|
+
`,d={QueryName:e};t!==void 0&&(d.CategoryID=t),r!==void 0&&(d.CategoryPath=r),n!==void 0&&(d.Parameters=n),a!==void 0&&(d.MaxRows=a),i!==void 0&&(d.StartRow=i);const l=await this.ExecuteGQL(o,d);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
343
343
|
Success
|
|
344
344
|
QueryID
|
|
345
345
|
QueryName
|
|
@@ -364,14 +364,14 @@
|
|
|
364
364
|
}
|
|
365
365
|
}
|
|
366
366
|
}
|
|
367
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const
|
|
367
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const d=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:d,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(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 n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:S,v:h}=await this.getEntityNameAndUserView(e,t);i=h,a=S}const o=this.Entities.find(S=>S.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let d=!1;const l=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(d=!0,r=`Run${l}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),d||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(S=>({expression:S.expression,alias:S.alias})));const f=this.getViewRunTimeFieldList(o,i,e,d),E=e.Aggregates&&e.Aggregates.length>0?`
|
|
368
368
|
AggregateResults {
|
|
369
369
|
alias
|
|
370
370
|
expression
|
|
371
371
|
value
|
|
372
372
|
error
|
|
373
373
|
}
|
|
374
|
-
AggregateExecutionTime`:"",
|
|
374
|
+
AggregateExecutionTime`:"",m=u.gql`
|
|
375
375
|
query RunViewQuery ($input: ${s}!) {
|
|
376
376
|
${r}(input: $input) {
|
|
377
377
|
Results {
|
|
@@ -385,7 +385,7 @@
|
|
|
385
385
|
Success
|
|
386
386
|
ErrorMessage${E}
|
|
387
387
|
}
|
|
388
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(
|
|
388
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(m,{input:n});if(g&&g[r]){const S=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:g[r].AggregateExecutionTime});const h=g[r].Results;if(h&&h.length>0){const C=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);h.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(N=>{v[N.Name]=v[N.CodeName]})})}return g[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=[],n=[];for(const l of e){let f="",E="";const m={};let g=null,S=null;if(l.ViewEntity)S=l.ViewEntity,g=S.Get("Entity");else{const{entityName:v,v:N}=await this.getEntityNameAndUserView(l,t);S=N,g=v}const h=this.Entities.find(v=>v.Name===g);if(!h)throw new Error(`Entity ${g} not found in metadata`);s.push(h);let D=!1;const C=c.getGraphQLTypeNameBase(h);l.ViewID?(f=`Run${C}ViewByID`,E="RunViewByIDInput",m.ViewID=l.ViewID):l.ViewName?(f=`Run${C}ViewByName`,E="RunViewByNameInput",m.ViewName=l.ViewName):(D=!0,f=`Run${C}DynamicView`,E="RunDynamicViewInput",m.EntityName=l.EntityName),m.ExtraFilter=l.ExtraFilter||"",m.OrderBy=l.OrderBy||"",m.UserSearchString=l.UserSearchString||"",m.Fields=l.Fields,m.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(m.MaxRows=l.MaxRows),l.StartRow!==void 0&&(m.StartRow=l.StartRow),l.AfterKey&&(m.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),m.ForceAuditLog=l.ForceAuditLog||!1,m.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(m.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(m.BypassCache=l.BypassCache),D||(m.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=l.OverrideExcludeFilter||"",m.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(m.Aggregates=l.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(m),n.push(...this.getViewRunTimeFieldList(h,S,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
389
389
|
AggregateResults {
|
|
390
390
|
alias
|
|
391
391
|
expression
|
|
@@ -410,7 +410,7 @@
|
|
|
410
410
|
Success
|
|
411
411
|
ErrorMessage${i}
|
|
412
412
|
}
|
|
413
|
-
}`,
|
|
413
|
+
}`,d=await this.ExecuteGQL(o,{input:r});if(d&&d.RunViews){const l=d.RunViews;for(const[f,E]of l.entries())E.Results=E.Results.map(m=>{let g=JSON.parse(m.Data);return this.ConvertBackToMJFields(g),g});return l}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,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,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=u.gql`
|
|
414
414
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
415
415
|
RunViewsWithCacheCheck(input: $input) {
|
|
416
416
|
success
|
|
@@ -443,7 +443,7 @@
|
|
|
443
443
|
}
|
|
444
444
|
}
|
|
445
445
|
}
|
|
446
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,
|
|
446
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,d)=>{const l=e[d];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(E=>{const m=JSON.parse(E.Data);return this.ConvertBackToMJFields(m),m});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(E=>{const m=JSON.parse(E.Data);return this.ConvertBackToMJFields(m),m});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(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 M.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await M.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new w;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
447
447
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
448
448
|
EntityName
|
|
449
449
|
RelatedEntityName
|
|
@@ -494,32 +494,32 @@
|
|
|
494
494
|
Message
|
|
495
495
|
}
|
|
496
496
|
}
|
|
497
|
-
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,
|
|
498
|
-
${e.Fields.map(g=>
|
|
497
|
+
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,d=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),l=new w,f=` ${o}(input: $input) {
|
|
498
|
+
${e.Fields.map(g=>l.MapFieldName(g.CodeName)).join(`
|
|
499
499
|
`)}
|
|
500
500
|
}`,E=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
|
|
501
501
|
${f}
|
|
502
502
|
}
|
|
503
|
-
`;for(let g=0;g<
|
|
504
|
-
${
|
|
505
|
-
${e.Fields.filter(
|
|
503
|
+
`;for(let g=0;g<d.length;g++){const S=d[g];let h=e.Get(S.Name);if(h)switch(S.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:h=h.getTime();break;case c.EntityFieldTSType.Boolean:typeof h!="boolean"&&(h=parseInt(h)!==0);break;case c.EntityFieldTSType.Number:if(typeof h!="number"){const D=Number(h);isNaN(D)||(h=D)}break}h===null&&S.EntityFieldInfo.AllowsNull===!1&&(S.EntityFieldInfo.DefaultValue!==null?h=S.EntityFieldInfo.DefaultValue:S.FieldType===c.EntityFieldTSType.Number||S.FieldType===c.EntityFieldTSType.Boolean?h=0:h=""),n.input[l.MapFieldName(S.CodeName)]=h}const m=e.RestoreContext;if(m&&(n.input.RestoreContext___={SourceChangeID:m.SourceChangeID,Reason:m.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(S=>{let h=null;S.OldValue!==null&&S.OldValue!==void 0&&(S.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?h=S.OldValue.getTime().toString():S.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?h=S.OldValue===!0?"1":"0":typeof S.OldValue!="string"?h=S.OldValue.toString():h=S.OldValue),g.push({Key:l.MapFieldName(S.CodeName),Value:h})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:g},(S,h)=>{s.EndedAt=new Date,h&&S?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(S)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(E,n);if(g&&g[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let m=0;m<t.KeyValuePairs.length;m++){const g=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[m].FieldName.trim().toLowerCase()).EntityFieldInfo,S=t.GetValueByIndex(m),h=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${h}!`,a.length>0&&(a+=", "),a+=`${g.CodeName}: $${g.CodeName}`,g.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(m)))throw new Error(`Primary Key value ${S} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(S)}else n[g.CodeName]=S}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",d=c.getGraphQLTypeNameBase(e.EntityInfo),l=new w,f=u.gql`query Single${d}${o.length>0?"Full":""} (${i}) {
|
|
504
|
+
${d}(${a}) {
|
|
505
|
+
${e.Fields.filter(m=>!m.EntityFieldInfo.IsBinaryFieldType).map(m=>m.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?m.CodeName.replace("__mj_","_mj__"):m.CodeName).join(`
|
|
506
506
|
`)}
|
|
507
507
|
${o}
|
|
508
508
|
}
|
|
509
509
|
}
|
|
510
|
-
`,E=await this.ExecuteGQL(f,n);return E&&E[
|
|
510
|
+
`,E=await this.ExecuteGQL(f,n);return E&&E[d]?this.ConvertBackToMJFields(E[d]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return new w().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>R.UUIDsEqual(o.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
511
511
|
${i} {
|
|
512
512
|
${a.Fields.map(o=>o.CodeName).join(`
|
|
513
513
|
`)}
|
|
514
514
|
}
|
|
515
|
-
`}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(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",
|
|
516
|
-
`),
|
|
517
|
-
${
|
|
515
|
+
`}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(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",d="";for(let g of e.PrimaryKey.KeyValuePairs){const S=e.Fields.find(h=>h.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());n[S.CodeName]=S.Value,a.push({varName:S.CodeName,inputType:S.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${S.CodeName}: $${S.CodeName}`,o.length>0&&(o+=", "),o+=`$${S.CodeName}: ${S.EntityFieldInfo.GraphQLType}!`,d.length>0&&(d+=`
|
|
516
|
+
`),d+=`${S.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),E=u.gql`${f}(${i}, options___: $options___) {
|
|
517
|
+
${d}
|
|
518
518
|
}
|
|
519
|
-
`,
|
|
519
|
+
`,m=u.gql`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
|
|
520
520
|
${E}
|
|
521
521
|
}
|
|
522
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",E,n,{mutationName:f,mutationInputTypes:a},(g,
|
|
522
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",E,n,{mutationName:f,mutationInputTypes:a},(g,S)=>{if(s.EndedAt=new Date,S&&g){let h=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==g[D.FieldName]&&(h=!1);h?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(m,n);if(g&&g[f]){const S=g[f];for(let h of e.PrimaryKey.KeyValuePairs){let D=S[h.FieldName],C=h.Value;if(typeof C=="number"&&(C=C.toString()),typeof D=="number"&&(D=D.toString()),C!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${h.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
523
523
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
524
524
|
DatasetID
|
|
525
525
|
DatasetName
|
|
@@ -551,7 +551,7 @@
|
|
|
551
551
|
Success
|
|
552
552
|
IsFavorite
|
|
553
553
|
}
|
|
554
|
-
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(
|
|
554
|
+
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(d=>d.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
555
555
|
SetRecordFavoriteStatus(params: $params){
|
|
556
556
|
Success
|
|
557
557
|
}
|
|
@@ -586,16 +586,16 @@
|
|
|
586
586
|
ErrorMessage
|
|
587
587
|
Result
|
|
588
588
|
}
|
|
589
|
-
}`,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 p.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(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=p.Instance&&p.Instance._configData===this._configData;if(e&&p.Instance._refreshPromise)return p.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(p.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&p.Instance&&(p.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,p.Instance&&p.Instance._configData===this._configData&&(p.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return p.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,
|
|
589
|
+
}`,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 p.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(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=p.Instance&&p.Instance._configData===this._configData;if(e&&p.Instance._refreshPromise)return p.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(p.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&p.Instance&&(p.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,p.Instance&&p.Instance._configData===this._configData&&(p.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return p.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,d]of this._dynamicHeaders)i.setHeader(o,d);return i}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__")+`
|
|
590
590
|
`:s.startsWith("_")||(t+=s+`
|
|
591
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}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._isDisposingSocketIntentionally=!1,this._wsClient=U.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",()=>{this._isDisposingSocketIntentionally||this._socketStateSubject.next("disconnected")}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new b.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:y(a=>{r.next(a.data)},"next"),error:y(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(
|
|
591
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}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._isDisposingSocketIntentionally=!1,this._wsClient=U.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",()=>{this._isDisposingSocketIntentionally||this._socketStateSubject.next("disconnected")}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new b.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:y(a=>{r.next(a.data)},"next"),error:y(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(d){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",d),r.error(d)}}else r.error(a)},"error"),complete:y(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new b.Observable(o=>{r.activeSubscribers++;const d=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,d.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
|
|
592
592
|
statusUpdates(sessionId: $sessionId) {
|
|
593
593
|
date
|
|
594
594
|
message
|
|
595
595
|
sessionId
|
|
596
596
|
}
|
|
597
597
|
}
|
|
598
|
-
`,n=new b.Subject,a=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(o=>{const
|
|
598
|
+
`,n=new b.Subject,a=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(o=>{const d=a.subscribe({query:s,variables:{sessionId:e}},{next:y(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:y(async l=>{const f=l;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(m){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",m),o.error(m)}}else o.error(l)},"error"),complete:y(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,d()}}).subscribe({next:y(o=>n.next(o),"next"),error:y(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:y(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(o=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers++;const l=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
|
|
599
599
|
subscription ClientToolRequest($sessionID: String!) {
|
|
600
600
|
ClientToolRequest(sessionID: $sessionID) {
|
|
601
601
|
AgentRunID
|
|
@@ -1406,7 +1406,7 @@
|
|
|
1406
1406
|
failedAccounts
|
|
1407
1407
|
}
|
|
1408
1408
|
}
|
|
1409
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(
|
|
1409
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(d=>({path:d.path,name:d.name,size:d.size,contentType:d.contentType,lastModified:new Date(d.lastModified),relevance:d.relevance,excerpt:d.excerpt,matchInFilename:d.matchInFilename,objectId:d.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class ge{static{y(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
|
|
1410
1410
|
mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
|
|
1411
1411
|
SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
|
|
1412
1412
|
Success
|
|
@@ -1545,7 +1545,7 @@
|
|
|
1545
1545
|
ElapsedMs
|
|
1546
1546
|
ErrorMessage
|
|
1547
1547
|
}
|
|
1548
|
-
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:y(
|
|
1548
|
+
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:y(d=>{const l=d?.SearchStreamEvents;l&&(t.next(l),l.Phase==="final"?(t.complete(),n?.unsubscribe()):l.Phase==="error"&&(t.error(new Error(l.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:y(d=>t.error(d),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class me{static{y(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
|
|
1549
1549
|
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1550
1550
|
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1551
1551
|
Success
|
|
@@ -1696,7 +1696,7 @@
|
|
|
1696
1696
|
PipelineSteps { Name Status DurationMs Message }
|
|
1697
1697
|
GitCommitSuccess APIRestarted
|
|
1698
1698
|
}
|
|
1699
|
-
}`,
|
|
1699
|
+
}`,d={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(E=>({SourceObjectID:E.SourceObjectID??null,SourceObjectName:E.SourceObjectName??null,Fields:E.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(o,{input:d,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplyAll(
|
|
1700
1700
|
$input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1701
1701
|
) {
|
|
1702
1702
|
IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|