@memberjunction/ng-react 6.1.4 → 6.2.0-edge.1
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/__tests__/react-bridge.service.test.js +11 -3
- package/dist/__tests__/react-bridge.service.test.js.map +1 -1
- package/dist/lib/components/mj-react-component.component.d.ts +128 -14
- package/dist/lib/components/mj-react-component.component.js +313 -207
- package/dist/lib/components/mj-react-component.component.js.map +1 -1
- package/dist/lib/config/react-debug.config.d.ts +4 -0
- package/dist/lib/config/react-debug.config.js +10 -2
- package/dist/lib/config/react-debug.config.js.map +1 -1
- package/dist/lib/hooks/antd-dropdown-position-hook.d.ts +2 -0
- package/dist/lib/hooks/antd-dropdown-position-hook.js +5 -1
- package/dist/lib/hooks/antd-dropdown-position-hook.js.map +1 -1
- package/dist/lib/services/angular-adapter.service.d.ts +32 -0
- package/dist/lib/services/angular-adapter.service.js +78 -18
- package/dist/lib/services/angular-adapter.service.js.map +1 -1
- package/dist/lib/services/react-bridge.service.d.ts +26 -2
- package/dist/lib/services/react-bridge.service.js +66 -18
- package/dist/lib/services/react-bridge.service.js.map +1 -1
- package/dist/lib/services/script-loader.service.d.ts +17 -0
- package/dist/lib/services/script-loader.service.js +26 -6
- package/dist/lib/services/script-loader.service.js.map +1 -1
- package/package.json +10 -10
- package/dist/__tests__/runtime-utilities-ml.test.d.ts +0 -1
- package/dist/__tests__/runtime-utilities-ml.test.js +0 -170
- package/dist/__tests__/runtime-utilities-ml.test.js.map +0 -1
- package/dist/lib/utilities/runtime-utilities.d.ts +0 -80
- package/dist/lib/utilities/runtime-utilities.js +0 -396
- package/dist/lib/utilities/runtime-utilities.js.map +0 -1
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @vitest-environment jsdom
|
|
3
|
-
*
|
|
4
|
-
* Focused tests for the ML tools surface (`ComponentUtilities.ml`) built by RuntimeUtilities.
|
|
5
|
-
* The provider statics and the Predictive Studio Remote Operation are mocked so we can exercise
|
|
6
|
-
* the listModels RunView mapping and the score Remote-Op marshalling without a live backend.
|
|
7
|
-
*/
|
|
8
|
-
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
9
|
-
// Hoisted so the `vi.mock` factories (which are themselves hoisted above the imports) can
|
|
10
|
-
// safely reference these without a "before initialization" error.
|
|
11
|
-
const { MockGraphQLDataProvider, mockProviderInstance, mockRunView, mockScoreExecute } = vi.hoisted(() => {
|
|
12
|
-
class MockGraphQLDataProvider {
|
|
13
|
-
}
|
|
14
|
-
return {
|
|
15
|
-
// Mock the GraphQL provider so `BaseEntity.Provider instanceof GraphQLDataProvider` is true.
|
|
16
|
-
MockGraphQLDataProvider,
|
|
17
|
-
mockProviderInstance: new MockGraphQLDataProvider(),
|
|
18
|
-
// Controllable RunView mock.
|
|
19
|
-
mockRunView: vi.fn(),
|
|
20
|
-
// Controllable Remote Operation mock.
|
|
21
|
-
mockScoreExecute: vi.fn()
|
|
22
|
-
};
|
|
23
|
-
});
|
|
24
|
-
vi.mock('@memberjunction/core', async (importOriginal) => {
|
|
25
|
-
const actual = await importOriginal();
|
|
26
|
-
return {
|
|
27
|
-
...actual,
|
|
28
|
-
LogError: vi.fn(),
|
|
29
|
-
BaseEntity: { Provider: mockProviderInstance },
|
|
30
|
-
// RuntimeUtilities now reads through a provider rather than constructing a global RunView,
|
|
31
|
-
// so the mock has to answer the static factory and the global-provider fallback.
|
|
32
|
-
Metadata: Object.assign(class {
|
|
33
|
-
constructor() {
|
|
34
|
-
this.Entities = [];
|
|
35
|
-
this.GetEntityObject = vi.fn();
|
|
36
|
-
}
|
|
37
|
-
}, { Provider: mockProviderInstance }),
|
|
38
|
-
RunView: Object.assign(class {
|
|
39
|
-
constructor() {
|
|
40
|
-
this.RunView = mockRunView;
|
|
41
|
-
this.RunViews = vi.fn();
|
|
42
|
-
}
|
|
43
|
-
}, { FromMetadataProvider: () => ({ RunView: mockRunView, RunViews: vi.fn() }) }),
|
|
44
|
-
RunQuery: class {
|
|
45
|
-
constructor() {
|
|
46
|
-
this.RunQuery = vi.fn();
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
});
|
|
51
|
-
vi.mock('@memberjunction/graphql-dataprovider', () => ({
|
|
52
|
-
GraphQLDataProvider: MockGraphQLDataProvider
|
|
53
|
-
}));
|
|
54
|
-
vi.mock('@memberjunction/core-entities', () => ({
|
|
55
|
-
GeoDataEngine: { Instance: undefined },
|
|
56
|
-
MJMLModelEntity: class {
|
|
57
|
-
},
|
|
58
|
-
PredictiveStudioScoreRecordSetOperation: class {
|
|
59
|
-
constructor() {
|
|
60
|
-
this.Execute = mockScoreExecute;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
}));
|
|
64
|
-
vi.mock('@memberjunction/ai-vectors-memory', () => ({
|
|
65
|
-
SimpleVectorService: class {
|
|
66
|
-
}
|
|
67
|
-
}));
|
|
68
|
-
vi.mock('@memberjunction/global', async (importOriginal) => {
|
|
69
|
-
const actual = await importOriginal();
|
|
70
|
-
return { ...actual };
|
|
71
|
-
});
|
|
72
|
-
import { RuntimeUtilities } from '../lib/utilities/runtime-utilities';
|
|
73
|
-
describe('RuntimeUtilities — SimpleMLTools', () => {
|
|
74
|
-
beforeEach(() => {
|
|
75
|
-
vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
76
|
-
vi.spyOn(console, 'error').mockImplementation(() => { });
|
|
77
|
-
mockRunView.mockReset();
|
|
78
|
-
mockScoreExecute.mockReset();
|
|
79
|
-
});
|
|
80
|
-
it('exposes an `ml` capability when a GraphQL provider is present', () => {
|
|
81
|
-
const u = new RuntimeUtilities().buildUtilities();
|
|
82
|
-
expect(u.ml).toBeDefined();
|
|
83
|
-
expect(typeof u.ml.listModels).toBe('function');
|
|
84
|
-
expect(typeof u.ml.score).toBe('function');
|
|
85
|
-
});
|
|
86
|
-
it('listModels maps MJ: ML Models rows and parses JSON metrics', async () => {
|
|
87
|
-
mockRunView.mockResolvedValue({
|
|
88
|
-
Success: true,
|
|
89
|
-
Results: [
|
|
90
|
-
{
|
|
91
|
-
ID: 'M1',
|
|
92
|
-
Pipeline: 'Renewal Pipeline',
|
|
93
|
-
Version: 3,
|
|
94
|
-
TargetVariable: 'Renewed',
|
|
95
|
-
ProblemType: 'classification',
|
|
96
|
-
Status: 'Published',
|
|
97
|
-
Metrics: '{"auc":0.91}',
|
|
98
|
-
HoldoutMetrics: 'not-json'
|
|
99
|
-
}
|
|
100
|
-
]
|
|
101
|
-
});
|
|
102
|
-
const u = new RuntimeUtilities().buildUtilities();
|
|
103
|
-
const models = await u.ml.listModels();
|
|
104
|
-
expect(mockRunView).toHaveBeenCalledTimes(1);
|
|
105
|
-
const params = mockRunView.mock.calls[0][0];
|
|
106
|
-
expect(params.EntityName).toBe('MJ: ML Models');
|
|
107
|
-
expect(params.ExtraFilter).toBe("Status='Published'");
|
|
108
|
-
expect(params.OrderBy).toBe('Version DESC');
|
|
109
|
-
expect(models).toHaveLength(1);
|
|
110
|
-
expect(models[0]).toMatchObject({
|
|
111
|
-
id: 'M1',
|
|
112
|
-
pipeline: 'Renewal Pipeline',
|
|
113
|
-
version: 3,
|
|
114
|
-
targetVariable: 'Renewed',
|
|
115
|
-
problemType: 'classification',
|
|
116
|
-
status: 'Published',
|
|
117
|
-
metrics: { auc: 0.91 }
|
|
118
|
-
});
|
|
119
|
-
// Invalid JSON is defensively dropped to undefined.
|
|
120
|
-
expect(models[0].holdoutMetrics).toBeUndefined();
|
|
121
|
-
});
|
|
122
|
-
it('listModels applies status/targetVariable/maxResults filter and returns [] on failure', async () => {
|
|
123
|
-
mockRunView.mockResolvedValue({ Success: false, ErrorMessage: 'boom', Results: [] });
|
|
124
|
-
const u = new RuntimeUtilities().buildUtilities();
|
|
125
|
-
const models = await u.ml.listModels({ status: 'Validated', targetVariable: "O'Brien", maxResults: 5 });
|
|
126
|
-
const params = mockRunView.mock.calls[0][0];
|
|
127
|
-
expect(params.ExtraFilter).toBe("Status='Validated' AND TargetVariable='O''Brien'");
|
|
128
|
-
expect(params.MaxRows).toBe(5);
|
|
129
|
-
expect(models).toEqual([]);
|
|
130
|
-
});
|
|
131
|
-
it('score normalizes record keys, requests ephemeral predictions, and maps the result', async () => {
|
|
132
|
-
mockScoreExecute.mockResolvedValue({
|
|
133
|
-
Success: true,
|
|
134
|
-
Output: {
|
|
135
|
-
scored: 2,
|
|
136
|
-
failed: 0,
|
|
137
|
-
skipped: 1,
|
|
138
|
-
wroteBack: false,
|
|
139
|
-
predictions: [
|
|
140
|
-
{ recordId: 'R1', score: 0.8, class: 'Yes' },
|
|
141
|
-
{ recordId: 'R2', score: 0.2, class: 'No' }
|
|
142
|
-
]
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
const u = new RuntimeUtilities().buildUtilities();
|
|
146
|
-
const result = await u.ml.score('M1', ['R1', { ID: 'R2' }, { Other: 'R3' }], { primaryKeyField: 'ID' });
|
|
147
|
-
expect(mockScoreExecute).toHaveBeenCalledTimes(1);
|
|
148
|
-
const [input, ctx] = mockScoreExecute.mock.calls[0];
|
|
149
|
-
expect(input.modelId).toBe('M1');
|
|
150
|
-
expect(input.scope).toEqual({ records: ['R1', 'R2'] }); // Other-keyed object dropped (no ID)
|
|
151
|
-
expect(input.writeBack).toBeUndefined(); // ephemeral
|
|
152
|
-
expect(ctx.provider).toBe(mockProviderInstance);
|
|
153
|
-
expect(result).toEqual({
|
|
154
|
-
scoredCount: 2,
|
|
155
|
-
failedCount: 0,
|
|
156
|
-
skippedCount: 1,
|
|
157
|
-
predictions: [
|
|
158
|
-
{ recordId: 'R1', score: 0.8, class: 'Yes' },
|
|
159
|
-
{ recordId: 'R2', score: 0.2, class: 'No' }
|
|
160
|
-
]
|
|
161
|
-
});
|
|
162
|
-
});
|
|
163
|
-
it('score returns a zeroed result with records counted as failed on error', async () => {
|
|
164
|
-
mockScoreExecute.mockResolvedValue({ Success: false, ErrorMessage: 'no model' });
|
|
165
|
-
const u = new RuntimeUtilities().buildUtilities();
|
|
166
|
-
const result = await u.ml.score('M1', ['R1', 'R2']);
|
|
167
|
-
expect(result).toEqual({ scoredCount: 0, failedCount: 2, skippedCount: 0, predictions: [] });
|
|
168
|
-
});
|
|
169
|
-
});
|
|
170
|
-
//# sourceMappingURL=runtime-utilities-ml.test.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-utilities-ml.test.js","sourceRoot":"","sources":["../../src/__tests__/runtime-utilities-ml.test.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAE9D,0FAA0F;AAC1F,kEAAkE;AAClE,MAAM,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,WAAW,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;IACvG,MAAM,uBAAuB;KAAG;IAChC,OAAO;QACL,6FAA6F;QAC7F,uBAAuB;QACvB,oBAAoB,EAAE,IAAI,uBAAuB,EAAE;QACnD,6BAA6B;QAC7B,WAAW,EAAE,EAAE,CAAC,EAAE,EAAE;QACpB,sCAAsC;QACtC,gBAAgB,EAAE,EAAE,CAAC,EAAE,EAAE;KAC1B,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,EAAE,CAAC,IAAI,CAAC,sBAAsB,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE;IACvD,MAAM,MAAM,GAAG,MAAM,cAAc,EAAyC,CAAC;IAC7E,OAAO;QACL,GAAG,MAAM;QACT,QAAQ,EAAE,EAAE,CAAC,EAAE,EAAE;QACjB,UAAU,EAAE,EAAE,QAAQ,EAAE,oBAAoB,EAAE;QAC9C,2FAA2F;QAC3F,iFAAiF;QACjF,QAAQ,EAAE,MAAM,CAAC,MAAM,CACrB;YAAA;gBACE,aAAQ,GAAG,EAAE,CAAC;gBACd,oBAAe,GAAG,EA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QAErD,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;IAC/F,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/**\n * @vitest-environment jsdom\n *\n * Focused tests for the ML tools surface (`ComponentUtilities.ml`) built by RuntimeUtilities.\n * The provider statics and the Predictive Studio Remote Operation are mocked so we can exercise\n * the listModels RunView mapping and the score Remote-Op marshalling without a live backend.\n */\nimport { describe, it, expect, vi, beforeEach } from 'vitest';\n\n// Hoisted so the `vi.mock` factories (which are themselves hoisted above the imports) can\n// safely reference these without a \"before initialization\" error.\nconst { MockGraphQLDataProvider, mockProviderInstance, mockRunView, mockScoreExecute } = vi.hoisted(() => {\n class MockGraphQLDataProvider {}\n return {\n // Mock the GraphQL provider so `BaseEntity.Provider instanceof GraphQLDataProvider` is true.\n MockGraphQLDataProvider,\n mockProviderInstance: new MockGraphQLDataProvider(),\n // Controllable RunView mock.\n mockRunView: vi.fn(),\n // Controllable Remote Operation mock.\n mockScoreExecute: vi.fn()\n };\n});\n\nvi.mock('@memberjunction/core', async (importOriginal) => {\n const actual = await importOriginal<typeof import('@memberjunction/core')>();\n return {\n ...actual,\n LogError: vi.fn(),\n BaseEntity: { Provider: mockProviderInstance },\n // RuntimeUtilities now reads through a provider rather than constructing a global RunView,\n // so the mock has to answer the static factory and the global-provider fallback.\n Metadata: Object.assign(\n class {\n Entities = [];\n GetEntityObject = vi.fn();\n },\n { Provider: mockProviderInstance },\n ),\n RunView: Object.assign(\n class {\n RunView = mockRunView;\n RunViews = vi.fn();\n },\n { FromMetadataProvider: () => ({ RunView: mockRunView, RunViews: vi.fn() }) },\n ),\n RunQuery: class {\n RunQuery = vi.fn();\n }\n };\n});\n\nvi.mock('@memberjunction/graphql-dataprovider', () => ({\n GraphQLDataProvider: MockGraphQLDataProvider\n}));\n\nvi.mock('@memberjunction/core-entities', () => ({\n GeoDataEngine: { Instance: undefined },\n MJMLModelEntity: class {},\n PredictiveStudioScoreRecordSetOperation: class {\n Execute = mockScoreExecute;\n }\n}));\n\nvi.mock('@memberjunction/ai-vectors-memory', () => ({\n SimpleVectorService: class {}\n}));\n\nvi.mock('@memberjunction/global', async (importOriginal) => {\n const actual = await importOriginal<typeof import('@memberjunction/global')>();\n return { ...actual };\n});\n\nimport { RuntimeUtilities } from '../lib/utilities/runtime-utilities';\n\ndescribe('RuntimeUtilities — SimpleMLTools', () => {\n beforeEach(() => {\n vi.spyOn(console, 'log').mockImplementation(() => {});\n vi.spyOn(console, 'error').mockImplementation(() => {});\n mockRunView.mockReset();\n mockScoreExecute.mockReset();\n });\n\n it('exposes an `ml` capability when a GraphQL provider is present', () => {\n const u = new RuntimeUtilities().buildUtilities();\n expect(u.ml).toBeDefined();\n expect(typeof u.ml!.listModels).toBe('function');\n expect(typeof u.ml!.score).toBe('function');\n });\n\n it('listModels maps MJ: ML Models rows and parses JSON metrics', async () => {\n mockRunView.mockResolvedValue({\n Success: true,\n Results: [\n {\n ID: 'M1',\n Pipeline: 'Renewal Pipeline',\n Version: 3,\n TargetVariable: 'Renewed',\n ProblemType: 'classification',\n Status: 'Published',\n Metrics: '{\"auc\":0.91}',\n HoldoutMetrics: 'not-json'\n }\n ]\n });\n\n const u = new RuntimeUtilities().buildUtilities();\n const models = await u.ml!.listModels();\n\n expect(mockRunView).toHaveBeenCalledTimes(1);\n const params = mockRunView.mock.calls[0][0];\n expect(params.EntityName).toBe('MJ: ML Models');\n expect(params.ExtraFilter).toBe(\"Status='Published'\");\n expect(params.OrderBy).toBe('Version DESC');\n\n expect(models).toHaveLength(1);\n expect(models[0]).toMatchObject({\n id: 'M1',\n pipeline: 'Renewal Pipeline',\n version: 3,\n targetVariable: 'Renewed',\n problemType: 'classification',\n status: 'Published',\n metrics: { auc: 0.91 }\n });\n // Invalid JSON is defensively dropped to undefined.\n expect(models[0].holdoutMetrics).toBeUndefined();\n });\n\n it('listModels applies status/targetVariable/maxResults filter and returns [] on failure', async () => {\n mockRunView.mockResolvedValue({ Success: false, ErrorMessage: 'boom', Results: [] });\n\n const u = new RuntimeUtilities().buildUtilities();\n const models = await u.ml!.listModels({ status: 'Validated', targetVariable: \"O'Brien\", maxResults: 5 });\n\n const params = mockRunView.mock.calls[0][0];\n expect(params.ExtraFilter).toBe(\"Status='Validated' AND TargetVariable='O''Brien'\");\n expect(params.MaxRows).toBe(5);\n expect(models).toEqual([]);\n });\n\n it('score normalizes record keys, requests ephemeral predictions, and maps the result', async () => {\n mockScoreExecute.mockResolvedValue({\n Success: true,\n Output: {\n scored: 2,\n failed: 0,\n skipped: 1,\n wroteBack: false,\n predictions: [\n { recordId: 'R1', score: 0.8, class: 'Yes' },\n { recordId: 'R2', score: 0.2, class: 'No' }\n ]\n }\n });\n\n const u = new RuntimeUtilities().buildUtilities();\n const result = await u.ml!.score('M1', ['R1', { ID: 'R2' }, { Other: 'R3' }], { primaryKeyField: 'ID' });\n\n expect(mockScoreExecute).toHaveBeenCalledTimes(1);\n const [input, ctx] = mockScoreExecute.mock.calls[0];\n expect(input.modelId).toBe('M1');\n expect(input.scope).toEqual({ records: ['R1', 'R2'] }); // Other-keyed object dropped (no ID)\n expect(input.writeBack).toBeUndefined(); // ephemeral\n expect(ctx.provider).toBe(mockProviderInstance);\n\n expect(result).toEqual({\n scoredCount: 2,\n failedCount: 0,\n skippedCount: 1,\n predictions: [\n { recordId: 'R1', score: 0.8, class: 'Yes' },\n { recordId: 'R2', score: 0.2, class: 'No' }\n ]\n });\n });\n\n it('score returns a zeroed result with records counted as failed on error', async () => {\n mockScoreExecute.mockResolvedValue({ Success: false, ErrorMessage: 'no model' });\n\n const u = new RuntimeUtilities().buildUtilities();\n const result = await u.ml!.score('M1', ['R1', 'R2']);\n\n expect(result).toEqual({ scoredCount: 0, failedCount: 2, skippedCount: 0, predictions: [] });\n });\n});\n"]}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality
|
|
3
|
-
* @module @memberjunction/ng-react/utilities
|
|
4
|
-
*/
|
|
5
|
-
import { IMetadataProvider } from '@memberjunction/core';
|
|
6
|
-
import { ComponentUtilities } from '@memberjunction/interactive-component-types';
|
|
7
|
-
/**
|
|
8
|
-
* Base class for providing runtime utilities to React components in Angular.
|
|
9
|
-
* This class can be extended and registered with MJ's ClassFactory
|
|
10
|
-
* to provide custom implementations of data access methods.
|
|
11
|
-
*/
|
|
12
|
-
export declare class RuntimeUtilities {
|
|
13
|
-
private debug;
|
|
14
|
-
/**
|
|
15
|
-
* The provider every read in the built utilities goes through. Always set by
|
|
16
|
-
* {@link buildUtilities} before use — falls back to the global provider there
|
|
17
|
-
* (`provider ?? Metadata.Provider`) when the host doesn't supply one.
|
|
18
|
-
*/
|
|
19
|
-
private provider;
|
|
20
|
-
/**
|
|
21
|
-
* Builds the complete utilities object for React components
|
|
22
|
-
* This is the main method that components will use
|
|
23
|
-
*
|
|
24
|
-
* @param provider the host's provider. A React component mounted under a non-default provider
|
|
25
|
-
* passes its own `ProviderToUse`; omitting it falls back to the global default, named
|
|
26
|
-
* explicitly rather than reached for via `new Metadata()`.
|
|
27
|
-
*/
|
|
28
|
-
buildUtilities(debug?: boolean, provider?: IMetadataProvider): ComponentUtilities;
|
|
29
|
-
/**
|
|
30
|
-
* Sets up the utilities object - copied from skip-chat implementation
|
|
31
|
-
*/
|
|
32
|
-
private SetupUtilities;
|
|
33
|
-
private CreateSimpleAITools;
|
|
34
|
-
/**
|
|
35
|
-
* Creates the ML tools surface for components — listing trained models and scoring records.
|
|
36
|
-
* `listModels` reads the `MJ: ML Models` catalog via RunView; `score` marshals the
|
|
37
|
-
* `PredictiveStudio.ScoreRecordSet` Remote Operation over GraphQL to the server engine (the
|
|
38
|
-
* Python sidecar lives server-side and cannot run in the browser). Returns `undefined` when no
|
|
39
|
-
* GraphQL provider is available, so the `ml` capability degrades cleanly.
|
|
40
|
-
*/
|
|
41
|
-
private CreateSimpleMLTools;
|
|
42
|
-
/**
|
|
43
|
-
* Loads the trained-model catalog from `MJ: ML Models`, newest version first, mapping each row
|
|
44
|
-
* to a {@link SimpleMLModelInfo}. Resilient — logs and returns `[]` on any failure.
|
|
45
|
-
*/
|
|
46
|
-
private listMLModels;
|
|
47
|
-
/**
|
|
48
|
-
* Builds the ExtraFilter clause for {@link listMLModels}. Defaults to `Status='Published'` so
|
|
49
|
-
* components only see promoted models unless the caller overrides the status.
|
|
50
|
-
*/
|
|
51
|
-
private buildMLModelsFilter;
|
|
52
|
-
/** Maps a single `MJ: ML Models` row to the component-facing {@link SimpleMLModelInfo} shape. */
|
|
53
|
-
private mapMLModel;
|
|
54
|
-
/** Defensively parses a JSON metrics blob; returns `undefined` for null/empty/invalid JSON. */
|
|
55
|
-
private parseMLMetrics;
|
|
56
|
-
/**
|
|
57
|
-
* Scores records with a trained model by invoking the `PredictiveStudio.ScoreRecordSet` Remote
|
|
58
|
-
* Operation. Normalizes `records` to primary-key strings, requests ephemeral predictions (no
|
|
59
|
-
* write-back), and maps the result. Resilient — logs and returns a zeroed result with the input
|
|
60
|
-
* records counted as failed on any error.
|
|
61
|
-
*/
|
|
62
|
-
private scoreMLRecords;
|
|
63
|
-
/**
|
|
64
|
-
* Normalizes a mixed array of primary-key strings and row objects into an array of primary-key
|
|
65
|
-
* strings, reading `primaryKeyField` from objects. Drops entries without a resolvable key.
|
|
66
|
-
*/
|
|
67
|
-
private normalizeRecordKeys;
|
|
68
|
-
/** Escapes single quotes for safe inlining into a RunView ExtraFilter SQL string literal. */
|
|
69
|
-
private escapeSqlLiteral;
|
|
70
|
-
private CreateSimpleMetadata;
|
|
71
|
-
private CreateSimpleGeoDataEngine;
|
|
72
|
-
private CreateSimpleRunQuery;
|
|
73
|
-
private CreateSimpleRunView;
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Factory function to create RuntimeUtilities
|
|
77
|
-
* In a Node.js environment, this will use MJ's ClassFactory for runtime substitution
|
|
78
|
-
* In a browser environment, it will use the base class directly
|
|
79
|
-
*/
|
|
80
|
-
export declare function createRuntimeUtilities(): RuntimeUtilities;
|
|
@@ -1,396 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality
|
|
3
|
-
* @module @memberjunction/ng-react/utilities
|
|
4
|
-
*/
|
|
5
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
6
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
7
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
8
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
9
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
10
|
-
};
|
|
11
|
-
import { Metadata, RunView, RunQuery, LogError, BaseEntity } from '@memberjunction/core';
|
|
12
|
-
import { MJGlobal, RegisterClass } from '@memberjunction/global';
|
|
13
|
-
import { GeoDataEngine } from '@memberjunction/core-entities';
|
|
14
|
-
import { GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';
|
|
15
|
-
import { SimpleVectorService } from '@memberjunction/ai-vectors-memory';
|
|
16
|
-
import { PredictiveStudioScoreRecordSetOperation } from '@memberjunction/core-entities';
|
|
17
|
-
/**
|
|
18
|
-
* Base class for providing runtime utilities to React components in Angular.
|
|
19
|
-
* This class can be extended and registered with MJ's ClassFactory
|
|
20
|
-
* to provide custom implementations of data access methods.
|
|
21
|
-
*/
|
|
22
|
-
let RuntimeUtilities = class RuntimeUtilities {
|
|
23
|
-
constructor() {
|
|
24
|
-
this.debug = false;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Builds the complete utilities object for React components
|
|
28
|
-
* This is the main method that components will use
|
|
29
|
-
*
|
|
30
|
-
* @param provider the host's provider. A React component mounted under a non-default provider
|
|
31
|
-
* passes its own `ProviderToUse`; omitting it falls back to the global default, named
|
|
32
|
-
* explicitly rather than reached for via `new Metadata()`.
|
|
33
|
-
*/
|
|
34
|
-
buildUtilities(debug = false, provider) {
|
|
35
|
-
this.debug = debug;
|
|
36
|
-
this.provider = provider ?? Metadata.Provider;
|
|
37
|
-
return this.SetupUtilities(this.provider);
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Sets up the utilities object - copied from skip-chat implementation
|
|
41
|
-
*/
|
|
42
|
-
SetupUtilities(md) {
|
|
43
|
-
const rv = RunView.FromMetadataProvider(md);
|
|
44
|
-
const rq = new RunQuery(md);
|
|
45
|
-
const u = {
|
|
46
|
-
md: this.CreateSimpleMetadata(md),
|
|
47
|
-
rv: this.CreateSimpleRunView(rv),
|
|
48
|
-
rq: this.CreateSimpleRunQuery(rq),
|
|
49
|
-
ai: this.CreateSimpleAITools(),
|
|
50
|
-
geoDataEngine: this.CreateSimpleGeoDataEngine(),
|
|
51
|
-
ml: this.CreateSimpleMLTools()
|
|
52
|
-
};
|
|
53
|
-
return u;
|
|
54
|
-
}
|
|
55
|
-
CreateSimpleAITools() {
|
|
56
|
-
// Get the GraphQL provider - it's the same as the BaseEntity provider
|
|
57
|
-
const provider = BaseEntity.Provider;
|
|
58
|
-
// Check if it's a GraphQLDataProvider
|
|
59
|
-
if (!(provider instanceof GraphQLDataProvider)) {
|
|
60
|
-
throw new Error('Current data provider is not a GraphQLDataProvider. AI tools require GraphQL provider.');
|
|
61
|
-
}
|
|
62
|
-
const graphQLProvider = provider;
|
|
63
|
-
return {
|
|
64
|
-
ExecutePrompt: async (params) => {
|
|
65
|
-
try {
|
|
66
|
-
// Use the AI client from GraphQLDataProvider to execute simple prompt
|
|
67
|
-
const result = await graphQLProvider.AI.ExecuteSimplePrompt({
|
|
68
|
-
systemPrompt: params.systemPrompt,
|
|
69
|
-
messages: params.messages,
|
|
70
|
-
preferredModels: params.preferredModels,
|
|
71
|
-
modelPower: params.modelPower
|
|
72
|
-
});
|
|
73
|
-
console.log(`🤖 ExecutePrompt succeeded!`);
|
|
74
|
-
if (this.debug) {
|
|
75
|
-
console.log(' > params', params);
|
|
76
|
-
console.log(' > result:', result);
|
|
77
|
-
}
|
|
78
|
-
return {
|
|
79
|
-
success: result.success,
|
|
80
|
-
result: result.result || '',
|
|
81
|
-
resultObject: result.resultObject,
|
|
82
|
-
modelName: result.modelName || ''
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
catch (error) {
|
|
86
|
-
LogError(error);
|
|
87
|
-
return {
|
|
88
|
-
success: false,
|
|
89
|
-
result: 'Failed to execute prompt: ' + (error instanceof Error ? error.message : String(error)),
|
|
90
|
-
modelName: ''
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
},
|
|
94
|
-
EmbedText: async (params) => {
|
|
95
|
-
try {
|
|
96
|
-
// Use the AI client from GraphQLDataProvider to generate embeddings
|
|
97
|
-
const result = await graphQLProvider.AI.EmbedText({
|
|
98
|
-
textToEmbed: params.textToEmbed,
|
|
99
|
-
modelSize: params.modelSize
|
|
100
|
-
});
|
|
101
|
-
if (result.error) {
|
|
102
|
-
throw new Error(result.error || 'Failed to generate embeddings');
|
|
103
|
-
}
|
|
104
|
-
const numEmbeddings = Array.isArray(params.textToEmbed) ? result.embeddings?.length : 1;
|
|
105
|
-
console.log(`🤖 EmbedText succeeded! ${numEmbeddings} embeddings returned`);
|
|
106
|
-
if (this.debug) {
|
|
107
|
-
console.log(' > params', params);
|
|
108
|
-
console.log(' > result:', result);
|
|
109
|
-
}
|
|
110
|
-
return {
|
|
111
|
-
result: result.embeddings,
|
|
112
|
-
modelName: result.modelName,
|
|
113
|
-
vectorDimensions: result.vectorDimensions
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
catch (error) {
|
|
117
|
-
LogError(error);
|
|
118
|
-
throw error; // Re-throw for embeddings as they're critical
|
|
119
|
-
}
|
|
120
|
-
},
|
|
121
|
-
VectorService: new SimpleVectorService()
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Creates the ML tools surface for components — listing trained models and scoring records.
|
|
126
|
-
* `listModels` reads the `MJ: ML Models` catalog via RunView; `score` marshals the
|
|
127
|
-
* `PredictiveStudio.ScoreRecordSet` Remote Operation over GraphQL to the server engine (the
|
|
128
|
-
* Python sidecar lives server-side and cannot run in the browser). Returns `undefined` when no
|
|
129
|
-
* GraphQL provider is available, so the `ml` capability degrades cleanly.
|
|
130
|
-
*/
|
|
131
|
-
CreateSimpleMLTools() {
|
|
132
|
-
const provider = BaseEntity.Provider;
|
|
133
|
-
// Scoring requires a GraphQL provider to route the Remote Operation to the server engine.
|
|
134
|
-
if (!(provider instanceof GraphQLDataProvider)) {
|
|
135
|
-
return undefined;
|
|
136
|
-
}
|
|
137
|
-
const graphQLProvider = provider;
|
|
138
|
-
return {
|
|
139
|
-
listModels: (filter, contextUser) => this.listMLModels(filter, contextUser),
|
|
140
|
-
score: (modelId, records, options) => this.scoreMLRecords(graphQLProvider, modelId, records, options)
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
/**
|
|
144
|
-
* Loads the trained-model catalog from `MJ: ML Models`, newest version first, mapping each row
|
|
145
|
-
* to a {@link SimpleMLModelInfo}. Resilient — logs and returns `[]` on any failure.
|
|
146
|
-
*/
|
|
147
|
-
async listMLModels(filter, contextUser) {
|
|
148
|
-
try {
|
|
149
|
-
const rv = RunView.FromMetadataProvider(this.provider);
|
|
150
|
-
const result = await rv.RunView({
|
|
151
|
-
EntityName: 'MJ: ML Models',
|
|
152
|
-
ExtraFilter: this.buildMLModelsFilter(filter),
|
|
153
|
-
OrderBy: 'Version DESC',
|
|
154
|
-
MaxRows: filter?.maxResults,
|
|
155
|
-
ResultType: 'entity_object'
|
|
156
|
-
}, contextUser);
|
|
157
|
-
if (!result.Success) {
|
|
158
|
-
console.error(`❌ listModels failed for MJ: ML Models: ${result.ErrorMessage}`);
|
|
159
|
-
return [];
|
|
160
|
-
}
|
|
161
|
-
return result.Results.map((m) => this.mapMLModel(m));
|
|
162
|
-
}
|
|
163
|
-
catch (error) {
|
|
164
|
-
LogError(error);
|
|
165
|
-
return [];
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* Builds the ExtraFilter clause for {@link listMLModels}. Defaults to `Status='Published'` so
|
|
170
|
-
* components only see promoted models unless the caller overrides the status.
|
|
171
|
-
*/
|
|
172
|
-
buildMLModelsFilter(filter) {
|
|
173
|
-
const clauses = [];
|
|
174
|
-
const status = filter?.status ?? 'Published';
|
|
175
|
-
clauses.push(`Status='${this.escapeSqlLiteral(status)}'`);
|
|
176
|
-
if (filter?.targetVariable) {
|
|
177
|
-
clauses.push(`TargetVariable='${this.escapeSqlLiteral(filter.targetVariable)}'`);
|
|
178
|
-
}
|
|
179
|
-
return clauses.join(' AND ');
|
|
180
|
-
}
|
|
181
|
-
/** Maps a single `MJ: ML Models` row to the component-facing {@link SimpleMLModelInfo} shape. */
|
|
182
|
-
mapMLModel(m) {
|
|
183
|
-
return {
|
|
184
|
-
id: m.ID,
|
|
185
|
-
pipeline: m.Pipeline,
|
|
186
|
-
version: m.Version,
|
|
187
|
-
targetVariable: m.TargetVariable,
|
|
188
|
-
problemType: m.ProblemType,
|
|
189
|
-
status: m.Status,
|
|
190
|
-
metrics: this.parseMLMetrics(m.Metrics),
|
|
191
|
-
holdoutMetrics: this.parseMLMetrics(m.HoldoutMetrics)
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
/** Defensively parses a JSON metrics blob; returns `undefined` for null/empty/invalid JSON. */
|
|
195
|
-
parseMLMetrics(raw) {
|
|
196
|
-
if (!raw) {
|
|
197
|
-
return undefined;
|
|
198
|
-
}
|
|
199
|
-
try {
|
|
200
|
-
const parsed = JSON.parse(raw);
|
|
201
|
-
return parsed && typeof parsed === 'object' ? parsed : undefined;
|
|
202
|
-
}
|
|
203
|
-
catch {
|
|
204
|
-
return undefined;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* Scores records with a trained model by invoking the `PredictiveStudio.ScoreRecordSet` Remote
|
|
209
|
-
* Operation. Normalizes `records` to primary-key strings, requests ephemeral predictions (no
|
|
210
|
-
* write-back), and maps the result. Resilient — logs and returns a zeroed result with the input
|
|
211
|
-
* records counted as failed on any error.
|
|
212
|
-
*/
|
|
213
|
-
async scoreMLRecords(provider, modelId, records, options) {
|
|
214
|
-
const keys = this.normalizeRecordKeys(records, options?.primaryKeyField ?? 'ID');
|
|
215
|
-
try {
|
|
216
|
-
const input = {
|
|
217
|
-
modelId,
|
|
218
|
-
scope: { records: keys }
|
|
219
|
-
// No writeBack → predictions are returned ephemerally.
|
|
220
|
-
};
|
|
221
|
-
const op = new PredictiveStudioScoreRecordSetOperation();
|
|
222
|
-
const result = await op.Execute(input, { provider, user: options?.contextUser });
|
|
223
|
-
if (!result.Success || !result.Output) {
|
|
224
|
-
console.error(`❌ score failed for model ${modelId}: ${result.ErrorMessage}`);
|
|
225
|
-
return { scoredCount: 0, failedCount: keys.length, skippedCount: 0, predictions: [] };
|
|
226
|
-
}
|
|
227
|
-
const out = result.Output;
|
|
228
|
-
return {
|
|
229
|
-
scoredCount: out.scored,
|
|
230
|
-
failedCount: out.failed,
|
|
231
|
-
skippedCount: out.skipped,
|
|
232
|
-
predictions: (out.predictions ?? []).map((p) => ({
|
|
233
|
-
recordId: p.recordId,
|
|
234
|
-
score: p.score,
|
|
235
|
-
class: p.class
|
|
236
|
-
}))
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
catch (error) {
|
|
240
|
-
LogError(error);
|
|
241
|
-
return { scoredCount: 0, failedCount: keys.length, skippedCount: 0, predictions: [] };
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
/**
|
|
245
|
-
* Normalizes a mixed array of primary-key strings and row objects into an array of primary-key
|
|
246
|
-
* strings, reading `primaryKeyField` from objects. Drops entries without a resolvable key.
|
|
247
|
-
*/
|
|
248
|
-
normalizeRecordKeys(records, primaryKeyField) {
|
|
249
|
-
const keys = [];
|
|
250
|
-
for (const r of records) {
|
|
251
|
-
if (typeof r === 'string') {
|
|
252
|
-
keys.push(r);
|
|
253
|
-
}
|
|
254
|
-
else if (r != null) {
|
|
255
|
-
const value = r[primaryKeyField];
|
|
256
|
-
if (value != null) {
|
|
257
|
-
keys.push(String(value));
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
return keys;
|
|
262
|
-
}
|
|
263
|
-
/** Escapes single quotes for safe inlining into a RunView ExtraFilter SQL string literal. */
|
|
264
|
-
escapeSqlLiteral(value) {
|
|
265
|
-
return value.replace(/'/g, "''");
|
|
266
|
-
}
|
|
267
|
-
CreateSimpleMetadata(md) {
|
|
268
|
-
return {
|
|
269
|
-
Entities: md.Entities,
|
|
270
|
-
GetEntityObject: (entityName) => {
|
|
271
|
-
return md.GetEntityObject(entityName);
|
|
272
|
-
}
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
CreateSimpleGeoDataEngine() {
|
|
276
|
-
try {
|
|
277
|
-
const geo = GeoDataEngine.Instance;
|
|
278
|
-
if (!geo)
|
|
279
|
-
return undefined;
|
|
280
|
-
return {
|
|
281
|
-
ResolvePointToLocation: (lat, lng) => {
|
|
282
|
-
return geo.ResolvePointToLocation(lat, lng);
|
|
283
|
-
},
|
|
284
|
-
// GeoDataEngine is on-demand load — callers must await before ResolvePointToLocation works.
|
|
285
|
-
EnsureLoaded: () => geo.EnsureLoaded(),
|
|
286
|
-
get Loaded() {
|
|
287
|
-
return geo.Loaded;
|
|
288
|
-
}
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
catch {
|
|
292
|
-
// GeoDataEngine may not be configured yet — return undefined
|
|
293
|
-
return undefined;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
CreateSimpleRunQuery(rq) {
|
|
297
|
-
return {
|
|
298
|
-
RunQuery: async (params) => {
|
|
299
|
-
// Run a single query and return the results
|
|
300
|
-
try {
|
|
301
|
-
const result = await rq.RunQuery(params);
|
|
302
|
-
if (result.Success) {
|
|
303
|
-
console.log(`✅ RunQuery "${params.QueryName}" succeeded: ${result.RowCount} rows returned`);
|
|
304
|
-
if (this.debug) {
|
|
305
|
-
console.log(' > params', params);
|
|
306
|
-
console.log(' > result:', result);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
else {
|
|
310
|
-
console.error(`❌ RunQuery failed: ${result.ErrorMessage}`);
|
|
311
|
-
}
|
|
312
|
-
return result;
|
|
313
|
-
}
|
|
314
|
-
catch (error) {
|
|
315
|
-
console.error(`❌ RunQuery threw exception:`, error);
|
|
316
|
-
LogError(error);
|
|
317
|
-
throw error; // Re-throw to handle it in the caller
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
CreateSimpleRunView(rv) {
|
|
323
|
-
return {
|
|
324
|
-
RunView: async (params) => {
|
|
325
|
-
// Run a single view and return the results
|
|
326
|
-
try {
|
|
327
|
-
const result = await rv.RunView(params);
|
|
328
|
-
if (result.Success) {
|
|
329
|
-
console.log(`✅ RunView succeeded for ${params.EntityName}: ${result.TotalRowCount} rows returned`);
|
|
330
|
-
if (this.debug) {
|
|
331
|
-
console.log(' > params', params);
|
|
332
|
-
console.log(' > result:', result);
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
else {
|
|
336
|
-
console.error(`❌ RunView failed for ${params.EntityName}: ${result.ErrorMessage}`);
|
|
337
|
-
}
|
|
338
|
-
return result;
|
|
339
|
-
}
|
|
340
|
-
catch (error) {
|
|
341
|
-
console.error(`❌ RunView threw exception:`, error);
|
|
342
|
-
LogError(error);
|
|
343
|
-
throw error; // Re-throw to handle it in the caller
|
|
344
|
-
}
|
|
345
|
-
},
|
|
346
|
-
RunViews: async (params) => {
|
|
347
|
-
// Runs multiple views and returns the results
|
|
348
|
-
try {
|
|
349
|
-
const results = await rv.RunViews(params);
|
|
350
|
-
const entityNames = params.map(p => p.EntityName).join(', ');
|
|
351
|
-
const totalRows = results.reduce((sum, r) => sum + (r.TotalRowCount || 0), 0);
|
|
352
|
-
console.log(`✅ RunViews succeeded for [${entityNames}]: ${totalRows} total rows returned`);
|
|
353
|
-
if (this.debug) {
|
|
354
|
-
console.log(' > params', params);
|
|
355
|
-
console.log(' > results:', results);
|
|
356
|
-
}
|
|
357
|
-
return results;
|
|
358
|
-
}
|
|
359
|
-
catch (error) {
|
|
360
|
-
console.error(`❌ RunViews threw exception:`, error);
|
|
361
|
-
LogError(error);
|
|
362
|
-
throw error; // Re-throw to handle it in the caller
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
};
|
|
368
|
-
RuntimeUtilities = __decorate([
|
|
369
|
-
RegisterClass(RuntimeUtilities, 'RuntimeUtilities')
|
|
370
|
-
], RuntimeUtilities);
|
|
371
|
-
export { RuntimeUtilities };
|
|
372
|
-
/**
|
|
373
|
-
* Factory function to create RuntimeUtilities
|
|
374
|
-
* In a Node.js environment, this will use MJ's ClassFactory for runtime substitution
|
|
375
|
-
* In a browser environment, it will use the base class directly
|
|
376
|
-
*/
|
|
377
|
-
export function createRuntimeUtilities() {
|
|
378
|
-
// Check if we're in a Node.js environment with MJGlobal available
|
|
379
|
-
if (typeof window === 'undefined') {
|
|
380
|
-
try {
|
|
381
|
-
// Use ClassFactory to get the registered class, defaulting to base RuntimeUtilities
|
|
382
|
-
const obj = MJGlobal.Instance.ClassFactory.CreateInstance(RuntimeUtilities);
|
|
383
|
-
if (!obj) {
|
|
384
|
-
throw new Error('Failed to create RuntimeUtilities instance');
|
|
385
|
-
}
|
|
386
|
-
// Ensure the object is an instance of RuntimeUtilities
|
|
387
|
-
return obj;
|
|
388
|
-
}
|
|
389
|
-
catch (e) {
|
|
390
|
-
// Fall through to default
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
// Default: just use the base class
|
|
394
|
-
return new RuntimeUtilities();
|
|
395
|
-
}
|
|
396
|
-
//# sourceMappingURL=runtime-utilities.js.map
|