@memberjunction/ng-react
Version:
Angular components for hosting React components in MemberJunction applications
219 lines • 9.24 kB
JavaScript
/**
* @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality
* @module @memberjunction/ng-react/utilities
*/
import { __decorate } from "tslib";
import { Metadata, RunView, RunQuery, LogError, BaseEntity } from '@memberjunction/core';
import { MJGlobal, RegisterClass } from '@memberjunction/global';
import { GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';
import { SimpleVectorService } from '@memberjunction/ai-vectors-memory';
/**
* Base class for providing runtime utilities to React components in Angular.
* This class can be extended and registered with MJ's ClassFactory
* to provide custom implementations of data access methods.
*/
let RuntimeUtilities = class RuntimeUtilities {
constructor() {
this.debug = false;
}
/**
* Builds the complete utilities object for React components
* This is the main method that components will use
*/
buildUtilities(debug = false) {
this.debug = debug;
const md = new Metadata();
return this.SetupUtilities(md);
}
/**
* Sets up the utilities object - copied from skip-chat implementation
*/
SetupUtilities(md) {
const rv = new RunView();
const rq = new RunQuery();
const u = {
md: this.CreateSimpleMetadata(md),
rv: this.CreateSimpleRunView(rv),
rq: this.CreateSimpleRunQuery(rq),
ai: this.CreateSimpleAITools()
};
return u;
}
CreateSimpleAITools() {
// Get the GraphQL provider - it's the same as the BaseEntity provider
const provider = BaseEntity.Provider;
// Check if it's a GraphQLDataProvider
if (!(provider instanceof GraphQLDataProvider)) {
throw new Error('Current data provider is not a GraphQLDataProvider. AI tools require GraphQL provider.');
}
const graphQLProvider = provider;
return {
ExecutePrompt: async (params) => {
try {
// Use the AI client from GraphQLDataProvider to execute simple prompt
const result = await graphQLProvider.AI.ExecuteSimplePrompt({
systemPrompt: params.systemPrompt,
messages: params.messages,
preferredModels: params.preferredModels,
modelPower: params.modelPower
});
console.log(`🤖 ExecutePrompt succeeded!`);
if (this.debug) {
console.log(' > params', params);
console.log(' > result:', result);
}
return {
success: result.success,
result: result.result || '',
resultObject: result.resultObject,
modelName: result.modelName || ''
};
}
catch (error) {
LogError(error);
return {
success: false,
result: 'Failed to execute prompt: ' + (error instanceof Error ? error.message : String(error)),
modelName: ''
};
}
},
EmbedText: async (params) => {
try {
// Use the AI client from GraphQLDataProvider to generate embeddings
const result = await graphQLProvider.AI.EmbedText({
textToEmbed: params.textToEmbed,
modelSize: params.modelSize
});
if (result.error) {
throw new Error(result.error || 'Failed to generate embeddings');
}
const numEmbeddings = Array.isArray(params.textToEmbed) ? result.embeddings?.length : 1;
console.log(`🤖 EmbedText succeeded! ${numEmbeddings} embeddings returned`);
if (this.debug) {
console.log(' > params', params);
console.log(' > result:', result);
}
return {
result: result.embeddings,
modelName: result.modelName,
vectorDimensions: result.vectorDimensions
};
}
catch (error) {
LogError(error);
throw error; // Re-throw for embeddings as they're critical
}
},
VectorService: new SimpleVectorService()
};
}
CreateSimpleMetadata(md) {
return {
Entities: md.Entities,
GetEntityObject: (entityName) => {
return md.GetEntityObject(entityName);
}
};
}
CreateSimpleRunQuery(rq) {
return {
RunQuery: async (params) => {
// Run a single query and return the results
try {
const result = await rq.RunQuery(params);
if (result.Success) {
console.log(`✅ RunQuery "${params.QueryName}" succeeded: ${result.RowCount} rows returned`);
if (this.debug) {
console.log(' > params', params);
console.log(' > result:', result);
}
}
else {
console.error(`❌ RunQuery failed: ${result.ErrorMessage}`);
}
return result;
}
catch (error) {
console.error(`❌ RunQuery threw exception:`, error);
LogError(error);
throw error; // Re-throw to handle it in the caller
}
}
};
}
CreateSimpleRunView(rv) {
return {
RunView: async (params) => {
// Run a single view and return the results
try {
const result = await rv.RunView(params);
if (result.Success) {
console.log(`✅ RunView succeeded for ${params.EntityName}: ${result.TotalRowCount} rows returned`);
if (this.debug) {
console.log(' > params', params);
console.log(' > result:', result);
}
}
else {
console.error(`❌ RunView failed for ${params.EntityName}: ${result.ErrorMessage}`);
}
return result;
}
catch (error) {
console.error(`❌ RunView threw exception:`, error);
LogError(error);
throw error; // Re-throw to handle it in the caller
}
},
RunViews: async (params) => {
// Runs multiple views and returns the results
try {
const results = await rv.RunViews(params);
const entityNames = params.map(p => p.EntityName).join(', ');
const totalRows = results.reduce((sum, r) => sum + (r.TotalRowCount || 0), 0);
console.log(`✅ RunViews succeeded for [${entityNames}]: ${totalRows} total rows returned`);
if (this.debug) {
console.log(' > params', params);
console.log(' > results:', results);
}
return results;
}
catch (error) {
console.error(`❌ RunViews threw exception:`, error);
LogError(error);
throw error; // Re-throw to handle it in the caller
}
}
};
}
};
RuntimeUtilities = __decorate([
RegisterClass(RuntimeUtilities, 'RuntimeUtilities')
], RuntimeUtilities);
export { RuntimeUtilities };
/**
* Factory function to create RuntimeUtilities
* In a Node.js environment, this will use MJ's ClassFactory for runtime substitution
* In a browser environment, it will use the base class directly
*/
export function createRuntimeUtilities() {
// Check if we're in a Node.js environment with MJGlobal available
if (typeof window === 'undefined') {
try {
// Use ClassFactory to get the registered class, defaulting to base RuntimeUtilities
const obj = MJGlobal.Instance.ClassFactory.CreateInstance(RuntimeUtilities);
if (!obj) {
throw new Error('Failed to create RuntimeUtilities instance');
}
// Ensure the object is an instance of RuntimeUtilities
return obj;
}
catch (e) {
// Fall through to default
}
}
// Default: just use the base class
return new RuntimeUtilities();
}
//# sourceMappingURL=runtime-utilities.js.map