@memberjunction/ng-react 5.50.0 → 6.1.0-edge.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/LICENSE +7 -0
- package/dist/__tests__/runtime-utilities-ml.test.js +6 -4
- package/dist/__tests__/runtime-utilities-ml.test.js.map +1 -1
- package/dist/lib/components/mj-react-component.component.d.ts +10 -0
- package/dist/lib/components/mj-react-component.component.js +43 -8
- package/dist/lib/components/mj-react-component.component.js.map +1 -1
- package/dist/lib/services/angular-adapter.service.js +3 -0
- package/dist/lib/services/angular-adapter.service.js.map +1 -1
- package/dist/lib/services/react-bridge.service.js +7 -0
- package/dist/lib/services/react-bridge.service.js.map +1 -1
- package/dist/lib/utilities/runtime-utilities.d.ts +12 -1
- package/dist/lib/utilities/runtime-utilities.js +10 -6
- package/dist/lib/utilities/runtime-utilities.js.map +1 -1
- package/package.json +19 -17
package/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 MemberJunction
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
@@ -27,18 +27,20 @@ vi.mock('@memberjunction/core', async (importOriginal) => {
|
|
|
27
27
|
...actual,
|
|
28
28
|
LogError: vi.fn(),
|
|
29
29
|
BaseEntity: { Provider: mockProviderInstance },
|
|
30
|
-
|
|
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 {
|
|
31
33
|
constructor() {
|
|
32
34
|
this.Entities = [];
|
|
33
35
|
this.GetEntityObject = vi.fn();
|
|
34
36
|
}
|
|
35
|
-
},
|
|
36
|
-
RunView: class {
|
|
37
|
+
}, { Provider: mockProviderInstance }),
|
|
38
|
+
RunView: Object.assign(class {
|
|
37
39
|
constructor() {
|
|
38
40
|
this.RunView = mockRunView;
|
|
39
41
|
this.RunViews = vi.fn();
|
|
40
42
|
}
|
|
41
|
-
},
|
|
43
|
+
}, { FromMetadataProvider: () => ({ RunView: mockRunView, RunViews: vi.fn() }) }),
|
|
42
44
|
RunQuery: class {
|
|
43
45
|
constructor() {
|
|
44
46
|
this.RunQuery = vi.fn();
|
|
@@ -1 +1 @@
|
|
|
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,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C;QAEjF,MAAM,CAAC,GAAG,IAAI,gBAAgB,EAAE,CAAC,cAAc,EAAE,CAAC;QAClD,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,EAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;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 Metadata: class {\n Entities = [];\n GetEntityObject = vi.fn();\n },\n RunView: class {\n RunView = mockRunView;\n 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
|
+
{"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,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5B,CAAC;SAAA,EACD,EAAE,QAAQ,EAAE,oBAAoB,EAAE,CACnC;QACD,OAAO,EAAE,MAAM,CAAC,MAAM,CACpB;YAAA;gBACE,YAAO,GAAG,WAAW,CAAC;gBACtB,aAAQ,GAAG,EAAE,CA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,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"]}
|
|
@@ -67,6 +67,16 @@ export declare class MJReactComponent extends BaseAngularComponent implements Af
|
|
|
67
67
|
private themeObserver?;
|
|
68
68
|
set styles(value: Partial<ComponentStyles> | undefined);
|
|
69
69
|
get styles(): Partial<ComponentStyles>;
|
|
70
|
+
/**
|
|
71
|
+
* Explicitly user-requested styling from the spec being rendered, resolved above
|
|
72
|
+
* the theme. Reads the resolved spec when available (registry components resolve
|
|
73
|
+
* asynchronously) and falls back to the spec passed in.
|
|
74
|
+
*/
|
|
75
|
+
private get styleOverrides();
|
|
76
|
+
private _mergedStylesBase?;
|
|
77
|
+
private _mergedStylesOverrides?;
|
|
78
|
+
private _mergedStylesResult?;
|
|
79
|
+
private applyStyleOverridesMemoized;
|
|
70
80
|
/**
|
|
71
81
|
* Identifies the current theme so bridged styles can be memoized and refreshed
|
|
72
82
|
* when the user's mode (`data-theme`) or the org overlay (`data-theme-overlay`)
|
|
@@ -9,7 +9,7 @@ import { BaseAngularComponent } from '@memberjunction/ng-base-types';
|
|
|
9
9
|
import { ComponentSpec } from '@memberjunction/interactive-component-types';
|
|
10
10
|
import { ReactBridgeService } from '../services/react-bridge.service';
|
|
11
11
|
import { AngularAdapterService } from '../services/angular-adapter.service';
|
|
12
|
-
import { createErrorBoundary, ComponentHierarchyRegistrar, resourceManager, reactRootManager, BuildStylesFromTheme, wrapWithLibraryThemeProviders, ComponentRegistryService, resolveUserStateScope, userStateStorageKey, parseStoredUserSettings, mergeUserSettings, applyUserSettingsUpdate } from '@memberjunction/react-runtime';
|
|
12
|
+
import { createErrorBoundary, ComponentHierarchyRegistrar, resourceManager, reactRootManager, BuildStylesFromTheme, ApplyStyleOverrides, wrapWithLibraryThemeProviders, ComponentRegistryService, resolveUserStateScope, userStateStorageKey, parseStoredUserSettings, mergeUserSettings, applyUserSettingsUpdate } from '@memberjunction/react-runtime';
|
|
13
13
|
import { createRuntimeUtilities } from '../utilities/runtime-utilities';
|
|
14
14
|
import { LogError, CompositeKey, RunView, DataSnapshot, DataTable, MJColumnDescriptor } from '@memberjunction/core';
|
|
15
15
|
import { MJNotificationService } from '@memberjunction/ng-notifications';
|
|
@@ -51,6 +51,15 @@ export class MJReactComponent extends BaseAngularComponent {
|
|
|
51
51
|
if (isDifferent) {
|
|
52
52
|
this.reinitializeComponent();
|
|
53
53
|
}
|
|
54
|
+
else if (JSON.stringify(previousComponent.styleOverrides) !== JSON.stringify(value.styleOverrides)) {
|
|
55
|
+
// Same code, new styleOverrides (a regenerated spec whose only change is the
|
|
56
|
+
// requested styling): re-render in place — no teardown needed. The resolved
|
|
57
|
+
// spec must be kept in step because the styleOverrides getter prefers it.
|
|
58
|
+
if (this.resolvedComponentSpec) {
|
|
59
|
+
this.resolvedComponentSpec.styleOverrides = value.styleOverrides;
|
|
60
|
+
}
|
|
61
|
+
this.renderComponent();
|
|
62
|
+
}
|
|
54
63
|
}
|
|
55
64
|
}
|
|
56
65
|
get component() {
|
|
@@ -63,7 +72,7 @@ export class MJReactComponent extends BaseAngularComponent {
|
|
|
63
72
|
// Lazy initialization - only create default utilities when needed
|
|
64
73
|
if (!this._utilities) {
|
|
65
74
|
const runtimeUtils = createRuntimeUtilities();
|
|
66
|
-
this._utilities = runtimeUtils.buildUtilities(this.enableLogging);
|
|
75
|
+
this._utilities = runtimeUtils.buildUtilities(this.enableLogging, this.ProviderToUse);
|
|
67
76
|
if (this.enableLogging) {
|
|
68
77
|
console.log('MJReactComponent: Auto-initialized utilities using createRuntimeUtilities()');
|
|
69
78
|
}
|
|
@@ -74,9 +83,10 @@ export class MJReactComponent extends BaseAngularComponent {
|
|
|
74
83
|
this._styles = value;
|
|
75
84
|
}
|
|
76
85
|
get styles() {
|
|
77
|
-
// An explicitly-provided styles input always wins
|
|
86
|
+
// An explicitly-provided styles input always wins — but user-requested overrides
|
|
87
|
+
// still layer on top, since they represent an explicit request rather than a theme.
|
|
78
88
|
if (this._styles) {
|
|
79
|
-
return this._styles;
|
|
89
|
+
return this.applyStyleOverridesMemoized(this._styles);
|
|
80
90
|
}
|
|
81
91
|
// Otherwise bridge the host's live MJ theme (--mj-* tokens) into ComponentStyles
|
|
82
92
|
// so generated components inherit the active theme — including dark mode and
|
|
@@ -90,7 +100,29 @@ export class MJReactComponent extends BaseAngularComponent {
|
|
|
90
100
|
console.log(`MJReactComponent: Bridged styles from live theme (key="${key}")`);
|
|
91
101
|
}
|
|
92
102
|
}
|
|
93
|
-
|
|
103
|
+
// Applied outside the theme memo so the spec's overrides survive a theme flip
|
|
104
|
+
// (the memo caches the theme, not the request).
|
|
105
|
+
return this.applyStyleOverridesMemoized(this._themeStyles);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Explicitly user-requested styling from the spec being rendered, resolved above
|
|
109
|
+
* the theme. Reads the resolved spec when available (registry components resolve
|
|
110
|
+
* asynchronously) and falls back to the spec passed in.
|
|
111
|
+
*/
|
|
112
|
+
get styleOverrides() {
|
|
113
|
+
return this.resolvedComponentSpec?.styleOverrides ?? this._component?.styleOverrides;
|
|
114
|
+
}
|
|
115
|
+
applyStyleOverridesMemoized(base) {
|
|
116
|
+
const overrides = this.styleOverrides;
|
|
117
|
+
if (!overrides) {
|
|
118
|
+
return base;
|
|
119
|
+
}
|
|
120
|
+
if (!this._mergedStylesResult || this._mergedStylesBase !== base || this._mergedStylesOverrides !== overrides) {
|
|
121
|
+
this._mergedStylesBase = base;
|
|
122
|
+
this._mergedStylesOverrides = overrides;
|
|
123
|
+
this._mergedStylesResult = ApplyStyleOverrides(base, overrides);
|
|
124
|
+
}
|
|
125
|
+
return this._mergedStylesResult;
|
|
94
126
|
}
|
|
95
127
|
/**
|
|
96
128
|
* Identifies the current theme so bridged styles can be memoized and refreshed
|
|
@@ -1067,8 +1099,11 @@ export class MJReactComponent extends BaseAngularComponent {
|
|
|
1067
1099
|
this.compiledComponent = null;
|
|
1068
1100
|
this.isInitialized = false;
|
|
1069
1101
|
this.capturedData = [];
|
|
1070
|
-
// Trigger registry cleanup
|
|
1071
|
-
|
|
1102
|
+
// Trigger registry cleanup (guard: adapter may not be initialized if
|
|
1103
|
+
// React bootstrap failed or was destroyed during retry)
|
|
1104
|
+
if (this.adapter.isInitialized()) {
|
|
1105
|
+
this.adapter.getRegistry().cleanup();
|
|
1106
|
+
}
|
|
1072
1107
|
}
|
|
1073
1108
|
/**
|
|
1074
1109
|
* Public method to refresh the component
|
|
@@ -1268,5 +1303,5 @@ export class MJReactComponent extends BaseAngularComponent {
|
|
|
1268
1303
|
type: ViewChild,
|
|
1269
1304
|
args: ['container', { read: ElementRef, static: true }]
|
|
1270
1305
|
}] }); })();
|
|
1271
|
-
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(MJReactComponent, { className: "MJReactComponent", filePath: "lib/components/mj-react-component.component.ts", lineNumber:
|
|
1306
|
+
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(MJReactComponent, { className: "MJReactComponent", filePath: "lib/components/mj-react-component.component.ts", lineNumber: 159 }); })();
|
|
1272
1307
|
//# sourceMappingURL=mj-react-component.component.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mj-react-component.component.js","sourceRoot":"","sources":["../../../src/lib/components/mj-react-component.component.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,SAAS,EACT,KAAK,EACL,MAAM,EACN,YAAY,EACZ,SAAS,EACT,UAAU,EAGV,uBAAuB,EACvB,iBAAiB,EAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,aAAa,EAAuE,MAAM,6CAA6C,CAAC;AACjJ,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EACL,mBAAmB,EACnB,2BAA2B,EAC3B,eAAe,EACf,gBAAgB,EAGhB,oBAAoB,EACpB,6BAA6B,EAC7B,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,EACvB,iBAAiB,EACjB,uBAAuB,EACxB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAs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BAaL,KAAK;;kBAWL,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBAEN,MAAM;;kBAEN,SAAS;mBAAC,WAAW,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE;;kFA7L/C,gBAAgB","sourcesContent":["/**\n * @fileoverview Angular component that hosts React components with proper memory management.\n * Provides a bridge between Angular and React ecosystems in MemberJunction applications.\n * @module @memberjunction/ng-react\n */\n\nimport {\n Component,\n Input,\n Output,\n EventEmitter,\n ViewChild,\n ElementRef,\n AfterViewInit,\n OnDestroy,\n ChangeDetectionStrategy,\n ChangeDetectorRef\n} from '@angular/core';\nimport { Subject } from 'rxjs';\nimport { BaseAngularComponent } from '@memberjunction/ng-base-types';\nimport { ComponentSpec, ComponentCallbacks, ComponentStyles, ComponentObject, BaseEventArgs } from '@memberjunction/interactive-component-types';\nimport { ReactBridgeService } from '../services/react-bridge.service';\nimport { AngularAdapterService } from '../services/angular-adapter.service';\nimport {\n createErrorBoundary,\n ComponentHierarchyRegistrar,\n resourceManager,\n reactRootManager,\n ResolvedComponents,\n SetupStyles,\n BuildStylesFromTheme,\n wrapWithLibraryThemeProviders,\n ComponentRegistryService,\n resolveUserStateScope,\n userStateStorageKey,\n parseStoredUserSettings,\n mergeUserSettings,\n applyUserSettingsUpdate\n} from '@memberjunction/react-runtime';\nimport { createRuntimeUtilities } from '../utilities/runtime-utilities';\nimport { LogError, CompositeKey, KeyValuePair, Metadata, RunView, RunViewParams, RunViewResult, RunQueryParams, RunQueryResult, DataSnapshot, DataTable, MJColumnDescriptor } from '@memberjunction/core';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { ComponentMetadataEngine, UserInfoEngine } from '@memberjunction/core-entities';\nimport { ComponentUtilities, SimpleRunView, SimpleRunQuery } from '@memberjunction/interactive-component-types';\n\n/**\n * A captured RunView/RunQuery result with its original parameters.\n * Used by the automatic data capture system for components that don't\n * implement getCurrentDataState().\n */\ninterface CapturedDataResult {\n /** Entity name or query name */\n sourceName: string;\n /** 'view' or 'query' */\n sourceType: 'view' | 'query';\n /** Original RunView/RunQuery params */\n params: Record<string, unknown>;\n /** Returned rows */\n rows: Record<string, unknown>[];\n /** Total available rows (may differ from rows.length due to pagination) */\n totalRows: number;\n /** When the data was fetched */\n fetchedAt: Date;\n}\n\n/**\n * Event emitted by React components\n */\nexport interface ReactComponentEvent {\n type: string;\n payload: any;\n}\n\n/**\n * State change event emitted when component state updates\n */\nexport interface StateChangeEvent {\n path: string;\n value: any;\n}\n\n/**\n * User settings changed event emitted when component saves user preferences\n */\nexport interface UserSettingsChangedEvent {\n settings: Record<string, any>;\n componentName?: string;\n timestamp: Date;\n}\n\n/**\n * Angular component that hosts React components with proper memory management.\n * This component provides a bridge between Angular and React, allowing React components\n * to be used seamlessly within Angular applications.\n */\n@Component({\n standalone: false,\n selector: 'mj-react-component',\n template: `\n <div class=\"react-component-wrapper\">\n <div #container class=\"react-component-container\" [class.loading]=\"!isInitialized\"></div>\n @if (!isInitialized && !hasError) {\n <div class=\"loading-overlay\">\n <div class=\"loading-spinner\">\n <i class=\"fa-solid fa-spinner fa-spin\"></i>\n </div>\n <div class=\"loading-text\">Loading component...</div>\n </div>\n }\n </div>\n `,\n styles: [`\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n .react-component-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n }\n .react-component-container {\n width: 100%;\n height: 100%;\n transition: opacity 0.3s ease;\n }\n .react-component-container.loading {\n opacity: 0;\n }\n .loading-overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 1;\n }\n .loading-spinner {\n font-size: 48px;\n color: #5B4FE9;\n margin-bottom: 16px;\n }\n .loading-text {\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n font-size: 14px;\n color: #64748B;\n margin-top: 8px;\n }\n `],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class MJReactComponent extends BaseAngularComponent implements AfterViewInit, OnDestroy {\n private _component!: ComponentSpec;\n\n /**\n * The component specification to render.\n * When this changes after initialization, the component will be reinitialized\n * to load and render the new specification.\n */\n @Input()\n set component(value: ComponentSpec) {\n const previousComponent = this._component;\n this._component = value;\n\n // If already initialized and component spec changed, reinitialize\n if (this.isInitialized && value && previousComponent !== value) {\n // Check if it's actually a different component (not just same reference)\n const isDifferent = !previousComponent ||\n previousComponent.name !== value.name ||\n previousComponent.code !== value.code ||\n previousComponent.version !== value.version;\n\n if (isDifferent) {\n this.reinitializeComponent();\n }\n }\n }\n get component(): ComponentSpec {\n return this._component;\n }\n\n /**\n * Controls verbose logging for component lifecycle and operations.\n * Note: This does NOT control which React build (dev/prod) is loaded.\n * To control React builds, use ReactDebugConfig.setDebugMode() at app startup.\n */\n @Input() enableLogging: boolean = false;\n @Input() useComponentManager: boolean = true; // NEW: Use unified ComponentManager by default\n \n // Auto-initialize utilities if not provided\n private _utilities: any;\n @Input()\n set utilities(value: any) {\n this._utilities = value;\n }\n get utilities(): any {\n // Lazy initialization - only create default utilities when needed\n if (!this._utilities) {\n const runtimeUtils = createRuntimeUtilities();\n this._utilities = runtimeUtils.buildUtilities(this.enableLogging);\n if (this.enableLogging) {\n console.log('MJReactComponent: Auto-initialized utilities using createRuntimeUtilities()');\n }\n }\n return this._utilities;\n }\n \n // Auto-initialize styles if not provided\n private _styles?: Partial<ComponentStyles>;\n // Theme-bridge cache: the ComponentStyles derived from the live `--mj-*` theme,\n // memoized per theme key so we don't re-read getComputedStyle on every access.\n private _themeStyles?: ComponentStyles;\n private _themeStylesKey?: string;\n private themeObserver?: MutationObserver;\n @Input()\n set styles(value: Partial<ComponentStyles> | undefined) {\n this._styles = value;\n }\n get styles(): Partial<ComponentStyles> {\n // An explicitly-provided styles input always wins.\n if (this._styles) {\n return this._styles;\n }\n // Otherwise bridge the host's live MJ theme (--mj-* tokens) into ComponentStyles\n // so generated components inherit the active theme — including dark mode and\n // hover/active/focus state families — instead of the frozen defaults. Memoized\n // per theme key; invalidated by the MutationObserver on data-theme changes.\n const key = this.computeThemeKey();\n if (!this._themeStyles || this._themeStylesKey !== key) {\n this._themeStyles = BuildStylesFromTheme();\n this._themeStylesKey = key;\n if (this.enableLogging) {\n console.log(`MJReactComponent: Bridged styles from live theme (key=\"${key}\")`);\n }\n }\n return this._themeStyles;\n }\n\n /**\n * Identifies the current theme so bridged styles can be memoized and refreshed\n * when the user's mode (`data-theme`) or the org overlay (`data-theme-overlay`)\n * changes. Non-DOM environments return a constant key.\n */\n private computeThemeKey(): string {\n if (typeof document === 'undefined') {\n return 'no-dom';\n }\n const root = document.documentElement;\n return `${root.getAttribute('data-theme') || 'light'}|${root.getAttribute('data-theme-overlay') || ''}`;\n }\n\n /**\n * Watches the document root for theme changes (`data-theme` / `data-theme-overlay`)\n * and, when the theme flips, invalidates the bridged-styles cache and re-renders so\n * the live React component picks up the new theme. No-op when styles are supplied\n * explicitly or when there is no DOM.\n */\n private setupThemeObserver(): void {\n if (this._styles || typeof MutationObserver === 'undefined' || typeof document === 'undefined') {\n return;\n }\n this.themeObserver = new MutationObserver(() => {\n const key = this.computeThemeKey();\n if (key !== this._themeStylesKey) {\n this._themeStyles = undefined;\n this._themeStylesKey = undefined;\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n });\n this.themeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['data-theme', 'data-theme-overlay'],\n });\n }\n \n private _savedUserSettings: any = {};\n @Input()\n set savedUserSettings(value: any) {\n this._savedUserSettings = value || {};\n // Re-render if component is initialized\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n get savedUserSettings(): any {\n return this._savedUserSettings;\n }\n\n /**\n * Optional explicit scope for per-user settings persistence. When omitted, the\n * scope defaults to `<namespace>/<name>` of the component spec. Settings are\n * stored per-user via `UserInfoEngine` under the key\n * `InteractiveComponents_UserState_Root/<scope>`. Provide an\n * explicit scope when a single component spec is rendered in multiple distinct\n * contexts that should NOT share preferences (e.g. the same form spec used for\n * different entities) — set it to something stable and unique per context.\n */\n @Input() UserStateScope?: string;\n\n /**\n * When `true` (default), the host transparently persists `savedUserSettings`\n * per-user, cross-device via `UserInfoEngine` — seeding the component from\n * storage on load and saving (debounced) on every `onSaveUserSettings` call,\n * auto-scoped per component. Set to `false` to opt out and own persistence\n * yourself by handling the `userSettingsChanged` output instead.\n */\n @Input() PersistUserSettings: boolean = true;\n\n /**\n * Host-supplied props spread into the React component's props alongside the\n * standard `utilities`, `callbacks`, `components`, `styles`, `libraries`, and\n * `savedUserSettings`. Used by hosts that need to push data context the React\n * component can't fetch itself — e.g. `InteractiveFormComponent` passing\n * `FormHostProps` (the current record snapshot, mode, permissions).\n *\n * Standard keys take precedence over caller-supplied keys to keep the\n * platform contract stable.\n */\n private _componentProps: object = {};\n @Input()\n set componentProps(value: object | undefined) {\n this._componentProps = value ?? {};\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n get componentProps(): object {\n return this._componentProps;\n }\n\n @Output() stateChange = new EventEmitter<StateChangeEvent>();\n @Output() componentEvent = new EventEmitter<ReactComponentEvent>();\n @Output() refreshData = new EventEmitter<void>();\n @Output() openEntityRecord = new EventEmitter<{ entityName: string; key: CompositeKey }>();\n @Output() userSettingsChanged = new EventEmitter<UserSettingsChangedEvent>();\n /** Emitted once after the component successfully loads and resolvedComponentSpec is populated. */\n @Output() initialized = new EventEmitter<void>();\n \n @ViewChild('container', { read: ElementRef, static: true }) container!: ElementRef<HTMLDivElement>;\n\n // ─── Automatic data capture ───\n // Stores RunView/RunQuery results for components that don't implement getCurrentDataState().\n // Cleared on component reinitialize. Used as fallback in GetCurrentDataState().\n private capturedData: CapturedDataResult[] = [];\n\n private reactRootId: string | null = null;\n private compiledComponent: ComponentObject | null = null;\n private loadedDependencies: Record<string, ComponentObject> = {};\n private destroyed$ = new Subject<void>();\n private currentCallbacks: ComponentCallbacks | null = null;\n isInitialized = false;\n private isRendering = false;\n private pendingRender = false;\n private isDestroying = false;\n private componentId: string;\n private componentVersion: string = ''; // Store the version for resolver\n hasError = false;\n \n /**\n * Public property containing the fully resolved component specification.\n * This includes all external code fetched from registries, allowing consumers\n * to inspect the complete resolved specification including dependencies.\n * Only populated after successful component initialization.\n */\n public resolvedComponentSpec: ComponentSpec | null = null;\n\n constructor(\n private reactBridge: ReactBridgeService,\n private adapter: AngularAdapterService,\n private cdr: ChangeDetectorRef,\n private notificationService: MJNotificationService\n ) {\n super();\n // Generate unique component ID for resource tracking\n this.componentId = `mj-react-component-${Date.now()}-${Math.random()}`;\n }\n\n async ngAfterViewInit() {\n // Try to get registry size safely\n let registrySize = 'N/A';\n try {\n if (this.adapter.isInitialized()) {\n registrySize = this.adapter.getRegistry().size().toString();\n } else {\n registrySize = 'Not initialized yet';\n }\n } catch (e) {\n registrySize = 'Not available';\n }\n \n console.log(`🎬 [ngAfterViewInit] Starting component initialization:`, {\n componentId: this.componentId,\n componentName: this.component?.name,\n timestamp: new Date().toISOString(),\n registrySize: registrySize\n });\n \n // Trigger change detection to show loading state\n this.cdr.detectChanges();\n // Refresh bridged theme styles when the user's mode / org overlay changes.\n this.setupThemeObserver();\n await this.initializeComponent();\n }\n\n ngOnDestroy() {\n // Set destroying flag immediately\n this.isDestroying = true;\n\n // Cancel any pending renders\n this.pendingRender = false;\n\n this.themeObserver?.disconnect();\n this.themeObserver = undefined;\n\n this.destroyed$.next();\n this.destroyed$.complete();\n this.cleanup();\n }\n\n /**\n * Reinitialize the component when the input spec changes.\n * Cleans up the current component and initializes with the new spec.\n */\n private async reinitializeComponent() {\n // Don't reinitialize if we're being destroyed\n if (this.isDestroying) {\n return;\n }\n\n // Clear cached state from previous component\n this.compiledComponent = null;\n this.resolvedComponentSpec = null;\n this.loadedDependencies = {};\n this.componentVersion = '';\n this.hasError = false;\n this.isInitialized = false;\n this.capturedData = [];\n\n // Unmount existing React root if present\n if (this.reactRootId) {\n this.isRendering = false;\n this.pendingRender = false;\n reactRootManager.unmountRoot(this.reactRootId);\n this.reactRootId = null;\n }\n\n // Trigger change detection to show loading state\n this.cdr.detectChanges();\n\n // Initialize with the new component spec\n await this.initializeComponent();\n }\n\n /**\n * Initialize the React component\n */\n private async initializeComponent() {\n try {\n // Ensure React is loaded\n await this.reactBridge.getReactContext();\n\n // Wait for React to be fully ready (handles first-load delay)\n await this.reactBridge.waitForReactReady();\n\n // NEW: Use ComponentManager if enabled (default: true)\n if (this.useComponentManager) {\n console.log(`🎯 [initializeComponent] Using NEW ComponentManager approach`);\n await this.loadComponentWithManager();\n \n // Component is already compiled and stored in this.compiledComponent\n // No need to fetch from registry - it's already set\n } else {\n console.log(`📦 [initializeComponent] Using legacy approach (will be deprecated)`);\n // Register component hierarchy (this compiles and registers all components including from registries)\n await this.registerComponentHierarchy();\n \n // The resolved spec should now be available from the registration result\n // No need to fetch again\n \n // Get the already-registered component from the registry\n const registry = this.adapter.getRegistry();\n \n console.log(`🔍 [initializeComponent] Looking for component in registry:`, {\n name: this.component.name,\n namespace: this.component.namespace || 'Global',\n version: this.componentVersion\n });\n \n // Let's also check what's actually in the registry\n // Note: ComponentRegistry doesn't have a list() method, so we'll skip this for now\n \n const componentWrapper = registry.get(\n this.component.name, \n this.component.namespace || 'Global', \n this.componentVersion\n );\n \n console.log(`🔍 [initializeComponent] Registry.get result:`, {\n found: !!componentWrapper,\n type: componentWrapper ? typeof componentWrapper : 'undefined',\n hasComponent: componentWrapper ? !!componentWrapper.component : false\n });\n \n if (!componentWrapper) {\n const source = this.component.registry ? `external registry ${this.component.registry}` : 'local registry';\n console.error(`❌ [initializeComponent] Component not found! Details:`, {\n searchedName: this.component.name,\n searchedNamespace: this.component.namespace || 'Global',\n searchedVersion: this.componentVersion,\n source: source\n });\n throw new Error(`Component ${this.component.name} was not found in registry after registration from ${source}`);\n }\n \n // The registry now stores ComponentObjects directly\n // Validate it has the expected structure\n if (!componentWrapper || typeof componentWrapper !== 'object') {\n throw new Error(`Invalid component wrapper returned for ${this.component.name}: ${typeof componentWrapper}`);\n }\n \n if (!componentWrapper.component) {\n throw new Error(`Component wrapper missing 'component' property for ${this.component.name}`);\n }\n \n // Now that we use a regular HOC wrapper, components should always be functions\n if (typeof componentWrapper.component !== 'function') {\n throw new Error(`Component is not a function for ${this.component.name}: ${typeof componentWrapper.component}`);\n }\n \n this.compiledComponent = componentWrapper;\n } // End of else block for legacy approach\n \n // Create managed React root\n const reactContext = this.reactBridge.getCurrentContext();\n if (!reactContext) {\n throw new Error('React context not available');\n }\n \n this.reactRootId = reactRootManager.createRoot(\n this.container.nativeElement,\n (container: HTMLElement) => reactContext.ReactDOM.createRoot(container),\n this.componentId\n );\n\n // Seed savedUserSettings from durable per-user storage before the first\n // render so the component mounts with the user's persisted preferences.\n await this.seedUserSettingsFromStore();\n\n // Initial render\n this.renderComponent();\n this.isInitialized = true;\n\n // Trigger change detection since we're using OnPush\n this.cdr.detectChanges();\n\n // Notify parent that the component has successfully initialized and\n // resolvedComponentSpec is now populated with the full spec from the registry\n this.initialized.emit();\n\n } catch (error) {\n this.hasError = true;\n LogError(`Failed to initialize React component: ${error}`);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error instanceof Error ? error.message : String(error),\n source: 'initialization'\n }\n });\n // Trigger change detection to show error state\n this.cdr.detectChanges();\n }\n }\n \n\n /**\n * Generate a hash from component code for versioning\n * Uses a simple hash function that's fast and sufficient for version differentiation\n */\n private generateComponentHash(spec: ComponentSpec): string {\n // Collect all code from the component hierarchy\n const codeStrings: string[] = [];\n \n const collectCode = (s: ComponentSpec) => {\n if (s.code) {\n codeStrings.push(s.code);\n }\n if (s.dependencies) {\n for (const dep of s.dependencies) {\n collectCode(dep);\n }\n }\n };\n \n collectCode(spec);\n \n // Generate hash from concatenated code\n const fullCode = codeStrings.join('|');\n let hash = 0;\n for (let i = 0; i < fullCode.length; i++) {\n const char = fullCode.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n \n // Convert to hex string and take first 8 characters for readability\n const hexHash = Math.abs(hash).toString(16).padStart(8, '0').substring(0, 8);\n return `v${hexHash}`;\n }\n\n /**\n * Resolve components using the runtime's resolver\n */\n private async resolveComponentsWithVersion(spec: ComponentSpec, version: string, namespace: string = 'Global'): Promise<ResolvedComponents> {\n const resolver = this.adapter.getResolver();\n \n // Debug: Log what dependencies we're trying to resolve\n if (this.enableLogging) {\n console.log(`Resolving components for ${spec.name}. Dependencies:`, spec.dependencies);\n }\n \n // Use the runtime's resolver which now handles registry-based components\n const resolved = await resolver.resolveComponents(\n spec, \n namespace,\n this.ProviderToUse.CurrentUser // Pass current user context for database operations\n );\n \n if (this.enableLogging) {\n console.log(`Resolved ${Object.keys(resolved).length} components for version ${version}:`, Object.keys(resolved));\n }\n return resolved;\n }\n\n\n /**\n * NEW: Load component using unified ComponentManager - MUCH SIMPLER!\n */\n private async loadComponentWithManager() {\n try {\n const manager = this.adapter.getComponentManager();\n \n console.log(`🚀 [ComponentManager] Loading component hierarchy: ${this.component.name}`);\n \n // Load the entire hierarchy with one simple call\n const result = await manager.loadHierarchy(this.component, {\n contextUser: this.ProviderToUse.CurrentUser,\n defaultNamespace: 'Global',\n defaultVersion: this.component.version || this.generateComponentHash(this.component),\n returnType: 'both'\n });\n \n if (!result.success) {\n const errorMessages = result.errors.map(e => `${e.componentName}: ${e.message}`).join(', ');\n console.error(`❌ [ComponentManager] Failed to load hierarchy:`, errorMessages);\n throw new Error(`Component loading failed: ${errorMessages}`);\n }\n \n // Store the results (handle undefined values)\n this.resolvedComponentSpec = this.enrichSpecWithRegistryInfo(result.resolvedSpec || null);\n this.compiledComponent = result.rootComponent || null;\n this.componentVersion = result.resolvedSpec?.version || this.component.version || 'latest';\n \n // IMPORTANT: Store the loaded dependencies for use in renderComponent\n this.loadedDependencies = result.components || {};\n \n console.log(`✅ [ComponentManager] Successfully loaded hierarchy:`, {\n rootComponent: result.resolvedSpec?.name,\n loadedCount: result.loadedComponents.length,\n dependencies: Object.keys(this.loadedDependencies),\n stats: result.stats\n });\n \n // Component is ready to render\n return true;\n \n } catch (error) {\n console.error(`❌ [ComponentManager] Error loading component:`, error);\n throw error;\n }\n }\n\n /**\n * Register all components in the hierarchy\n * @deprecated Use loadComponentWithManager() instead\n */\n private async registerComponentHierarchy() {\n // Use semantic version from spec or generate hash-based version for uniqueness\n const version = this.component.version || this.generateComponentHash(this.component);\n this.componentVersion = version; // Store for use in resolver\n \n console.log(`🔍 [registerComponentHierarchy] Starting registration for ${this.component.name}@${version}`, {\n location: this.component.location,\n registry: this.component.registry,\n namespace: this.component.namespace,\n hasCode: !!this.component.code,\n codeLength: this.component.code?.length || 0\n });\n \n // Check if already registered to avoid duplication\n const registry = this.adapter.getRegistry();\n const checkNamespace = this.component.namespace || 'Global';\n \n console.log(`🔍 [registerComponentHierarchy] Checking registry for existing component:`, {\n name: this.component.name,\n namespace: checkNamespace,\n version: version,\n registrySize: registry.size(),\n registryId: registry.registryId || 'unknown'\n });\n \n // Log registry state for debugging\n console.log(`📦 [registerComponentHierarchy] Registry state:`, {\n totalSize: registry.size(),\n registryInstance: registry.registryId || 'unknown'\n });\n \n const existingComponent = registry.get(this.component.name, checkNamespace, version);\n \n if (existingComponent) {\n console.log(`⚠️ [registerComponentHierarchy] Component ${this.component.name}@${version} already registered!`, {\n existingType: typeof existingComponent,\n hasComponent: !!(existingComponent as any).component,\n registrationTime: (existingComponent as any).registeredAt || 'unknown',\n runtimeContextLibraries: Object.keys(this.adapter.getRuntimeContext().libraries || {})\n });\n \n // For registry components, we need to check the resolved spec's libraries, not the input spec\n // The input spec from Angular doesn't have library information for registry components\n if (this.component.location === 'registry' && this.component.registry) {\n console.log(`📋 [registerComponentHierarchy] Component is from registry, need to fetch full spec to check libraries`);\n // Continue to fetch the full spec below - don't return early\n } else {\n // For local components, check using the input spec\n const requiredLibraries = this.component.libraries || [];\n const runtimeLibraries = this.adapter.getRuntimeContext().libraries || {};\n const missingLibraries = requiredLibraries.filter(lib => !runtimeLibraries[lib.globalVariable]);\n \n if (missingLibraries.length > 0) {\n console.warn(`⚠️ [registerComponentHierarchy] Component registered but libraries missing:`, {\n required: requiredLibraries.map(l => l.globalVariable),\n loaded: Object.keys(runtimeLibraries),\n missing: missingLibraries.map(l => l.globalVariable)\n });\n // Don't return early - continue to load libraries\n } else {\n console.log(`✅ [registerComponentHierarchy] Component ${this.component.name}@${version} already registered with all libraries, skipping`);\n return;\n }\n }\n } else {\n console.log(`🆕 [registerComponentHierarchy] Component not found in registry, proceeding with registration`);\n }\n \n // Initialize metadata engine\n await ComponentMetadataEngine.Instance.Config(false, this.ProviderToUse.CurrentUser);\n \n // Use the runtime's hierarchy registrar\n const registrar = new ComponentHierarchyRegistrar(\n this.adapter.getCompiler(),\n this.adapter.getRegistry(),\n this.adapter.getRuntimeContext()\n );\n \n console.log(`📦 [registerComponentHierarchy] Calling registrar.registerHierarchy for ${this.component.name}`, {\n hasStyles: !!this.styles,\n namespace: this.component.namespace || 'Global',\n version: version,\n libraryCount: ComponentMetadataEngine.Instance.ComponentLibraries?.length || 0,\n hasCode: !!this.component.code,\n codeLength: this.component.code?.length || 0\n });\n \n // Register with proper configuration\n // Pass the partial spec - the React runtime will handle fetching from registries\n const result = await registrar.registerHierarchy(\n this.component, // Pass the original spec, not fetched\n {\n styles: this.styles as ComponentStyles,\n namespace: this.component.namespace || 'Global',\n version: version,\n allowOverride: false, // Each version is unique\n allLibraries: ComponentMetadataEngine.Instance.ComponentLibraries,\n debug: true,\n contextUser: this.ProviderToUse.CurrentUser\n }\n );\n \n if (!result.success) {\n const errors = result.errors.map(e => e.error).join(', ');\n console.error(`❌ [registerComponentHierarchy] Registration failed:`, errors);\n throw new Error(`Component registration failed: ${errors}`);\n }\n \n // Store the resolved spec from the registration result\n if (result.resolvedSpec) {\n this.resolvedComponentSpec = this.enrichSpecWithRegistryInfo(result.resolvedSpec || null);\n console.log(`📋 [registerComponentHierarchy] Received resolved spec from runtime:`, {\n name: result.resolvedSpec.name,\n hasCode: !!result.resolvedSpec.code,\n libraryCount: result.resolvedSpec.libraries?.length || 0,\n dependencyCount: result.resolvedSpec.dependencies?.length || 0\n });\n }\n \n console.log(`✅ [registerComponentHierarchy] Successfully registered ${result.registeredComponents.length} components:`, result.registeredComponents);\n \n // Verify the component is actually in the registry\n const verifyComponent = registry.get(this.component.name, this.component.namespace || 'Global', version);\n console.log(`🔍 [registerComponentHierarchy] Verification - component in registry after registration:`, {\n found: !!verifyComponent,\n name: this.component.name,\n namespace: this.component.namespace || 'Global',\n version: version,\n componentType: verifyComponent ? typeof verifyComponent : 'not found'\n });\n }\n\n /**\n * Post-process resolved spec to ensure all components show their true registry source.\n * This enriches the spec for UI display purposes to show where components actually came from.\n * Applied to all resolved specs so any consumer of this wrapper benefits.\n */\n private enrichSpecWithRegistryInfo(spec: ComponentSpec | null): ComponentSpec | null {\n if (!spec || !this.component) return spec;\n \n // Create a deep copy to avoid mutating the original\n const enrichedSpec = JSON.parse(JSON.stringify(spec));\n \n // Recursive function to process spec and all dependencies\n // Takes the original spec at the same level to find registry info\n const processSpec = (currentSpec: ComponentSpec, originalSpec: ComponentSpec) => {\n // If this component has code but shows location as 'embedded', \n // check the original spec to see where it came from\n if (currentSpec.code && currentSpec.location === 'embedded' && currentSpec.name) {\n // Try to find this component in the original spec at the same level\n // First check if the original spec itself matches by name\n if (originalSpec.name === currentSpec.name) {\n // Use the original's registry info if it had any\n if (originalSpec.location === 'registry' || originalSpec.registry) {\n currentSpec.location = 'registry';\n if (originalSpec.registry) {\n currentSpec.registry = originalSpec.registry;\n }\n if (originalSpec.namespace) {\n currentSpec.namespace = originalSpec.namespace;\n }\n }\n }\n \n // Also check in original's dependencies for a match\n if (originalSpec.dependencies) {\n const originalDep = originalSpec.dependencies.find(d => d.name === currentSpec.name);\n if (originalDep && (originalDep.location === 'registry' || originalDep.registry)) {\n currentSpec.location = 'registry';\n if (originalDep.registry) {\n currentSpec.registry = originalDep.registry;\n }\n if (originalDep.namespace) {\n currentSpec.namespace = originalDep.namespace;\n }\n }\n }\n }\n \n // Process all dependencies recursively\n if (currentSpec.dependencies && Array.isArray(currentSpec.dependencies)) {\n currentSpec.dependencies.forEach((dep, index) => {\n // Find the corresponding original dependency by name or use the one at same index\n let originalDep = originalSpec.dependencies?.find(d => d.name === dep.name);\n if (!originalDep && originalSpec.dependencies && index < originalSpec.dependencies.length) {\n originalDep = originalSpec.dependencies[index];\n }\n if (originalDep) {\n processSpec(dep, originalDep);\n }\n });\n }\n };\n \n processSpec(enrichedSpec, this.component);\n return enrichedSpec;\n }\n\n /**\n * Render the React component\n */\n private async renderComponent() {\n // Don't render if component is being destroyed\n if (this.isDestroying) {\n return;\n }\n \n if (!this.compiledComponent || !this.reactRootId) {\n return;\n }\n\n // Prevent concurrent renders\n if (this.isRendering) {\n this.pendingRender = true;\n return;\n }\n\n const context = this.reactBridge.getCurrentContext();\n if (!context) {\n return;\n }\n\n this.isRendering = true;\n const { React } = context;\n \n // Resolve components with the correct version using runtime's resolver\n // SKIP this if using ComponentManager - components are already loaded!\n let components = {};\n if (!this.useComponentManager) {\n components = await this.resolveComponentsWithVersion(this.component, this.componentVersion);\n } else {\n // Use the dependencies that were already loaded and unwrapped by ComponentManager\n components = this.loadedDependencies;\n console.log(`🎯 [renderComponent] Using dependencies from ComponentManager:`, Object.keys(components));\n }\n \n // Create callbacks once per component instance\n if (!this.currentCallbacks) {\n this.currentCallbacks = this.createCallbacks();\n }\n \n // Get libraries from runtime context\n const runtimeContext = this.adapter.getRuntimeContext();\n const libraries = runtimeContext.libraries || {};\n \n // Build props — wrap utilities with data capture for fallback snapshot support.\n // Host-supplied componentProps spread first so platform-provided keys\n // (utilities, callbacks, components, styles, libraries, savedUserSettings,\n // onSaveUserSettings) always win — the contract stays stable regardless of\n // what a host passes in.\n const wrappedUtilities = this.wrapUtilitiesWithCapture(this.utilities);\n const props = {\n ...this._componentProps,\n utilities: wrappedUtilities,\n callbacks: this.currentCallbacks,\n components,\n styles: this.styles as any,\n libraries, // Pass the loaded libraries to components\n savedUserSettings: this._savedUserSettings,\n onSaveUserSettings: this.handleSaveUserSettings.bind(this)\n };\n\n // Validate component before creating element\n if (!this.compiledComponent.component) {\n LogError(`Component is undefined for ${this.component.name} during render`);\n return;\n }\n \n // Components should be functions after HOC wrapping\n if (typeof this.compiledComponent.component !== 'function') {\n LogError(`Component is not a function for ${this.component.name}: ${typeof this.compiledComponent.component}`);\n return;\n }\n\n // Create error boundary\n const ErrorBoundary = createErrorBoundary(React, {\n onError: this.handleReactError.bind(this),\n logErrors: true,\n recovery: 'retry'\n });\n\n // Create element with error boundary. Auto-theme component libraries (antd) from\n // the live MJ theme by wrapping the mounted tree in their theme provider — antd\n // components don't read styles.* on their own and would otherwise render in their\n // built-in light theme even in dark mode. One wrap themes every antd component in\n // the subtree; no-op when antd isn't loaded.\n const themedComponent = wrapWithLibraryThemeProviders(\n React,\n React.createElement(this.compiledComponent.component, props),\n libraries,\n this.styles as ComponentStyles\n );\n const element = React.createElement(\n ErrorBoundary,\n null,\n themedComponent\n );\n\n // Render with timeout protection using resource manager\n const timeoutId = resourceManager.setTimeout(\n this.componentId,\n () => {\n // Check if still rendering and not destroyed\n if (this.isRendering && !this.isDestroying) {\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: 'Component render timeout - possible infinite loop detected',\n source: 'render'\n }\n });\n }\n },\n 5000,\n { purpose: 'render-timeout-protection' }\n );\n\n // Use managed React root for rendering\n reactRootManager.render(\n this.reactRootId,\n element,\n () => {\n // Clear the timeout as render completed\n resourceManager.clearTimeout(this.componentId, timeoutId);\n \n // Don't update state if component is destroyed\n if (this.isDestroying) {\n return;\n }\n \n this.isRendering = false;\n \n // If there was a pending render request, execute it now\n if (this.pendingRender) {\n this.pendingRender = false;\n this.renderComponent();\n }\n }\n );\n }\n\n /**\n * Create callbacks for the React component\n */\n private createCallbacks(): ComponentCallbacks {\n return {\n RegisterMethod: (_methodName: string, _handler: any) => {\n // The component compiler wrapper will handle this internally\n // This is just a placeholder to satisfy the interface\n // The actual registration happens in the wrapper component\n },\n CreateSimpleNotification: (message: string, style: \"none\" | \"success\" | \"error\" | \"warning\" | \"info\", hideAfter?: number) => {\n // Use the MJ notification service to display the notification\n const notificationStyle = style as \"none\" | \"success\" | \"error\" | \"warning\" | \"info\" | undefined;\n this.notificationService.CreateSimpleNotification(\n message, \n style, \n hideAfter\n );\n },\n OpenEntityRecord: async (entityName: string, key: CompositeKey) => {\n let keyToUse: CompositeKey | null = null;\n if (key instanceof Array) {\n keyToUse = CompositeKey.FromKeyValuePairs(key);\n }\n else if (typeof key === 'object' && !!key.GetValueByFieldName) {\n keyToUse = key as CompositeKey;\n }\n else if (typeof key === 'object') {\n //} && !!key.FieldName && !!key.Value) {\n // possible that have an object that is a simple key/value pair with\n // FieldName and value properties\n const keyAny = key as any;\n if (keyAny.FieldName && keyAny.Value) {\n keyToUse = CompositeKey.FromKeyValuePairs([keyAny as KeyValuePair]);\n }\n }\n if (keyToUse) {\n // now in some cases we have key/value pairs that the component we are hosting\n // use, but are not the pkey, so if that is the case, we'll run a quick view to try\n // and get the pkey so that we can emit the openEntityRecord call with the pkey\n const md = this.ProviderToUse;\n const e = md.EntityByName(entityName);\n if (!e) {\n console.warn(`Entity not found: ${entityName}`);\n return;\n }\n let shouldRunView = false;\n // now check each key in the keyToUse to see if it is a pkey\n for (const singleKey of keyToUse.KeyValuePairs) {\n const field = e.Fields.find(f => f.Name.trim().toLowerCase() === singleKey.FieldName.trim().toLowerCase());\n if (!field) {\n // if we get here this is a problem, the component has given us a non-matching field, this shouldn't ever happen\n // but if it doesn't log warning to console and exit\n console.warn(`Non-matching field found for key: ${JSON.stringify(keyToUse)}`);\n return;\n }\n else if (!field.IsPrimaryKey) {\n // if we get here that means we have a non-pkey so we'll want to do a lookup via a RunView\n // to get the actual pkey value\n shouldRunView = true;\n break;\n }\n }\n\n // if we get here and shouldRunView is true, we need to run a view using the info provided\n // by our contained component to get the pkey\n if (shouldRunView) {\n const rv = RunView.FromMetadataProvider(this.ProviderToUse);\n const result = await rv.RunView({\n EntityName: entityName,\n ExtraFilter: keyToUse.ToWhereClause()\n })\n if (result && result.Success && result.Results.length > 0) {\n // we have a match, use the first row and update our keyToUse\n const kvPairs: KeyValuePair[] = [];\n e.PrimaryKeys.forEach(pk => {\n kvPairs.push(\n {\n FieldName: pk.Name,\n Value: result.Results[0][pk.Name]\n }\n )\n })\n keyToUse = CompositeKey.FromKeyValuePairs(kvPairs);\n }\n }\n\n this.openEntityRecord.emit({ entityName, key: keyToUse });\n }\n },\n NotifyEvent: async (eventName: string, args: BaseEventArgs) => {\n this.componentEvent.emit({ type: eventName, payload: args });\n }\n };\n }\n\n /**\n * Handle React component errors\n */\n private handleReactError(error: any, errorInfo?: any) {\n LogError(`React component error: ${error?.toString() || 'Unknown error'}`, errorInfo);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error?.toString() || 'Unknown error',\n errorInfo,\n source: 'react'\n }\n });\n }\n\n /**\n * Handle onSaveUserSettings from components.\n *\n * This implements the SavedUserSettings pattern: the component owns its single\n * settings object and hands us the full latest copy whenever it changes. We\n * (1) **merge** the payload over our in-memory snapshot so any future re-render\n * passes the latest values, (2) persist the merged snapshot per-user via\n * UserInfoEngine (debounced, auto-scoped) unless the host opted out, and\n * (3) still bubble the event up for any parent container that wants to observe\n * changes — carrying the merged snapshot, so observers and storage agree.\n *\n * Merge (not replace) makes the host resilient to a component passing only the\n * changed keys, and to the stale-prop case: we deliberately never re-render on\n * save, so the `savedUserSettings` prop a component spreads is frozen at mount\n * and would otherwise lose earlier same-session changes. Removing a key\n * requires explicit intent — set it to `null` (see applyUserSettingsUpdate).\n */\n private handleSaveUserSettings(newSettings: Record<string, any>) {\n // Keep our snapshot current WITHOUT going through the setter (which would\n // re-render). The component already holds the correct state — it's the one\n // that told us about the change — so re-rendering would only cause flicker.\n this._savedUserSettings = applyUserSettingsUpdate(this._savedUserSettings, newSettings);\n\n // Durably persist the latest settings for this user, scoped to this component.\n this.persistUserSettings(this._savedUserSettings);\n\n // Bubble the event up to parent containers (back-compat; no consumer required).\n this.userSettingsChanged.emit({\n settings: this._savedUserSettings,\n componentName: this.component?.name,\n timestamp: new Date()\n });\n }\n\n /**\n * Resolve the durable storage key for this component's per-user settings, or\n * null when persistence is disabled or no stable scope can be derived.\n */\n private getUserStateStorageKey(): string | null {\n if (!this.PersistUserSettings) {\n return null;\n }\n const scope = resolveUserStateScope(\n this.UserStateScope,\n this._component?.namespace,\n this._component?.name\n );\n return userStateStorageKey(scope);\n }\n\n /**\n * Seed `savedUserSettings` from durable per-user storage (UserInfoEngine),\n * merging stored values over any host-provided defaults (stored wins). Best\n * effort — any failure leaves the host-provided / empty settings in place.\n */\n private async seedUserSettingsFromStore(): Promise<void> {\n const key = this.getUserStateStorageKey();\n if (!key) {\n return;\n }\n try {\n const provider = this.ProviderToUse;\n const user = provider?.CurrentUser;\n if (!user) {\n return; // No user context — cannot scope settings to a user.\n }\n // Idempotent: a no-op when the engine is already loaded for this user.\n await UserInfoEngine.Instance.Config(false, user, provider);\n const stored = parseStoredUserSettings(UserInfoEngine.Instance.GetSetting(key));\n this._savedUserSettings = mergeUserSettings(this._savedUserSettings, stored);\n } catch (error) {\n if (this.enableLogging) {\n console.warn('MJReactComponent: failed to seed user settings from store', error);\n }\n }\n }\n\n /**\n * Persist the component's settings object for the current user (debounced,\n * cross-device). Best effort — failures are logged when logging is enabled and\n * never surfaced to the component.\n */\n private persistUserSettings(settings: Record<string, any> | string): void {\n const key = this.getUserStateStorageKey();\n if (!key) {\n return;\n }\n try {\n const provider = this.ProviderToUse;\n const user = provider?.CurrentUser;\n if (!user) {\n return;\n }\n // The component normally hands us an object, but guard against a caller\n // that already serialized it — double-stringifying would store a quoted\n // JSON string the seed path could not parse back into settings.\n const serialized = typeof settings === 'string' ? settings : JSON.stringify(settings);\n UserInfoEngine.Instance.SetSettingDebounced(key, serialized, user);\n } catch (error) {\n if (this.enableLogging) {\n console.warn('MJReactComponent: failed to persist user settings', error);\n }\n }\n }\n\n // =================================================================\n // Automatic Data Capture — intercept RunView/RunQuery for fallback\n // =================================================================\n\n /**\n * Wraps a ComponentUtilities object so that every RunView / RunViews / RunQuery\n * call transparently stores the result in `this.capturedData`. The wrapped\n * object is referentially distinct from the original and is safe to pass to\n * multiple renders (results accumulate until the component resets).\n */\n private wrapUtilitiesWithCapture(original: ComponentUtilities): ComponentUtilities {\n const self = this;\n const wrappedRv: SimpleRunView = {\n RunView: async (params: RunViewParams, contextUser?: unknown) => {\n const result = await original.rv.RunView(params, contextUser as undefined);\n if (result?.Success) {\n self.capturedData.push({\n sourceName: String(params.EntityName ?? params.ExtraFilter ?? 'Unknown'),\n sourceType: 'view',\n params: params as unknown as Record<string, unknown>,\n rows: result.Results ?? [],\n totalRows: result.TotalRowCount ?? result.Results?.length ?? 0,\n fetchedAt: new Date()\n });\n }\n return result;\n },\n RunViews: async (params: RunViewParams[], contextUser?: unknown) => {\n const results = await original.rv.RunViews(params, contextUser as undefined);\n results.forEach((result: RunViewResult, i: number) => {\n if (result?.Success) {\n self.capturedData.push({\n sourceName: String(params[i]?.EntityName ?? `View ${i}`),\n sourceType: 'view',\n params: params[i] as unknown as Record<string, unknown>,\n rows: result.Results ?? [],\n totalRows: result.TotalRowCount ?? result.Results?.length ?? 0,\n fetchedAt: new Date()\n });\n }\n });\n return results;\n }\n };\n\n const wrappedRq: SimpleRunQuery = {\n RunQuery: async (params: RunQueryParams, contextUser?: unknown) => {\n const result = await original.rq.RunQuery(params, contextUser as undefined);\n if (result?.Success) {\n self.capturedData.push({\n sourceName: String(params.QueryID ?? params.QueryName ?? 'Query'),\n sourceType: 'query',\n params: params as unknown as Record<string, unknown>,\n rows: (result.Results ?? []) as Record<string, unknown>[],\n totalRows: result.TotalRowCount ?? result.Results?.length ?? 0,\n fetchedAt: new Date()\n });\n }\n return result;\n }\n };\n\n return {\n ...original,\n rv: wrappedRv,\n rq: wrappedRq\n };\n }\n\n /**\n * Builds a DataSnapshot from captured RunView/RunQuery results.\n * Returns null if no data was captured.\n */\n private BuildCapturedDataSnapshot(): DataSnapshot | null {\n if (this.capturedData.length === 0) return null;\n\n const tables: DataTable[] = this.capturedData.map((captured, idx) => {\n const table = new DataTable();\n table.name = captured.sourceName || `Table ${idx + 1}`;\n table.source = captured.sourceType;\n table.rows = captured.rows;\n // Infer columns from the first row's keys\n if (captured.rows.length > 0) {\n const firstRow = captured.rows[0];\n table.columns = Object.keys(firstRow).map(key => {\n const col = new MJColumnDescriptor(key);\n col.displayName = key;\n const val = firstRow[key];\n if (typeof val === 'number') col.sqlBaseType = 'float';\n else if (val instanceof Date) col.sqlBaseType = 'datetime';\n else col.sqlBaseType = 'nvarchar';\n return col;\n });\n }\n table.metadata = {\n entityName: captured.sourceType === 'view' ? captured.sourceName : undefined,\n rowCount: captured.rows.length,\n totalAvailableRows: captured.totalRows,\n fetchedAt: captured.fetchedAt\n };\n return table;\n });\n\n return DataSnapshot.FromTables(tables, this.component?.title ?? this.component?.name);\n }\n\n /**\n * Clean up resources\n */\n private cleanup() {\n // Clean up all resources managed by resource manager\n resourceManager.cleanupComponent(this.componentId);\n \n // Clean up prop builder subscriptions\n if (this.currentCallbacks) {\n this.currentCallbacks = null;\n }\n \n // Unmount React root using managed unmount\n if (this.reactRootId) {\n // Force stop rendering flags\n this.isRendering = false;\n this.pendingRender = false;\n \n // This will handle waiting for render completion if needed\n reactRootManager.unmountRoot(this.reactRootId);\n this.reactRootId = null;\n }\n\n // Clear references\n this.compiledComponent = null;\n this.isInitialized = false;\n this.capturedData = [];\n\n // Trigger registry cleanup\n this.adapter.getRegistry().cleanup();\n }\n\n /**\n * Public method to refresh the component\n * @deprecated Components manage their own state and data now\n */\n refresh() {\n // Check if the component has registered a refresh method\n if (this.compiledComponent?.refresh) {\n this.compiledComponent.refresh();\n } else {\n // Fallback: trigger a re-render if needed\n this.renderComponent();\n }\n }\n\n /**\n * Public method to update state programmatically\n * @param path - State path to update\n * @param value - New value\n * @deprecated Components manage their own state now\n */\n updateState(path: string, value: any) {\n // Just emit the event, don't manage state here\n this.stateChange.emit({ path, value });\n }\n\n // =================================================================\n // Standard Component Methods - Strongly Typed\n // =================================================================\n \n /**\n * Gets the current data state of the component.\n * Tries the component's explicit implementation first, then falls back\n * to a DataSnapshot built from intercepted RunView/RunQuery results.\n */\n getCurrentDataState(): DataSnapshot | undefined {\n const explicit = this.compiledComponent?.getCurrentDataState?.();\n if (explicit && typeof explicit === 'object') return explicit;\n return this.BuildCapturedDataSnapshot() ?? undefined;\n }\n \n /**\n * Validates the current state of the component\n * @returns true if valid, false or validation errors otherwise\n */\n validate(): boolean | { valid: boolean; errors?: string[] } {\n return this.compiledComponent?.validate?.() || true;\n }\n \n /**\n * Checks if the component has unsaved changes\n * @returns true if dirty, false otherwise\n */\n isDirty(): boolean {\n return this.compiledComponent?.isDirty?.() || false;\n }\n \n /**\n * Resets the component to its initial state\n */\n reset(): void {\n this.compiledComponent?.reset?.();\n }\n \n /**\n * Scrolls to a specific element or position within the component\n * @param target - Element selector, element reference, or scroll options\n */\n scrollTo(target: string | HTMLElement | { top?: number; left?: number }): void {\n this.compiledComponent?.scrollTo?.(target);\n }\n \n /**\n * Sets focus to a specific element within the component\n * @param target - Element selector or element reference\n */\n focus(target?: string | HTMLElement): void {\n this.compiledComponent?.focus?.(target);\n }\n \n /**\n * Invokes a custom method on the component\n * @param methodName - Name of the method to invoke\n * @param args - Arguments to pass to the method\n * @returns The result of the method call, or undefined if method doesn't exist\n */\n invokeMethod(methodName: string, ...args: any[]): any {\n return this.compiledComponent?.invokeMethod?.(methodName, ...args);\n }\n \n /**\n * Checks if a method is available on the component\n * @param methodName - Name of the method to check\n * @returns true if the method exists\n */\n hasMethod(methodName: string): boolean {\n return this.compiledComponent?.hasMethod?.(methodName) || false;\n }\n \n /**\n * Print the component content\n * Uses component's print method if available, otherwise uses window.print()\n */\n print(): void {\n if (this.compiledComponent?.print) {\n this.compiledComponent.print();\n } else if (typeof window !== 'undefined' && window.print) {\n window.print();\n }\n }\n\n /**\n * Force clear component registries\n * Used by Component Studio for fresh loads\n * This is a static method that can be called without a component instance\n */\n public static forceClearRegistries(): void {\n // Clear React runtime's component registry service\n ComponentRegistryService.reset();\n\n // Clear any cached hierarchy registrar\n if (typeof window !== 'undefined' && (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__) {\n (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__ = null;\n }\n\n console.log('🧹 All component registries cleared for fresh load');\n }\n\n /**\n * Gets the current data state from the hosted React component.\n * Falls back to a DataSnapshot built from intercepted RunView/RunQuery results\n * when the component does not explicitly implement getCurrentDataState.\n */\n public GetCurrentDataState(): DataSnapshot | undefined {\n return this.getCurrentDataState();\n }\n\n /**\n * Applies a data state snapshot to the hosted React component.\n * Returns true if the snapshot was successfully applied, false if the\n * component does not support setDataState or the operation failed.\n */\n public SetDataState(snapshot: DataSnapshot): boolean {\n return this.compiledComponent?.setDataState?.(snapshot) ?? false;\n }\n\n}"]}
|
|
1
|
+
{"version":3,"file":"mj-react-component.component.js","sourceRoot":"","sources":["../../../src/lib/components/mj-react-component.component.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,SAAS,EACT,KAAK,EACL,MAAM,EACN,YAAY,EACZ,SAAS,EACT,UAAU,EAGV,uBAAuB,EACvB,iBAAiB,EAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,aAAa,EAAuF,MAAM,6CAA6C,CAAC;AACjK,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EACL,mBAAmB,EACnB,2BAA2B,EAC3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B,YACpB;;;;;;;;;;;;GAYT,mBA6CgB,uBAAuB,CAAC,MAAM;;kBAU9C,KAAK;;kBAmCL,KAAK;;kBACL,KAAK;;kBAIL,KAAK;;kBAuBL,KAAK;;kBAmGL,KAAK;;kBAqBL,KAAK;;kBASL,KAAK;;kBAaL,KAAK;;kBAWL,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBAEN,MAAM;;kBAEN,SAAS;mBAAC,WAAW,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE;;kFAxO/C,gBAAgB","sourcesContent":["/**\n * @fileoverview Angular component that hosts React components with proper memory management.\n * Provides a bridge between Angular and React ecosystems in MemberJunction applications.\n * @module @memberjunction/ng-react\n */\n\nimport {\n Component,\n Input,\n Output,\n EventEmitter,\n ViewChild,\n ElementRef,\n AfterViewInit,\n OnDestroy,\n ChangeDetectionStrategy,\n ChangeDetectorRef\n} from '@angular/core';\nimport { Subject } from 'rxjs';\nimport { BaseAngularComponent } from '@memberjunction/ng-base-types';\nimport { ComponentSpec, ComponentCallbacks, ComponentStyles, ComponentObject, BaseEventArgs, StyleOverrides } from '@memberjunction/interactive-component-types';\nimport { ReactBridgeService } from '../services/react-bridge.service';\nimport { AngularAdapterService } from '../services/angular-adapter.service';\nimport {\n createErrorBoundary,\n ComponentHierarchyRegistrar,\n resourceManager,\n reactRootManager,\n ResolvedComponents,\n SetupStyles,\n BuildStylesFromTheme,\n ApplyStyleOverrides,\n wrapWithLibraryThemeProviders,\n ComponentRegistryService,\n resolveUserStateScope,\n userStateStorageKey,\n parseStoredUserSettings,\n mergeUserSettings,\n applyUserSettingsUpdate\n} from '@memberjunction/react-runtime';\nimport { createRuntimeUtilities } from '../utilities/runtime-utilities';\nimport { LogError, CompositeKey, KeyValuePair, Metadata, RunView, RunViewParams, RunViewResult, RunQueryParams, RunQueryResult, DataSnapshot, DataTable, MJColumnDescriptor } from '@memberjunction/core';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { ComponentMetadataEngine, UserInfoEngine } from '@memberjunction/core-entities';\nimport { ComponentUtilities, SimpleRunView, SimpleRunQuery } from '@memberjunction/interactive-component-types';\n\n/**\n * A captured RunView/RunQuery result with its original parameters.\n * Used by the automatic data capture system for components that don't\n * implement getCurrentDataState().\n */\ninterface CapturedDataResult {\n /** Entity name or query name */\n sourceName: string;\n /** 'view' or 'query' */\n sourceType: 'view' | 'query';\n /** Original RunView/RunQuery params */\n params: Record<string, unknown>;\n /** Returned rows */\n rows: Record<string, unknown>[];\n /** Total available rows (may differ from rows.length due to pagination) */\n totalRows: number;\n /** When the data was fetched */\n fetchedAt: Date;\n}\n\n/**\n * Event emitted by React components\n */\nexport interface ReactComponentEvent {\n type: string;\n payload: any;\n}\n\n/**\n * State change event emitted when component state updates\n */\nexport interface StateChangeEvent {\n path: string;\n value: any;\n}\n\n/**\n * User settings changed event emitted when component saves user preferences\n */\nexport interface UserSettingsChangedEvent {\n settings: Record<string, any>;\n componentName?: string;\n timestamp: Date;\n}\n\n/**\n * Angular component that hosts React components with proper memory management.\n * This component provides a bridge between Angular and React, allowing React components\n * to be used seamlessly within Angular applications.\n */\n@Component({\n standalone: false,\n selector: 'mj-react-component',\n template: `\n <div class=\"react-component-wrapper\">\n <div #container class=\"react-component-container\" [class.loading]=\"!isInitialized\"></div>\n @if (!isInitialized && !hasError) {\n <div class=\"loading-overlay\">\n <div class=\"loading-spinner\">\n <i class=\"fa-solid fa-spinner fa-spin\"></i>\n </div>\n <div class=\"loading-text\">Loading component...</div>\n </div>\n }\n </div>\n `,\n styles: [`\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n .react-component-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n }\n .react-component-container {\n width: 100%;\n height: 100%;\n transition: opacity 0.3s ease;\n }\n .react-component-container.loading {\n opacity: 0;\n }\n .loading-overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 1;\n }\n .loading-spinner {\n font-size: 48px;\n color: #5B4FE9;\n margin-bottom: 16px;\n }\n .loading-text {\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n font-size: 14px;\n color: #64748B;\n margin-top: 8px;\n }\n `],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class MJReactComponent extends BaseAngularComponent implements AfterViewInit, OnDestroy {\n private _component!: ComponentSpec;\n\n /**\n * The component specification to render.\n * When this changes after initialization, the component will be reinitialized\n * to load and render the new specification.\n */\n @Input()\n set component(value: ComponentSpec) {\n const previousComponent = this._component;\n this._component = value;\n\n // If already initialized and component spec changed, reinitialize\n if (this.isInitialized && value && previousComponent !== value) {\n // Check if it's actually a different component (not just same reference)\n const isDifferent = !previousComponent ||\n previousComponent.name !== value.name ||\n previousComponent.code !== value.code ||\n previousComponent.version !== value.version;\n\n if (isDifferent) {\n this.reinitializeComponent();\n } else if (JSON.stringify(previousComponent.styleOverrides) !== JSON.stringify(value.styleOverrides)) {\n // Same code, new styleOverrides (a regenerated spec whose only change is the\n // requested styling): re-render in place — no teardown needed. The resolved\n // spec must be kept in step because the styleOverrides getter prefers it.\n if (this.resolvedComponentSpec) {\n this.resolvedComponentSpec.styleOverrides = value.styleOverrides;\n }\n this.renderComponent();\n }\n }\n }\n get component(): ComponentSpec {\n return this._component;\n }\n\n /**\n * Controls verbose logging for component lifecycle and operations.\n * Note: This does NOT control which React build (dev/prod) is loaded.\n * To control React builds, use ReactDebugConfig.setDebugMode() at app startup.\n */\n @Input() enableLogging: boolean = false;\n @Input() useComponentManager: boolean = true; // NEW: Use unified ComponentManager by default\n \n // Auto-initialize utilities if not provided\n private _utilities: any;\n @Input()\n set utilities(value: any) {\n this._utilities = value;\n }\n get utilities(): any {\n // Lazy initialization - only create default utilities when needed\n if (!this._utilities) {\n const runtimeUtils = createRuntimeUtilities();\n this._utilities = runtimeUtils.buildUtilities(this.enableLogging, this.ProviderToUse);\n if (this.enableLogging) {\n console.log('MJReactComponent: Auto-initialized utilities using createRuntimeUtilities()');\n }\n }\n return this._utilities;\n }\n \n // Auto-initialize styles if not provided\n private _styles?: Partial<ComponentStyles>;\n // Theme-bridge cache: the ComponentStyles derived from the live `--mj-*` theme,\n // memoized per theme key so we don't re-read getComputedStyle on every access.\n private _themeStyles?: ComponentStyles;\n private _themeStylesKey?: string;\n private themeObserver?: MutationObserver;\n @Input()\n set styles(value: Partial<ComponentStyles> | undefined) {\n this._styles = value;\n }\n get styles(): Partial<ComponentStyles> {\n // An explicitly-provided styles input always wins — but user-requested overrides\n // still layer on top, since they represent an explicit request rather than a theme.\n if (this._styles) {\n return this.applyStyleOverridesMemoized(this._styles);\n }\n // Otherwise bridge the host's live MJ theme (--mj-* tokens) into ComponentStyles\n // so generated components inherit the active theme — including dark mode and\n // hover/active/focus state families — instead of the frozen defaults. Memoized\n // per theme key; invalidated by the MutationObserver on data-theme changes.\n const key = this.computeThemeKey();\n if (!this._themeStyles || this._themeStylesKey !== key) {\n this._themeStyles = BuildStylesFromTheme();\n this._themeStylesKey = key;\n if (this.enableLogging) {\n console.log(`MJReactComponent: Bridged styles from live theme (key=\"${key}\")`);\n }\n }\n // Applied outside the theme memo so the spec's overrides survive a theme flip\n // (the memo caches the theme, not the request).\n return this.applyStyleOverridesMemoized(this._themeStyles);\n }\n\n /**\n * Explicitly user-requested styling from the spec being rendered, resolved above\n * the theme. Reads the resolved spec when available (registry components resolve\n * asynchronously) and falls back to the spec passed in.\n */\n private get styleOverrides(): StyleOverrides | undefined {\n return this.resolvedComponentSpec?.styleOverrides ?? this._component?.styleOverrides;\n }\n\n // Memo for the override merge. ApplyStyleOverrides allocates a new object whenever\n // overrides are present, and components key effects/memos on the styles identity\n // (e.g. simple-chart tears down and rebuilds its Chart.js instance) — so the merged\n // result must be stable across reads. Keyed by reference: a theme rebuild, a new\n // styles input, or a restyled spec each produce a new ref, which is exactly when\n // the merge must re-run.\n private _mergedStylesBase?: Partial<ComponentStyles>;\n private _mergedStylesOverrides?: StyleOverrides;\n private _mergedStylesResult?: Partial<ComponentStyles>;\n\n private applyStyleOverridesMemoized(base: Partial<ComponentStyles>): Partial<ComponentStyles> {\n const overrides = this.styleOverrides;\n if (!overrides) {\n return base;\n }\n if (!this._mergedStylesResult || this._mergedStylesBase !== base || this._mergedStylesOverrides !== overrides) {\n this._mergedStylesBase = base;\n this._mergedStylesOverrides = overrides;\n this._mergedStylesResult = ApplyStyleOverrides(base, overrides);\n }\n return this._mergedStylesResult;\n }\n\n /**\n * Identifies the current theme so bridged styles can be memoized and refreshed\n * when the user's mode (`data-theme`) or the org overlay (`data-theme-overlay`)\n * changes. Non-DOM environments return a constant key.\n */\n private computeThemeKey(): string {\n if (typeof document === 'undefined') {\n return 'no-dom';\n }\n const root = document.documentElement;\n return `${root.getAttribute('data-theme') || 'light'}|${root.getAttribute('data-theme-overlay') || ''}`;\n }\n\n /**\n * Watches the document root for theme changes (`data-theme` / `data-theme-overlay`)\n * and, when the theme flips, invalidates the bridged-styles cache and re-renders so\n * the live React component picks up the new theme. No-op when styles are supplied\n * explicitly or when there is no DOM.\n */\n private setupThemeObserver(): void {\n if (this._styles || typeof MutationObserver === 'undefined' || typeof document === 'undefined') {\n return;\n }\n this.themeObserver = new MutationObserver(() => {\n const key = this.computeThemeKey();\n if (key !== this._themeStylesKey) {\n this._themeStyles = undefined;\n this._themeStylesKey = undefined;\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n });\n this.themeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['data-theme', 'data-theme-overlay'],\n });\n }\n \n private _savedUserSettings: any = {};\n @Input()\n set savedUserSettings(value: any) {\n this._savedUserSettings = value || {};\n // Re-render if component is initialized\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n get savedUserSettings(): any {\n return this._savedUserSettings;\n }\n\n /**\n * Optional explicit scope for per-user settings persistence. When omitted, the\n * scope defaults to `<namespace>/<name>` of the component spec. Settings are\n * stored per-user via `UserInfoEngine` under the key\n * `InteractiveComponents_UserState_Root/<scope>`. Provide an\n * explicit scope when a single component spec is rendered in multiple distinct\n * contexts that should NOT share preferences (e.g. the same form spec used for\n * different entities) — set it to something stable and unique per context.\n */\n @Input() UserStateScope?: string;\n\n /**\n * When `true` (default), the host transparently persists `savedUserSettings`\n * per-user, cross-device via `UserInfoEngine` — seeding the component from\n * storage on load and saving (debounced) on every `onSaveUserSettings` call,\n * auto-scoped per component. Set to `false` to opt out and own persistence\n * yourself by handling the `userSettingsChanged` output instead.\n */\n @Input() PersistUserSettings: boolean = true;\n\n /**\n * Host-supplied props spread into the React component's props alongside the\n * standard `utilities`, `callbacks`, `components`, `styles`, `libraries`, and\n * `savedUserSettings`. Used by hosts that need to push data context the React\n * component can't fetch itself — e.g. `InteractiveFormComponent` passing\n * `FormHostProps` (the current record snapshot, mode, permissions).\n *\n * Standard keys take precedence over caller-supplied keys to keep the\n * platform contract stable.\n */\n private _componentProps: object = {};\n @Input()\n set componentProps(value: object | undefined) {\n this._componentProps = value ?? {};\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n get componentProps(): object {\n return this._componentProps;\n }\n\n @Output() stateChange = new EventEmitter<StateChangeEvent>();\n @Output() componentEvent = new EventEmitter<ReactComponentEvent>();\n @Output() refreshData = new EventEmitter<void>();\n @Output() openEntityRecord = new EventEmitter<{ entityName: string; key: CompositeKey }>();\n @Output() userSettingsChanged = new EventEmitter<UserSettingsChangedEvent>();\n /** Emitted once after the component successfully loads and resolvedComponentSpec is populated. */\n @Output() initialized = new EventEmitter<void>();\n \n @ViewChild('container', { read: ElementRef, static: true }) container!: ElementRef<HTMLDivElement>;\n\n // ─── Automatic data capture ───\n // Stores RunView/RunQuery results for components that don't implement getCurrentDataState().\n // Cleared on component reinitialize. Used as fallback in GetCurrentDataState().\n private capturedData: CapturedDataResult[] = [];\n\n private reactRootId: string | null = null;\n private compiledComponent: ComponentObject | null = null;\n private loadedDependencies: Record<string, ComponentObject> = {};\n private destroyed$ = new Subject<void>();\n private currentCallbacks: ComponentCallbacks | null = null;\n isInitialized = false;\n private isRendering = false;\n private pendingRender = false;\n private isDestroying = false;\n private componentId: string;\n private componentVersion: string = ''; // Store the version for resolver\n hasError = false;\n \n /**\n * Public property containing the fully resolved component specification.\n * This includes all external code fetched from registries, allowing consumers\n * to inspect the complete resolved specification including dependencies.\n * Only populated after successful component initialization.\n */\n public resolvedComponentSpec: ComponentSpec | null = null;\n\n constructor(\n private reactBridge: ReactBridgeService,\n private adapter: AngularAdapterService,\n private cdr: ChangeDetectorRef,\n private notificationService: MJNotificationService\n ) {\n super();\n // Generate unique component ID for resource tracking\n this.componentId = `mj-react-component-${Date.now()}-${Math.random()}`;\n }\n\n async ngAfterViewInit() {\n // Try to get registry size safely\n let registrySize = 'N/A';\n try {\n if (this.adapter.isInitialized()) {\n registrySize = this.adapter.getRegistry().size().toString();\n } else {\n registrySize = 'Not initialized yet';\n }\n } catch (e) {\n registrySize = 'Not available';\n }\n \n console.log(`🎬 [ngAfterViewInit] Starting component initialization:`, {\n componentId: this.componentId,\n componentName: this.component?.name,\n timestamp: new Date().toISOString(),\n registrySize: registrySize\n });\n \n // Trigger change detection to show loading state\n this.cdr.detectChanges();\n // Refresh bridged theme styles when the user's mode / org overlay changes.\n this.setupThemeObserver();\n await this.initializeComponent();\n }\n\n ngOnDestroy() {\n // Set destroying flag immediately\n this.isDestroying = true;\n\n // Cancel any pending renders\n this.pendingRender = false;\n\n this.themeObserver?.disconnect();\n this.themeObserver = undefined;\n\n this.destroyed$.next();\n this.destroyed$.complete();\n this.cleanup();\n }\n\n /**\n * Reinitialize the component when the input spec changes.\n * Cleans up the current component and initializes with the new spec.\n */\n private async reinitializeComponent() {\n // Don't reinitialize if we're being destroyed\n if (this.isDestroying) {\n return;\n }\n\n // Clear cached state from previous component\n this.compiledComponent = null;\n this.resolvedComponentSpec = null;\n this.loadedDependencies = {};\n this.componentVersion = '';\n this.hasError = false;\n this.isInitialized = false;\n this.capturedData = [];\n\n // Unmount existing React root if present\n if (this.reactRootId) {\n this.isRendering = false;\n this.pendingRender = false;\n reactRootManager.unmountRoot(this.reactRootId);\n this.reactRootId = null;\n }\n\n // Trigger change detection to show loading state\n this.cdr.detectChanges();\n\n // Initialize with the new component spec\n await this.initializeComponent();\n }\n\n /**\n * Initialize the React component\n */\n private async initializeComponent() {\n try {\n // Ensure React is loaded\n await this.reactBridge.getReactContext();\n\n // Wait for React to be fully ready (handles first-load delay)\n await this.reactBridge.waitForReactReady();\n\n // NEW: Use ComponentManager if enabled (default: true)\n if (this.useComponentManager) {\n console.log(`🎯 [initializeComponent] Using NEW ComponentManager approach`);\n await this.loadComponentWithManager();\n \n // Component is already compiled and stored in this.compiledComponent\n // No need to fetch from registry - it's already set\n } else {\n console.log(`📦 [initializeComponent] Using legacy approach (will be deprecated)`);\n // Register component hierarchy (this compiles and registers all components including from registries)\n await this.registerComponentHierarchy();\n \n // The resolved spec should now be available from the registration result\n // No need to fetch again\n \n // Get the already-registered component from the registry\n const registry = this.adapter.getRegistry();\n \n console.log(`🔍 [initializeComponent] Looking for component in registry:`, {\n name: this.component.name,\n namespace: this.component.namespace || 'Global',\n version: this.componentVersion\n });\n \n // Let's also check what's actually in the registry\n // Note: ComponentRegistry doesn't have a list() method, so we'll skip this for now\n \n const componentWrapper = registry.get(\n this.component.name, \n this.component.namespace || 'Global', \n this.componentVersion\n );\n \n console.log(`🔍 [initializeComponent] Registry.get result:`, {\n found: !!componentWrapper,\n type: componentWrapper ? typeof componentWrapper : 'undefined',\n hasComponent: componentWrapper ? !!componentWrapper.component : false\n });\n \n if (!componentWrapper) {\n const source = this.component.registry ? `external registry ${this.component.registry}` : 'local registry';\n console.error(`❌ [initializeComponent] Component not found! Details:`, {\n searchedName: this.component.name,\n searchedNamespace: this.component.namespace || 'Global',\n searchedVersion: this.componentVersion,\n source: source\n });\n throw new Error(`Component ${this.component.name} was not found in registry after registration from ${source}`);\n }\n \n // The registry now stores ComponentObjects directly\n // Validate it has the expected structure\n if (!componentWrapper || typeof componentWrapper !== 'object') {\n throw new Error(`Invalid component wrapper returned for ${this.component.name}: ${typeof componentWrapper}`);\n }\n \n if (!componentWrapper.component) {\n throw new Error(`Component wrapper missing 'component' property for ${this.component.name}`);\n }\n \n // Now that we use a regular HOC wrapper, components should always be functions\n if (typeof componentWrapper.component !== 'function') {\n throw new Error(`Component is not a function for ${this.component.name}: ${typeof componentWrapper.component}`);\n }\n \n this.compiledComponent = componentWrapper;\n } // End of else block for legacy approach\n \n // Create managed React root\n const reactContext = this.reactBridge.getCurrentContext();\n if (!reactContext) {\n throw new Error('React context not available');\n }\n \n this.reactRootId = reactRootManager.createRoot(\n this.container.nativeElement,\n (container: HTMLElement) => reactContext.ReactDOM.createRoot(container),\n this.componentId\n );\n\n // Seed savedUserSettings from durable per-user storage before the first\n // render so the component mounts with the user's persisted preferences.\n await this.seedUserSettingsFromStore();\n\n // Initial render\n this.renderComponent();\n this.isInitialized = true;\n\n // Trigger change detection since we're using OnPush\n this.cdr.detectChanges();\n\n // Notify parent that the component has successfully initialized and\n // resolvedComponentSpec is now populated with the full spec from the registry\n this.initialized.emit();\n\n } catch (error) {\n this.hasError = true;\n LogError(`Failed to initialize React component: ${error}`);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error instanceof Error ? error.message : String(error),\n source: 'initialization'\n }\n });\n // Trigger change detection to show error state\n this.cdr.detectChanges();\n }\n }\n \n\n /**\n * Generate a hash from component code for versioning\n * Uses a simple hash function that's fast and sufficient for version differentiation\n */\n private generateComponentHash(spec: ComponentSpec): string {\n // Collect all code from the component hierarchy\n const codeStrings: string[] = [];\n \n const collectCode = (s: ComponentSpec) => {\n if (s.code) {\n codeStrings.push(s.code);\n }\n if (s.dependencies) {\n for (const dep of s.dependencies) {\n collectCode(dep);\n }\n }\n };\n \n collectCode(spec);\n \n // Generate hash from concatenated code\n const fullCode = codeStrings.join('|');\n let hash = 0;\n for (let i = 0; i < fullCode.length; i++) {\n const char = fullCode.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n \n // Convert to hex string and take first 8 characters for readability\n const hexHash = Math.abs(hash).toString(16).padStart(8, '0').substring(0, 8);\n return `v${hexHash}`;\n }\n\n /**\n * Resolve components using the runtime's resolver\n */\n private async resolveComponentsWithVersion(spec: ComponentSpec, version: string, namespace: string = 'Global'): Promise<ResolvedComponents> {\n const resolver = this.adapter.getResolver();\n \n // Debug: Log what dependencies we're trying to resolve\n if (this.enableLogging) {\n console.log(`Resolving components for ${spec.name}. Dependencies:`, spec.dependencies);\n }\n \n // Use the runtime's resolver which now handles registry-based components\n const resolved = await resolver.resolveComponents(\n spec, \n namespace,\n this.ProviderToUse.CurrentUser // Pass current user context for database operations\n );\n \n if (this.enableLogging) {\n console.log(`Resolved ${Object.keys(resolved).length} components for version ${version}:`, Object.keys(resolved));\n }\n return resolved;\n }\n\n\n /**\n * NEW: Load component using unified ComponentManager - MUCH SIMPLER!\n */\n private async loadComponentWithManager() {\n try {\n const manager = this.adapter.getComponentManager();\n \n console.log(`🚀 [ComponentManager] Loading component hierarchy: ${this.component.name}`);\n \n // Load the entire hierarchy with one simple call\n const result = await manager.loadHierarchy(this.component, {\n contextUser: this.ProviderToUse.CurrentUser,\n defaultNamespace: 'Global',\n defaultVersion: this.component.version || this.generateComponentHash(this.component),\n returnType: 'both'\n });\n \n if (!result.success) {\n const errorMessages = result.errors.map(e => `${e.componentName}: ${e.message}`).join(', ');\n console.error(`❌ [ComponentManager] Failed to load hierarchy:`, errorMessages);\n throw new Error(`Component loading failed: ${errorMessages}`);\n }\n \n // Store the results (handle undefined values)\n this.resolvedComponentSpec = this.enrichSpecWithRegistryInfo(result.resolvedSpec || null);\n this.compiledComponent = result.rootComponent || null;\n this.componentVersion = result.resolvedSpec?.version || this.component.version || 'latest';\n \n // IMPORTANT: Store the loaded dependencies for use in renderComponent\n this.loadedDependencies = result.components || {};\n \n console.log(`✅ [ComponentManager] Successfully loaded hierarchy:`, {\n rootComponent: result.resolvedSpec?.name,\n loadedCount: result.loadedComponents.length,\n dependencies: Object.keys(this.loadedDependencies),\n stats: result.stats\n });\n \n // Component is ready to render\n return true;\n \n } catch (error) {\n console.error(`❌ [ComponentManager] Error loading component:`, error);\n throw error;\n }\n }\n\n /**\n * Register all components in the hierarchy\n * @deprecated Use loadComponentWithManager() instead\n */\n private async registerComponentHierarchy() {\n // Use semantic version from spec or generate hash-based version for uniqueness\n const version = this.component.version || this.generateComponentHash(this.component);\n this.componentVersion = version; // Store for use in resolver\n \n console.log(`🔍 [registerComponentHierarchy] Starting registration for ${this.component.name}@${version}`, {\n location: this.component.location,\n registry: this.component.registry,\n namespace: this.component.namespace,\n hasCode: !!this.component.code,\n codeLength: this.component.code?.length || 0\n });\n \n // Check if already registered to avoid duplication\n const registry = this.adapter.getRegistry();\n const checkNamespace = this.component.namespace || 'Global';\n \n console.log(`🔍 [registerComponentHierarchy] Checking registry for existing component:`, {\n name: this.component.name,\n namespace: checkNamespace,\n version: version,\n registrySize: registry.size(),\n registryId: registry.registryId || 'unknown'\n });\n \n // Log registry state for debugging\n console.log(`📦 [registerComponentHierarchy] Registry state:`, {\n totalSize: registry.size(),\n registryInstance: registry.registryId || 'unknown'\n });\n \n const existingComponent = registry.get(this.component.name, checkNamespace, version);\n \n if (existingComponent) {\n console.log(`⚠️ [registerComponentHierarchy] Component ${this.component.name}@${version} already registered!`, {\n existingType: typeof existingComponent,\n hasComponent: !!(existingComponent as any).component,\n registrationTime: (existingComponent as any).registeredAt || 'unknown',\n runtimeContextLibraries: Object.keys(this.adapter.getRuntimeContext().libraries || {})\n });\n \n // For registry components, we need to check the resolved spec's libraries, not the input spec\n // The input spec from Angular doesn't have library information for registry components\n if (this.component.location === 'registry' && this.component.registry) {\n console.log(`📋 [registerComponentHierarchy] Component is from registry, need to fetch full spec to check libraries`);\n // Continue to fetch the full spec below - don't return early\n } else {\n // For local components, check using the input spec\n const requiredLibraries = this.component.libraries || [];\n const runtimeLibraries = this.adapter.getRuntimeContext().libraries || {};\n const missingLibraries = requiredLibraries.filter(lib => !runtimeLibraries[lib.globalVariable]);\n \n if (missingLibraries.length > 0) {\n console.warn(`⚠️ [registerComponentHierarchy] Component registered but libraries missing:`, {\n required: requiredLibraries.map(l => l.globalVariable),\n loaded: Object.keys(runtimeLibraries),\n missing: missingLibraries.map(l => l.globalVariable)\n });\n // Don't return early - continue to load libraries\n } else {\n console.log(`✅ [registerComponentHierarchy] Component ${this.component.name}@${version} already registered with all libraries, skipping`);\n return;\n }\n }\n } else {\n console.log(`🆕 [registerComponentHierarchy] Component not found in registry, proceeding with registration`);\n }\n \n // Initialize metadata engine\n await ComponentMetadataEngine.Instance.Config(false, this.ProviderToUse.CurrentUser);\n \n // Use the runtime's hierarchy registrar\n const registrar = new ComponentHierarchyRegistrar(\n this.adapter.getCompiler(),\n this.adapter.getRegistry(),\n this.adapter.getRuntimeContext()\n );\n \n console.log(`📦 [registerComponentHierarchy] Calling registrar.registerHierarchy for ${this.component.name}`, {\n hasStyles: !!this.styles,\n namespace: this.component.namespace || 'Global',\n version: version,\n libraryCount: ComponentMetadataEngine.Instance.ComponentLibraries?.length || 0,\n hasCode: !!this.component.code,\n codeLength: this.component.code?.length || 0\n });\n \n // Register with proper configuration\n // Pass the partial spec - the React runtime will handle fetching from registries\n const result = await registrar.registerHierarchy(\n this.component, // Pass the original spec, not fetched\n {\n styles: this.styles as ComponentStyles,\n namespace: this.component.namespace || 'Global',\n version: version,\n allowOverride: false, // Each version is unique\n allLibraries: ComponentMetadataEngine.Instance.ComponentLibraries,\n debug: true,\n contextUser: this.ProviderToUse.CurrentUser\n }\n );\n \n if (!result.success) {\n const errors = result.errors.map(e => e.error).join(', ');\n console.error(`❌ [registerComponentHierarchy] Registration failed:`, errors);\n throw new Error(`Component registration failed: ${errors}`);\n }\n \n // Store the resolved spec from the registration result\n if (result.resolvedSpec) {\n this.resolvedComponentSpec = this.enrichSpecWithRegistryInfo(result.resolvedSpec || null);\n console.log(`📋 [registerComponentHierarchy] Received resolved spec from runtime:`, {\n name: result.resolvedSpec.name,\n hasCode: !!result.resolvedSpec.code,\n libraryCount: result.resolvedSpec.libraries?.length || 0,\n dependencyCount: result.resolvedSpec.dependencies?.length || 0\n });\n }\n \n console.log(`✅ [registerComponentHierarchy] Successfully registered ${result.registeredComponents.length} components:`, result.registeredComponents);\n \n // Verify the component is actually in the registry\n const verifyComponent = registry.get(this.component.name, this.component.namespace || 'Global', version);\n console.log(`🔍 [registerComponentHierarchy] Verification - component in registry after registration:`, {\n found: !!verifyComponent,\n name: this.component.name,\n namespace: this.component.namespace || 'Global',\n version: version,\n componentType: verifyComponent ? typeof verifyComponent : 'not found'\n });\n }\n\n /**\n * Post-process resolved spec to ensure all components show their true registry source.\n * This enriches the spec for UI display purposes to show where components actually came from.\n * Applied to all resolved specs so any consumer of this wrapper benefits.\n */\n private enrichSpecWithRegistryInfo(spec: ComponentSpec | null): ComponentSpec | null {\n if (!spec || !this.component) return spec;\n \n // Create a deep copy to avoid mutating the original\n const enrichedSpec = JSON.parse(JSON.stringify(spec));\n \n // Recursive function to process spec and all dependencies\n // Takes the original spec at the same level to find registry info\n const processSpec = (currentSpec: ComponentSpec, originalSpec: ComponentSpec) => {\n // If this component has code but shows location as 'embedded', \n // check the original spec to see where it came from\n if (currentSpec.code && currentSpec.location === 'embedded' && currentSpec.name) {\n // Try to find this component in the original spec at the same level\n // First check if the original spec itself matches by name\n if (originalSpec.name === currentSpec.name) {\n // Use the original's registry info if it had any\n if (originalSpec.location === 'registry' || originalSpec.registry) {\n currentSpec.location = 'registry';\n if (originalSpec.registry) {\n currentSpec.registry = originalSpec.registry;\n }\n if (originalSpec.namespace) {\n currentSpec.namespace = originalSpec.namespace;\n }\n }\n }\n \n // Also check in original's dependencies for a match\n if (originalSpec.dependencies) {\n const originalDep = originalSpec.dependencies.find(d => d.name === currentSpec.name);\n if (originalDep && (originalDep.location === 'registry' || originalDep.registry)) {\n currentSpec.location = 'registry';\n if (originalDep.registry) {\n currentSpec.registry = originalDep.registry;\n }\n if (originalDep.namespace) {\n currentSpec.namespace = originalDep.namespace;\n }\n }\n }\n }\n \n // Process all dependencies recursively\n if (currentSpec.dependencies && Array.isArray(currentSpec.dependencies)) {\n currentSpec.dependencies.forEach((dep, index) => {\n // Find the corresponding original dependency by name or use the one at same index\n let originalDep = originalSpec.dependencies?.find(d => d.name === dep.name);\n if (!originalDep && originalSpec.dependencies && index < originalSpec.dependencies.length) {\n originalDep = originalSpec.dependencies[index];\n }\n if (originalDep) {\n processSpec(dep, originalDep);\n }\n });\n }\n };\n \n processSpec(enrichedSpec, this.component);\n return enrichedSpec;\n }\n\n /**\n * Render the React component\n */\n private async renderComponent() {\n // Don't render if component is being destroyed\n if (this.isDestroying) {\n return;\n }\n \n if (!this.compiledComponent || !this.reactRootId) {\n return;\n }\n\n // Prevent concurrent renders\n if (this.isRendering) {\n this.pendingRender = true;\n return;\n }\n\n const context = this.reactBridge.getCurrentContext();\n if (!context) {\n return;\n }\n\n this.isRendering = true;\n const { React } = context;\n \n // Resolve components with the correct version using runtime's resolver\n // SKIP this if using ComponentManager - components are already loaded!\n let components = {};\n if (!this.useComponentManager) {\n components = await this.resolveComponentsWithVersion(this.component, this.componentVersion);\n } else {\n // Use the dependencies that were already loaded and unwrapped by ComponentManager\n components = this.loadedDependencies;\n console.log(`🎯 [renderComponent] Using dependencies from ComponentManager:`, Object.keys(components));\n }\n \n // Create callbacks once per component instance\n if (!this.currentCallbacks) {\n this.currentCallbacks = this.createCallbacks();\n }\n \n // Get libraries from runtime context\n const runtimeContext = this.adapter.getRuntimeContext();\n const libraries = runtimeContext.libraries || {};\n \n // Build props — wrap utilities with data capture for fallback snapshot support.\n // Host-supplied componentProps spread first so platform-provided keys\n // (utilities, callbacks, components, styles, libraries, savedUserSettings,\n // onSaveUserSettings) always win — the contract stays stable regardless of\n // what a host passes in.\n const wrappedUtilities = this.wrapUtilitiesWithCapture(this.utilities);\n const props = {\n ...this._componentProps,\n utilities: wrappedUtilities,\n callbacks: this.currentCallbacks,\n components,\n styles: this.styles as any,\n libraries, // Pass the loaded libraries to components\n savedUserSettings: this._savedUserSettings,\n onSaveUserSettings: this.handleSaveUserSettings.bind(this)\n };\n\n // Validate component before creating element\n if (!this.compiledComponent.component) {\n LogError(`Component is undefined for ${this.component.name} during render`);\n return;\n }\n \n // Components should be functions after HOC wrapping\n if (typeof this.compiledComponent.component !== 'function') {\n LogError(`Component is not a function for ${this.component.name}: ${typeof this.compiledComponent.component}`);\n return;\n }\n\n // Create error boundary\n const ErrorBoundary = createErrorBoundary(React, {\n onError: this.handleReactError.bind(this),\n logErrors: true,\n recovery: 'retry'\n });\n\n // Create element with error boundary. Auto-theme component libraries (antd) from\n // the live MJ theme by wrapping the mounted tree in their theme provider — antd\n // components don't read styles.* on their own and would otherwise render in their\n // built-in light theme even in dark mode. One wrap themes every antd component in\n // the subtree; no-op when antd isn't loaded.\n const themedComponent = wrapWithLibraryThemeProviders(\n React,\n React.createElement(this.compiledComponent.component, props),\n libraries,\n this.styles as ComponentStyles\n );\n const element = React.createElement(\n ErrorBoundary,\n null,\n themedComponent\n );\n\n // Render with timeout protection using resource manager\n const timeoutId = resourceManager.setTimeout(\n this.componentId,\n () => {\n // Check if still rendering and not destroyed\n if (this.isRendering && !this.isDestroying) {\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: 'Component render timeout - possible infinite loop detected',\n source: 'render'\n }\n });\n }\n },\n 5000,\n { purpose: 'render-timeout-protection' }\n );\n\n // Use managed React root for rendering\n reactRootManager.render(\n this.reactRootId,\n element,\n () => {\n // Clear the timeout as render completed\n resourceManager.clearTimeout(this.componentId, timeoutId);\n \n // Don't update state if component is destroyed\n if (this.isDestroying) {\n return;\n }\n \n this.isRendering = false;\n \n // If there was a pending render request, execute it now\n if (this.pendingRender) {\n this.pendingRender = false;\n this.renderComponent();\n }\n }\n );\n }\n\n /**\n * Create callbacks for the React component\n */\n private createCallbacks(): ComponentCallbacks {\n return {\n RegisterMethod: (_methodName: string, _handler: any) => {\n // The component compiler wrapper will handle this internally\n // This is just a placeholder to satisfy the interface\n // The actual registration happens in the wrapper component\n },\n CreateSimpleNotification: (message: string, style: \"none\" | \"success\" | \"error\" | \"warning\" | \"info\", hideAfter?: number) => {\n // Use the MJ notification service to display the notification\n const notificationStyle = style as \"none\" | \"success\" | \"error\" | \"warning\" | \"info\" | undefined;\n this.notificationService.CreateSimpleNotification(\n message, \n style, \n hideAfter\n );\n },\n OpenEntityRecord: async (entityName: string, key: CompositeKey) => {\n let keyToUse: CompositeKey | null = null;\n if (key instanceof Array) {\n keyToUse = CompositeKey.FromKeyValuePairs(key);\n }\n else if (typeof key === 'object' && !!key.GetValueByFieldName) {\n keyToUse = key as CompositeKey;\n }\n else if (typeof key === 'object') {\n //} && !!key.FieldName && !!key.Value) {\n // possible that have an object that is a simple key/value pair with\n // FieldName and value properties\n const keyAny = key as any;\n if (keyAny.FieldName && keyAny.Value) {\n keyToUse = CompositeKey.FromKeyValuePairs([keyAny as KeyValuePair]);\n }\n }\n if (keyToUse) {\n // now in some cases we have key/value pairs that the component we are hosting\n // use, but are not the pkey, so if that is the case, we'll run a quick view to try\n // and get the pkey so that we can emit the openEntityRecord call with the pkey\n const md = this.ProviderToUse;\n const e = md.EntityByName(entityName);\n if (!e) {\n console.warn(`Entity not found: ${entityName}`);\n return;\n }\n let shouldRunView = false;\n // now check each key in the keyToUse to see if it is a pkey\n for (const singleKey of keyToUse.KeyValuePairs) {\n const field = e.Fields.find(f => f.Name.trim().toLowerCase() === singleKey.FieldName.trim().toLowerCase());\n if (!field) {\n // if we get here this is a problem, the component has given us a non-matching field, this shouldn't ever happen\n // but if it doesn't log warning to console and exit\n console.warn(`Non-matching field found for key: ${JSON.stringify(keyToUse)}`);\n return;\n }\n else if (!field.IsPrimaryKey) {\n // if we get here that means we have a non-pkey so we'll want to do a lookup via a RunView\n // to get the actual pkey value\n shouldRunView = true;\n break;\n }\n }\n\n // if we get here and shouldRunView is true, we need to run a view using the info provided\n // by our contained component to get the pkey\n if (shouldRunView) {\n const rv = RunView.FromMetadataProvider(this.ProviderToUse);\n const result = await rv.RunView({\n EntityName: entityName,\n ExtraFilter: keyToUse.ToWhereClause()\n })\n if (result && result.Success && result.Results.length > 0) {\n // we have a match, use the first row and update our keyToUse\n const kvPairs: KeyValuePair[] = [];\n e.PrimaryKeys.forEach(pk => {\n kvPairs.push(\n {\n FieldName: pk.Name,\n Value: result.Results[0][pk.Name]\n }\n )\n })\n keyToUse = CompositeKey.FromKeyValuePairs(kvPairs);\n }\n }\n\n this.openEntityRecord.emit({ entityName, key: keyToUse });\n }\n },\n NotifyEvent: async (eventName: string, args: BaseEventArgs) => {\n this.componentEvent.emit({ type: eventName, payload: args });\n }\n };\n }\n\n /**\n * Handle React component errors\n */\n private handleReactError(error: any, errorInfo?: any) {\n LogError(`React component error: ${error?.toString() || 'Unknown error'}`, errorInfo);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error?.toString() || 'Unknown error',\n errorInfo,\n source: 'react'\n }\n });\n }\n\n /**\n * Handle onSaveUserSettings from components.\n *\n * This implements the SavedUserSettings pattern: the component owns its single\n * settings object and hands us the full latest copy whenever it changes. We\n * (1) **merge** the payload over our in-memory snapshot so any future re-render\n * passes the latest values, (2) persist the merged snapshot per-user via\n * UserInfoEngine (debounced, auto-scoped) unless the host opted out, and\n * (3) still bubble the event up for any parent container that wants to observe\n * changes — carrying the merged snapshot, so observers and storage agree.\n *\n * Merge (not replace) makes the host resilient to a component passing only the\n * changed keys, and to the stale-prop case: we deliberately never re-render on\n * save, so the `savedUserSettings` prop a component spreads is frozen at mount\n * and would otherwise lose earlier same-session changes. Removing a key\n * requires explicit intent — set it to `null` (see applyUserSettingsUpdate).\n */\n private handleSaveUserSettings(newSettings: Record<string, any>) {\n // Keep our snapshot current WITHOUT going through the setter (which would\n // re-render). The component already holds the correct state — it's the one\n // that told us about the change — so re-rendering would only cause flicker.\n this._savedUserSettings = applyUserSettingsUpdate(this._savedUserSettings, newSettings);\n\n // Durably persist the latest settings for this user, scoped to this component.\n this.persistUserSettings(this._savedUserSettings);\n\n // Bubble the event up to parent containers (back-compat; no consumer required).\n this.userSettingsChanged.emit({\n settings: this._savedUserSettings,\n componentName: this.component?.name,\n timestamp: new Date()\n });\n }\n\n /**\n * Resolve the durable storage key for this component's per-user settings, or\n * null when persistence is disabled or no stable scope can be derived.\n */\n private getUserStateStorageKey(): string | null {\n if (!this.PersistUserSettings) {\n return null;\n }\n const scope = resolveUserStateScope(\n this.UserStateScope,\n this._component?.namespace,\n this._component?.name\n );\n return userStateStorageKey(scope);\n }\n\n /**\n * Seed `savedUserSettings` from durable per-user storage (UserInfoEngine),\n * merging stored values over any host-provided defaults (stored wins). Best\n * effort — any failure leaves the host-provided / empty settings in place.\n */\n private async seedUserSettingsFromStore(): Promise<void> {\n const key = this.getUserStateStorageKey();\n if (!key) {\n return;\n }\n try {\n const provider = this.ProviderToUse;\n const user = provider?.CurrentUser;\n if (!user) {\n return; // No user context — cannot scope settings to a user.\n }\n // Idempotent: a no-op when the engine is already loaded for this user.\n await UserInfoEngine.Instance.Config(false, user, provider);\n const stored = parseStoredUserSettings(UserInfoEngine.Instance.GetSetting(key));\n this._savedUserSettings = mergeUserSettings(this._savedUserSettings, stored);\n } catch (error) {\n if (this.enableLogging) {\n console.warn('MJReactComponent: failed to seed user settings from store', error);\n }\n }\n }\n\n /**\n * Persist the component's settings object for the current user (debounced,\n * cross-device). Best effort — failures are logged when logging is enabled and\n * never surfaced to the component.\n */\n private persistUserSettings(settings: Record<string, any> | string): void {\n const key = this.getUserStateStorageKey();\n if (!key) {\n return;\n }\n try {\n const provider = this.ProviderToUse;\n const user = provider?.CurrentUser;\n if (!user) {\n return;\n }\n // The component normally hands us an object, but guard against a caller\n // that already serialized it — double-stringifying would store a quoted\n // JSON string the seed path could not parse back into settings.\n const serialized = typeof settings === 'string' ? settings : JSON.stringify(settings);\n UserInfoEngine.Instance.SetSettingDebounced(key, serialized, user);\n } catch (error) {\n if (this.enableLogging) {\n console.warn('MJReactComponent: failed to persist user settings', error);\n }\n }\n }\n\n // =================================================================\n // Automatic Data Capture — intercept RunView/RunQuery for fallback\n // =================================================================\n\n /**\n * Wraps a ComponentUtilities object so that every RunView / RunViews / RunQuery\n * call transparently stores the result in `this.capturedData`. The wrapped\n * object is referentially distinct from the original and is safe to pass to\n * multiple renders (results accumulate until the component resets).\n */\n private wrapUtilitiesWithCapture(original: ComponentUtilities): ComponentUtilities {\n const self = this;\n const wrappedRv: SimpleRunView = {\n RunView: async (params: RunViewParams, contextUser?: unknown) => {\n const result = await original.rv.RunView(params, contextUser as undefined);\n if (result?.Success) {\n self.capturedData.push({\n sourceName: String(params.EntityName ?? params.ExtraFilter ?? 'Unknown'),\n sourceType: 'view',\n params: params as unknown as Record<string, unknown>,\n rows: result.Results ?? [],\n totalRows: result.TotalRowCount ?? result.Results?.length ?? 0,\n fetchedAt: new Date()\n });\n }\n return result;\n },\n RunViews: async (params: RunViewParams[], contextUser?: unknown) => {\n const results = await original.rv.RunViews(params, contextUser as undefined);\n results.forEach((result: RunViewResult, i: number) => {\n if (result?.Success) {\n self.capturedData.push({\n sourceName: String(params[i]?.EntityName ?? `View ${i}`),\n sourceType: 'view',\n params: params[i] as unknown as Record<string, unknown>,\n rows: result.Results ?? [],\n totalRows: result.TotalRowCount ?? result.Results?.length ?? 0,\n fetchedAt: new Date()\n });\n }\n });\n return results;\n }\n };\n\n const wrappedRq: SimpleRunQuery = {\n RunQuery: async (params: RunQueryParams, contextUser?: unknown) => {\n const result = await original.rq.RunQuery(params, contextUser as undefined);\n if (result?.Success) {\n self.capturedData.push({\n sourceName: String(params.QueryID ?? params.QueryName ?? 'Query'),\n sourceType: 'query',\n params: params as unknown as Record<string, unknown>,\n rows: (result.Results ?? []) as Record<string, unknown>[],\n totalRows: result.TotalRowCount ?? result.Results?.length ?? 0,\n fetchedAt: new Date()\n });\n }\n return result;\n }\n };\n\n return {\n ...original,\n rv: wrappedRv,\n rq: wrappedRq\n };\n }\n\n /**\n * Builds a DataSnapshot from captured RunView/RunQuery results.\n * Returns null if no data was captured.\n */\n private BuildCapturedDataSnapshot(): DataSnapshot | null {\n if (this.capturedData.length === 0) return null;\n\n const tables: DataTable[] = this.capturedData.map((captured, idx) => {\n const table = new DataTable();\n table.name = captured.sourceName || `Table ${idx + 1}`;\n table.source = captured.sourceType;\n table.rows = captured.rows;\n // Infer columns from the first row's keys\n if (captured.rows.length > 0) {\n const firstRow = captured.rows[0];\n table.columns = Object.keys(firstRow).map(key => {\n const col = new MJColumnDescriptor(key);\n col.displayName = key;\n const val = firstRow[key];\n if (typeof val === 'number') col.sqlBaseType = 'float';\n else if (val instanceof Date) col.sqlBaseType = 'datetime';\n else col.sqlBaseType = 'nvarchar';\n return col;\n });\n }\n table.metadata = {\n entityName: captured.sourceType === 'view' ? captured.sourceName : undefined,\n rowCount: captured.rows.length,\n totalAvailableRows: captured.totalRows,\n fetchedAt: captured.fetchedAt\n };\n return table;\n });\n\n return DataSnapshot.FromTables(tables, this.component?.title ?? this.component?.name);\n }\n\n /**\n * Clean up resources\n */\n private cleanup() {\n // Clean up all resources managed by resource manager\n resourceManager.cleanupComponent(this.componentId);\n \n // Clean up prop builder subscriptions\n if (this.currentCallbacks) {\n this.currentCallbacks = null;\n }\n \n // Unmount React root using managed unmount\n if (this.reactRootId) {\n // Force stop rendering flags\n this.isRendering = false;\n this.pendingRender = false;\n \n // This will handle waiting for render completion if needed\n reactRootManager.unmountRoot(this.reactRootId);\n this.reactRootId = null;\n }\n\n // Clear references\n this.compiledComponent = null;\n this.isInitialized = false;\n this.capturedData = [];\n\n // Trigger registry cleanup (guard: adapter may not be initialized if\n // React bootstrap failed or was destroyed during retry)\n if (this.adapter.isInitialized()) {\n this.adapter.getRegistry().cleanup();\n }\n }\n\n /**\n * Public method to refresh the component\n * @deprecated Components manage their own state and data now\n */\n refresh() {\n // Check if the component has registered a refresh method\n if (this.compiledComponent?.refresh) {\n this.compiledComponent.refresh();\n } else {\n // Fallback: trigger a re-render if needed\n this.renderComponent();\n }\n }\n\n /**\n * Public method to update state programmatically\n * @param path - State path to update\n * @param value - New value\n * @deprecated Components manage their own state now\n */\n updateState(path: string, value: any) {\n // Just emit the event, don't manage state here\n this.stateChange.emit({ path, value });\n }\n\n // =================================================================\n // Standard Component Methods - Strongly Typed\n // =================================================================\n \n /**\n * Gets the current data state of the component.\n * Tries the component's explicit implementation first, then falls back\n * to a DataSnapshot built from intercepted RunView/RunQuery results.\n */\n getCurrentDataState(): DataSnapshot | undefined {\n const explicit = this.compiledComponent?.getCurrentDataState?.();\n if (explicit && typeof explicit === 'object') return explicit;\n return this.BuildCapturedDataSnapshot() ?? undefined;\n }\n \n /**\n * Validates the current state of the component\n * @returns true if valid, false or validation errors otherwise\n */\n validate(): boolean | { valid: boolean; errors?: string[] } {\n return this.compiledComponent?.validate?.() || true;\n }\n \n /**\n * Checks if the component has unsaved changes\n * @returns true if dirty, false otherwise\n */\n isDirty(): boolean {\n return this.compiledComponent?.isDirty?.() || false;\n }\n \n /**\n * Resets the component to its initial state\n */\n reset(): void {\n this.compiledComponent?.reset?.();\n }\n \n /**\n * Scrolls to a specific element or position within the component\n * @param target - Element selector, element reference, or scroll options\n */\n scrollTo(target: string | HTMLElement | { top?: number; left?: number }): void {\n this.compiledComponent?.scrollTo?.(target);\n }\n \n /**\n * Sets focus to a specific element within the component\n * @param target - Element selector or element reference\n */\n focus(target?: string | HTMLElement): void {\n this.compiledComponent?.focus?.(target);\n }\n \n /**\n * Invokes a custom method on the component\n * @param methodName - Name of the method to invoke\n * @param args - Arguments to pass to the method\n * @returns The result of the method call, or undefined if method doesn't exist\n */\n invokeMethod(methodName: string, ...args: any[]): any {\n return this.compiledComponent?.invokeMethod?.(methodName, ...args);\n }\n \n /**\n * Checks if a method is available on the component\n * @param methodName - Name of the method to check\n * @returns true if the method exists\n */\n hasMethod(methodName: string): boolean {\n return this.compiledComponent?.hasMethod?.(methodName) || false;\n }\n \n /**\n * Print the component content\n * Uses component's print method if available, otherwise uses window.print()\n */\n print(): void {\n if (this.compiledComponent?.print) {\n this.compiledComponent.print();\n } else if (typeof window !== 'undefined' && window.print) {\n window.print();\n }\n }\n\n /**\n * Force clear component registries\n * Used by Component Studio for fresh loads\n * This is a static method that can be called without a component instance\n */\n public static forceClearRegistries(): void {\n // Clear React runtime's component registry service\n ComponentRegistryService.reset();\n\n // Clear any cached hierarchy registrar\n if (typeof window !== 'undefined' && (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__) {\n (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__ = null;\n }\n\n console.log('🧹 All component registries cleared for fresh load');\n }\n\n /**\n * Gets the current data state from the hosted React component.\n * Falls back to a DataSnapshot built from intercepted RunView/RunQuery results\n * when the component does not explicitly implement getCurrentDataState.\n */\n public GetCurrentDataState(): DataSnapshot | undefined {\n return this.getCurrentDataState();\n }\n\n /**\n * Applies a data state snapshot to the hosted React component.\n * Returns true if the snapshot was successfully applied, false if the\n * component does not support setDataState or the operation failed.\n */\n public SetDataState(snapshot: DataSnapshot): boolean {\n return this.compiledComponent?.setDataState?.(snapshot) ?? false;\n }\n\n}"]}
|
|
@@ -228,6 +228,9 @@ export class AngularAdapterService {
|
|
|
228
228
|
this.runtime = undefined;
|
|
229
229
|
this.runtimeContext = undefined;
|
|
230
230
|
}
|
|
231
|
+
// Clear the cached initialization promise so a subsequent initialize()
|
|
232
|
+
// actually runs doInitialize() instead of returning the stale resolved promise.
|
|
233
|
+
this.initializationPromise = undefined;
|
|
231
234
|
}
|
|
232
235
|
/**
|
|
233
236
|
* Get Babel instance for direct use
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"angular-adapter.service.js","sourceRoot":"","sources":["../../../src/lib/services/angular-adapter.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG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AAO,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;YAChC,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;YACzB,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAClC,CAAC;IACH,CAAC;IAED;;;OAGG;IACH,QAAQ;QACN,OAAO,IAAI,CAAC,cAAc,EAAE,SAAS,EAAE,KAAK,IAAK,MAAc,CAAC,KAAK,CAAC;IACxE,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,IAAY,EAAE,QAAiB;QAC1C,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;QACrE,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE;gBACnC,OAAO,EAAE,CAAC,OAAO,CAAC;gBAClB,QAAQ,EAAE,QAAQ,IAAI,eAAe;aACtC,CAAC,CAAC;YACH,OAAO,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;sHA3SU,qBAAqB;uEAArB,qBAAqB,WAArB,qBAAqB,mBADR,MAAM;;iFACnB,qBAAqB;cADjC,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Angular adapter service that bridges the React runtime with Angular.\n * Provides Angular-specific functionality for the platform-agnostic React runtime.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable } from '@angular/core';\nimport {\n ComponentCompiler,\n ComponentRegistry,\n ComponentResolver,\n ComponentManager,\n createReactRuntime,\n CompileOptions,\n RuntimeContext,\n ExternalLibraryConfig,\n LibraryConfiguration,\n LibraryLoader,\n BuildStylesFromTheme\n} from '@memberjunction/react-runtime';\nimport { ScriptLoaderService } from './script-loader.service';\nimport { ComponentStyles } from '@memberjunction/interactive-component-types';\n\n/**\n * Angular-specific adapter for the React runtime.\n * Manages the integration between Angular services and the platform-agnostic React runtime.\n */\n@Injectable({ providedIn: 'root' })\nexport class AngularAdapterService {\n private runtime?: {\n compiler: ComponentCompiler;\n registry: ComponentRegistry;\n resolver: ComponentResolver;\n manager: ComponentManager;\n version: string;\n };\n private runtimeContext?: RuntimeContext;\n private initializationPromise: Promise<void> | undefined;\n\n constructor(private scriptLoader: ScriptLoaderService) {}\n\n /**\n * Eagerly start loading the React runtime in the background.\n * Call this at app startup (e.g., in APP_INITIALIZER or after auth) so that\n * React, ReactDOM, and Babel are already downloaded from CDN by the time the\n * user opens an interactive component artifact.\n *\n * Two-phase approach:\n * 1. Immediately inject `<link rel=\"preload\">` hints so the browser starts\n * downloading the CDN scripts in parallel with other page work.\n * 2. Fire-and-forget `initialize()` which creates `<script>` tags and\n * executes them. If the preload hints already fetched the bytes, the\n * script load is nearly instant (served from HTTP cache).\n *\n * Safe to call multiple times — the underlying initialize() deduplicates.\n * Does not block: returns immediately, initialization continues in background.\n */\n preload(): void {\n // Phase 1: Inject browser preload hints for CDN scripts\n LibraryLoader.preloadCoreScripts();\n\n // Phase 2: Fire-and-forget full initialization (script execution + runtime setup)\n this.initialize().catch(err => {\n console.warn('React runtime preload failed (will retry on demand):', err);\n });\n }\n\n /**\n * Initialize the React runtime with Angular-specific configuration\n * @param config Optional library configuration\n * @param additionalLibraries Optional additional libraries to merge\n * @param options Optional options including debug flag\n * @returns Promise resolving when runtime is ready\n */\n async initialize(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<void> {\n if (this.runtime) {\n return; // Already initialized\n }\n if (this.initializationPromise) {\n return this.initializationPromise; // in progress\n }\n\n // Start initialization and store the promise immediately\n this.initializationPromise = this.doInitialize(config, additionalLibraries, options);\n\n try {\n await this.initializationPromise;\n } catch (error) {\n // Clear the promise on error so it can be retried\n this.initializationPromise = undefined;\n throw error;\n }\n\n return;\n }\n\n private async doInitialize(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<void> {\n // Load React ecosystem with optional additional libraries\n const ecosystem = await this.scriptLoader.loadReactEcosystem(config, additionalLibraries, options);\n \n // Create runtime context\n this.runtimeContext = {\n React: ecosystem.React,\n ReactDOM: ecosystem.ReactDOM,\n libraries: ecosystem.libraries,\n utilities: {\n // Add any Angular-specific utilities here\n }\n };\n\n // Create the React runtime with runtime context for registry support\n this.runtime = createReactRuntime(ecosystem.Babel, {\n compiler: {\n cache: true,\n maxCacheSize: 100,\n debug: options?.debug\n },\n registry: {\n maxComponents: 1000,\n cleanupInterval: 60000,\n useLRU: true,\n enableNamespaces: true,\n debug: options?.debug\n }\n }, this.runtimeContext, options?.debug);\n }\n\n /**\n * Get the component compiler\n * @returns Component compiler instance\n */\n getCompiler(): ComponentCompiler {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.compiler;\n }\n\n /**\n * Get the component registry\n * @returns Component registry instance\n */\n getRegistry(): ComponentRegistry {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry;\n }\n\n /**\n * Get the component resolver\n * @returns Component resolver instance\n */\n getResolver(): ComponentResolver {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.resolver;\n }\n\n /**\n * Get the runtime context\n * @returns Runtime context with React and libraries\n */\n getRuntimeContext(): RuntimeContext {\n if (!this.runtimeContext) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtimeContext;\n }\n\n /**\n * Get the unified component manager\n * @returns Component manager instance\n */\n getComponentManager(): ComponentManager {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.manager;\n }\n\n\n /**\n * Compile a component with Angular-specific defaults\n * @param options - Compilation options\n * @returns Promise resolving to compilation result\n */\n async compileComponent(options: CompileOptions) {\n // Validate options before initialization\n if (!options) {\n throw new Error(\n 'Angular adapter error: No compilation options provided.\\n' +\n 'This usually means the component spec is null or undefined.\\n' +\n 'Please check that:\\n' +\n '1. Your component data is loaded properly\\n' +\n '2. The component spec has \"name\" and \"code\" properties\\n' +\n '3. The component input is not undefined'\n );\n }\n\n if (!options.componentName || options.componentName.trim() === '') {\n throw new Error(\n 'Angular adapter error: Component name is missing or empty.\\n' +\n `Received options: ${JSON.stringify(options, null, 2)}\\n` +\n 'Make sure your component spec includes a \"name\" property.'\n );\n }\n\n if (!options.componentCode || options.componentCode.trim() === '') {\n throw new Error(\n `Angular adapter error: Component code is missing or empty for component \"${options.componentName}\".\\n` +\n 'Make sure your component spec includes a \"code\" property with the React component source.'\n );\n }\n\n await this.initialize();\n \n // Apply default styles if not provided — bridge the host's live MJ theme\n // (--mj-* tokens) so compiled components match the active theme, including\n // dark mode. Falls back to SetupStyles() defaults when no themed DOM exists.\n const optionsWithDefaults = {\n ...options,\n styles: options.styles || BuildStylesFromTheme()\n };\n\n return this.runtime!.compiler.compile(optionsWithDefaults);\n }\n\n /**\n * Register a component in the registry\n * @param name - Component name\n * @param component - Compiled component\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component metadata\n */\n registerComponent(\n name: string,\n component: any,\n namespace: string = 'Global',\n version: string = 'v1'\n ) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.register(name, component, namespace, version);\n }\n\n /**\n * Get a component from the registry\n * @param name - Component name\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component if found\n */\n getComponent(name: string, namespace: string = 'Global', version?: string) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.get(name, namespace, version);\n }\n\n /**\n * Check if runtime is initialized\n * @returns true if initialized\n */\n isInitialized(): boolean {\n return !!this.runtime && !!this.runtimeContext;\n }\n\n /**\n * Get runtime version\n * @returns Runtime version string\n */\n getVersion(): string {\n return this.runtime?.version || 'unknown';\n }\n\n /**\n * Clean up resources\n */\n destroy(): void {\n if (this.runtime) {\n this.runtime.registry.destroy();\n this.runtime = undefined;\n this.runtimeContext = undefined;\n }\n }\n\n /**\n * Get Babel instance for direct use\n * @returns Babel instance\n */\n getBabel(): any {\n return this.runtimeContext?.libraries?.Babel || (window as any).Babel;\n }\n\n /**\n * Transpile JSX code directly\n * @param code - JSX code to transpile\n * @param filename - Optional filename for better error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename?: string): string {\n const babel = this.getBabel();\n if (!babel) {\n throw new Error('Babel not loaded. Initialize the runtime first.');\n }\n\n try {\n const result = babel.transform(code, {\n presets: ['react'],\n filename: filename || 'component.jsx'\n });\n return result.code;\n } catch (error: any) {\n throw new Error(`Failed to transpile JSX: ${error.message}`);\n }\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"angular-adapter.service.js","sourceRoot":"","sources":["../../../src/lib/services/angular-adapter.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAKL,kBAAkB,EAKlB,aAAa,EACb,oBAAoB,EACrB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;;;AAG9D;;;GAGG;AAEH,MAAM,OAAO,qBAAqB;IAWhC,YAAoB,YAAiC;QAAjC,iBAAY,GAAZ,YAAY,CAAqB;IAAG,CAAC;IAEzD;;;;;;;;;;;;;;;OAeG;IACH,OAAO;QACL,wDAAwD;QACxD,aAAa,CAAC,kBAAkB,EAAE,CAAC;QAEnC,kFAAkF;QAClF,IAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;YAC5B,OAAO,CAAC,IAAI,CAAC,sDAAsD,EAAE,G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iDAAiD,CAAC,CAAC;QACrE,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE;gBACnC,OAAO,EAAE,CAAC,OAAO,CAAC;gBAClB,QAAQ,EAAE,QAAQ,IAAI,eAAe;aACtC,CAAC,CAAC;YACH,OAAO,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;sHA9SU,qBAAqB;uEAArB,qBAAqB,WAArB,qBAAqB,mBADR,MAAM;;iFACnB,qBAAqB;cADjC,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Angular adapter service that bridges the React runtime with Angular.\n * Provides Angular-specific functionality for the platform-agnostic React runtime.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable } from '@angular/core';\nimport {\n ComponentCompiler,\n ComponentRegistry,\n ComponentResolver,\n ComponentManager,\n createReactRuntime,\n CompileOptions,\n RuntimeContext,\n ExternalLibraryConfig,\n LibraryConfiguration,\n LibraryLoader,\n BuildStylesFromTheme\n} from '@memberjunction/react-runtime';\nimport { ScriptLoaderService } from './script-loader.service';\nimport { ComponentStyles } from '@memberjunction/interactive-component-types';\n\n/**\n * Angular-specific adapter for the React runtime.\n * Manages the integration between Angular services and the platform-agnostic React runtime.\n */\n@Injectable({ providedIn: 'root' })\nexport class AngularAdapterService {\n private runtime?: {\n compiler: ComponentCompiler;\n registry: ComponentRegistry;\n resolver: ComponentResolver;\n manager: ComponentManager;\n version: string;\n };\n private runtimeContext?: RuntimeContext;\n private initializationPromise: Promise<void> | undefined;\n\n constructor(private scriptLoader: ScriptLoaderService) {}\n\n /**\n * Eagerly start loading the React runtime in the background.\n * Call this at app startup (e.g., in APP_INITIALIZER or after auth) so that\n * React, ReactDOM, and Babel are already downloaded from CDN by the time the\n * user opens an interactive component artifact.\n *\n * Two-phase approach:\n * 1. Immediately inject `<link rel=\"preload\">` hints so the browser starts\n * downloading the CDN scripts in parallel with other page work.\n * 2. Fire-and-forget `initialize()` which creates `<script>` tags and\n * executes them. If the preload hints already fetched the bytes, the\n * script load is nearly instant (served from HTTP cache).\n *\n * Safe to call multiple times — the underlying initialize() deduplicates.\n * Does not block: returns immediately, initialization continues in background.\n */\n preload(): void {\n // Phase 1: Inject browser preload hints for CDN scripts\n LibraryLoader.preloadCoreScripts();\n\n // Phase 2: Fire-and-forget full initialization (script execution + runtime setup)\n this.initialize().catch(err => {\n console.warn('React runtime preload failed (will retry on demand):', err);\n });\n }\n\n /**\n * Initialize the React runtime with Angular-specific configuration\n * @param config Optional library configuration\n * @param additionalLibraries Optional additional libraries to merge\n * @param options Optional options including debug flag\n * @returns Promise resolving when runtime is ready\n */\n async initialize(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<void> {\n if (this.runtime) {\n return; // Already initialized\n }\n if (this.initializationPromise) {\n return this.initializationPromise; // in progress\n }\n\n // Start initialization and store the promise immediately\n this.initializationPromise = this.doInitialize(config, additionalLibraries, options);\n\n try {\n await this.initializationPromise;\n } catch (error) {\n // Clear the promise on error so it can be retried\n this.initializationPromise = undefined;\n throw error;\n }\n\n return;\n }\n\n private async doInitialize(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<void> {\n // Load React ecosystem with optional additional libraries\n const ecosystem = await this.scriptLoader.loadReactEcosystem(config, additionalLibraries, options);\n \n // Create runtime context\n this.runtimeContext = {\n React: ecosystem.React,\n ReactDOM: ecosystem.ReactDOM,\n libraries: ecosystem.libraries,\n utilities: {\n // Add any Angular-specific utilities here\n }\n };\n\n // Create the React runtime with runtime context for registry support\n this.runtime = createReactRuntime(ecosystem.Babel, {\n compiler: {\n cache: true,\n maxCacheSize: 100,\n debug: options?.debug\n },\n registry: {\n maxComponents: 1000,\n cleanupInterval: 60000,\n useLRU: true,\n enableNamespaces: true,\n debug: options?.debug\n }\n }, this.runtimeContext, options?.debug);\n }\n\n /**\n * Get the component compiler\n * @returns Component compiler instance\n */\n getCompiler(): ComponentCompiler {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.compiler;\n }\n\n /**\n * Get the component registry\n * @returns Component registry instance\n */\n getRegistry(): ComponentRegistry {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry;\n }\n\n /**\n * Get the component resolver\n * @returns Component resolver instance\n */\n getResolver(): ComponentResolver {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.resolver;\n }\n\n /**\n * Get the runtime context\n * @returns Runtime context with React and libraries\n */\n getRuntimeContext(): RuntimeContext {\n if (!this.runtimeContext) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtimeContext;\n }\n\n /**\n * Get the unified component manager\n * @returns Component manager instance\n */\n getComponentManager(): ComponentManager {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.manager;\n }\n\n\n /**\n * Compile a component with Angular-specific defaults\n * @param options - Compilation options\n * @returns Promise resolving to compilation result\n */\n async compileComponent(options: CompileOptions) {\n // Validate options before initialization\n if (!options) {\n throw new Error(\n 'Angular adapter error: No compilation options provided.\\n' +\n 'This usually means the component spec is null or undefined.\\n' +\n 'Please check that:\\n' +\n '1. Your component data is loaded properly\\n' +\n '2. The component spec has \"name\" and \"code\" properties\\n' +\n '3. The component input is not undefined'\n );\n }\n\n if (!options.componentName || options.componentName.trim() === '') {\n throw new Error(\n 'Angular adapter error: Component name is missing or empty.\\n' +\n `Received options: ${JSON.stringify(options, null, 2)}\\n` +\n 'Make sure your component spec includes a \"name\" property.'\n );\n }\n\n if (!options.componentCode || options.componentCode.trim() === '') {\n throw new Error(\n `Angular adapter error: Component code is missing or empty for component \"${options.componentName}\".\\n` +\n 'Make sure your component spec includes a \"code\" property with the React component source.'\n );\n }\n\n await this.initialize();\n \n // Apply default styles if not provided — bridge the host's live MJ theme\n // (--mj-* tokens) so compiled components match the active theme, including\n // dark mode. Falls back to SetupStyles() defaults when no themed DOM exists.\n const optionsWithDefaults = {\n ...options,\n styles: options.styles || BuildStylesFromTheme()\n };\n\n return this.runtime!.compiler.compile(optionsWithDefaults);\n }\n\n /**\n * Register a component in the registry\n * @param name - Component name\n * @param component - Compiled component\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component metadata\n */\n registerComponent(\n name: string,\n component: any,\n namespace: string = 'Global',\n version: string = 'v1'\n ) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.register(name, component, namespace, version);\n }\n\n /**\n * Get a component from the registry\n * @param name - Component name\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component if found\n */\n getComponent(name: string, namespace: string = 'Global', version?: string) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.get(name, namespace, version);\n }\n\n /**\n * Check if runtime is initialized\n * @returns true if initialized\n */\n isInitialized(): boolean {\n return !!this.runtime && !!this.runtimeContext;\n }\n\n /**\n * Get runtime version\n * @returns Runtime version string\n */\n getVersion(): string {\n return this.runtime?.version || 'unknown';\n }\n\n /**\n * Clean up resources\n */\n destroy(): void {\n if (this.runtime) {\n this.runtime.registry.destroy();\n this.runtime = undefined;\n this.runtimeContext = undefined;\n }\n // Clear the cached initialization promise so a subsequent initialize()\n // actually runs doInitialize() instead of returning the stale resolved promise.\n this.initializationPromise = undefined;\n }\n\n /**\n * Get Babel instance for direct use\n * @returns Babel instance\n */\n getBabel(): any {\n return this.runtimeContext?.libraries?.Babel || (window as any).Babel;\n }\n\n /**\n * Transpile JSX code directly\n * @param code - JSX code to transpile\n * @param filename - Optional filename for better error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename?: string): string {\n const babel = this.getBabel();\n if (!babel) {\n throw new Error('Babel not loaded. Initialize the runtime first.');\n }\n\n try {\n const result = babel.transform(code, {\n presets: ['react'],\n filename: filename || 'component.jsx'\n });\n return result.code;\n } catch (error: any) {\n throw new Error(`Failed to transpile JSX: ${error.message}`);\n }\n }\n}"]}
|
|
@@ -65,6 +65,13 @@ export class ReactBridgeService {
|
|
|
65
65
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
66
66
|
}
|
|
67
67
|
await this.adapter.initialize(undefined, undefined, { debug: this.debug });
|
|
68
|
+
// Validate that ReactDOM.createRoot is actually callable.
|
|
69
|
+
// If CDN scripts loaded in the wrong order (ReactDOM before React),
|
|
70
|
+
// the ReactDOM object exists but createRoot is broken.
|
|
71
|
+
const ctx = this.adapter.getRuntimeContext();
|
|
72
|
+
if (!ctx.ReactDOM?.createRoot || typeof ctx.ReactDOM.createRoot !== 'function') {
|
|
73
|
+
throw new Error('ReactDOM loaded but createRoot is not available — possible script execution order issue');
|
|
74
|
+
}
|
|
68
75
|
// Register Angular-specific runtime hooks for library compatibility
|
|
69
76
|
reactRootManager.RegisterHook(createAntdDropdownPositionHook());
|
|
70
77
|
if (this.debug) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-bridge.service.js","sourceRoot":"","sources":["../../../src/lib/services/react-bridge.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAkB,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CA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CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACnD,CAAC;IAED;;OAEG;IACK,OAAO;QACb,kCAAkC;QAClC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACnC,IAAI,CAAC;gBACH,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;YACvD,CAAC;QACH,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QAExB,wBAAwB;QACxB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,CAAC,uBAAuB,GAAG,KAAK,CAAC;QAErC,gFAAgF;QAChF,gBAAgB,CAAC,OAAO,EAAE,CAAC;QAE3B,mBAAmB;QACnB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC;IACtC,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;IAC9B,CAAC;mHAxRU,kBAAkB;uEAAlB,kBAAkB,WAAlB,kBAAkB,mBADL,MAAM;;iFACnB,kBAAkB;cAD9B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service to manage React and ReactDOM instances with proper lifecycle.\n * Bridges Angular components with React rendering capabilities.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\nimport { filter } from 'rxjs/operators';\nimport { AngularAdapterService } from './angular-adapter.service';\nimport { RuntimeContext, reactRootManager } from '@memberjunction/react-runtime';\nimport { ReactDebugConfig } from '../config/react-debug.config';\nimport { createAntdDropdownPositionHook } from '../hooks/antd-dropdown-position-hook';\n\n/**\n * Service to manage React and ReactDOM instances with proper lifecycle.\n * Provides methods for creating and managing React roots in Angular applications.\n */\n@Injectable({ providedIn: 'root' })\nexport class ReactBridgeService implements OnDestroy {\n private reactRoots = new Set<any>();\n\n // Track React readiness state\n private reactReadySubject = new BehaviorSubject<boolean>(false);\n public reactReady$ = this.reactReadySubject.asObservable();\n\n // Track if this is the first component trying to use React\n private firstComponentAttempted = false;\n private maxWaitTime = 5000; // Maximum 5 seconds wait time for createRoot poll\n private checkInterval = 200; // Check every 200ms\n private maxBootstrapRetries = 2; // Retry bootstrap up to 2 additional times\n private retryBaseDelay = 2000; // Base delay between bootstrap retries (ms)\n\n // Debug flag from project configuration\n public debug: boolean = ReactDebugConfig.getDebugMode();\n\n // The current bootstrap attempt — shared between constructor and getReactContext()\n private bootstrapPromise: Promise<void> | null = null;\n\n constructor(private adapter: AngularAdapterService) {\n // Bootstrap React immediately on service initialization\n this.bootstrapWithRetries();\n }\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Bootstrap React from CDN with automatic retries.\n * Deduplicates: concurrent callers share the same in-flight promise.\n * On failure, clears the promise so the next call can retry.\n */\n private bootstrapWithRetries(): Promise<void> {\n if (!this.bootstrapPromise) {\n this.bootstrapPromise = this.doBootstrapWithRetries();\n }\n return this.bootstrapPromise;\n }\n\n /**\n * Attempt to load the React ecosystem from CDN, retrying with exponential\n * backoff if the CDN is unreachable or returns an error.\n */\n private async doBootstrapWithRetries(): Promise<void> {\n console.log(`ReactBridgeService: Initializing React with debug mode = ${this.debug} (from ReactDebugConfig)`);\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= this.maxBootstrapRetries; attempt++) {\n try {\n if (attempt > 0) {\n const delay = this.retryBaseDelay * Math.pow(2, attempt - 1);\n console.warn(\n `React CDN bootstrap attempt ${attempt + 1} of ${this.maxBootstrapRetries + 1} — retrying in ${delay}ms...`\n );\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n\n await this.adapter.initialize(undefined, undefined, { debug: this.debug });\n\n // Register Angular-specific runtime hooks for library compatibility\n reactRootManager.RegisterHook(createAntdDropdownPositionHook());\n\n if (this.debug) {\n console.log('React ecosystem pre-loaded successfully with DEVELOPMENT builds (detailed error messages)');\n } else {\n console.log('React ecosystem pre-loaded successfully with PRODUCTION builds (minified)');\n }\n return; // Success\n } catch (error) {\n lastError = error;\n console.error(`React bootstrap attempt ${attempt + 1} failed:`, error);\n }\n }\n\n // All attempts exhausted — clear promise so future calls can retry\n this.bootstrapPromise = null;\n throw lastError;\n }\n\n /**\n * Wait for React to be ready, with special handling for first component.\n * If bootstrap succeeded but createRoot isn't usable (stale browser cache),\n * forces a re-bootstrap and retries.\n */\n async waitForReactReady(): Promise<void> {\n // If already ready, return immediately\n if (this.reactReadySubject.value) {\n return;\n }\n\n // Check if this is the first component attempting to use React\n const isFirstComponent = !this.firstComponentAttempted;\n this.firstComponentAttempted = true;\n\n if (isFirstComponent) {\n await this.pollForReactReadyWithRetries();\n } else {\n // Subsequent components wait for the ready signal\n await firstValueFrom(this.reactReady$.pipe(filter(ready => ready)));\n }\n }\n\n /**\n * Poll for ReactDOM.createRoot availability. If the poll window expires\n * (bootstrap succeeded but createRoot is broken, e.g. stale cache),\n * force a fresh re-bootstrap and retry.\n */\n private async pollForReactReadyWithRetries(): Promise<void> {\n const overallStart = Date.now();\n\n for (let attempt = 0; attempt <= this.maxBootstrapRetries; attempt++) {\n if (attempt > 0) {\n console.warn(\n `React createRoot check failed (attempt ${attempt}) — forcing fresh CDN re-bootstrap...`\n );\n // Clear the cached bootstrap promise so doBootstrapWithRetries runs fresh\n this.bootstrapPromise = null;\n this.adapter.destroy();\n try {\n await this.bootstrapWithRetries();\n } catch {\n // Bootstrap itself failed — continue to next poll attempt\n continue;\n }\n }\n\n const ready = await this.pollForCreateRoot();\n if (ready) {\n this.reactReadySubject.next(true);\n if (this.debug) {\n console.log(`React is fully ready after ${Date.now() - overallStart}ms (attempt ${attempt + 1})`);\n }\n return;\n }\n }\n\n // All attempts exhausted\n const totalTime = Date.now() - overallStart;\n console.error(\n `React readiness test failed after ${this.maxBootstrapRetries + 1} attempts (${totalTime}ms total)`\n );\n this.firstComponentAttempted = false;\n throw new Error(\n `ReactDOM.createRoot not available after ${this.maxBootstrapRetries + 1} attempts (${totalTime}ms). ` +\n `Try a hard refresh (Ctrl+Shift+R) to clear the browser cache.`\n );\n }\n\n /**\n * Poll for ReactDOM.createRoot for up to maxWaitTime ms.\n * @returns true if createRoot became available, false if the poll window expired.\n */\n private async pollForCreateRoot(): Promise<boolean> {\n const startTime = Date.now();\n\n while (Date.now() - startTime < this.maxWaitTime) {\n try {\n const testDiv = document.createElement('div');\n const context = this.adapter.getRuntimeContext();\n\n if (context.ReactDOM?.createRoot) {\n const testRoot = context.ReactDOM.createRoot(testDiv);\n if (testRoot) {\n testRoot.unmount();\n return true;\n }\n }\n } catch {\n // Not ready yet, continue checking\n }\n\n await new Promise(resolve => setTimeout(resolve, this.checkInterval));\n }\n\n return false;\n }\n\n /**\n * Get the current React context if loaded.\n * Awaits the bootstrap (with retries) rather than calling adapter.initialize() independently.\n * @returns React context with React, ReactDOM, Babel, and libraries\n */\n async getReactContext(): Promise<RuntimeContext> {\n await this.bootstrapWithRetries();\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Get the current React context synchronously\n * @returns React context or null if not loaded\n */\n getCurrentContext(): RuntimeContext | null {\n if (!this.adapter.isInitialized()) {\n return null;\n }\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Create a React root for rendering\n * @param container - DOM element to render into\n * @returns React root instance\n */\n createRoot(container: HTMLElement): any {\n const context = this.getCurrentContext();\n if (!context?.ReactDOM?.createRoot) {\n throw new Error('ReactDOM.createRoot not available');\n }\n\n const root = context.ReactDOM.createRoot(container);\n this.reactRoots.add(root);\n return root;\n }\n\n /**\n * Unmount and clean up a React root\n * @param root - React root to unmount\n */\n unmountRoot(root: any): void {\n if (root && typeof root.unmount === 'function') {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.delete(root);\n }\n\n /**\n * Transpile JSX code to JavaScript\n * @param code - JSX code to transpile\n * @param filename - Optional filename for error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename: string): string {\n return this.adapter.transpileJSX(code, filename);\n }\n\n /**\n * Clean up all React roots and reset context\n */\n private cleanup(): void {\n // Unmount all tracked React roots\n for (const root of this.reactRoots) {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.clear();\n \n // Reset readiness state\n this.reactReadySubject.next(false);\n this.firstComponentAttempted = false;\n\n // Clean up runtime hooks (disconnects observers, removes injected styles, etc.)\n reactRootManager.cleanup();\n\n // Clean up adapter\n this.adapter.destroy();\n }\n\n /**\n * Check if React is currently ready\n * @returns true if React is ready\n */\n isReady(): boolean {\n return this.reactReadySubject.value;\n }\n\n /**\n * Get the number of active React roots\n * @returns Number of active roots\n */\n getActiveRootsCount(): number {\n return this.reactRoots.size;\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"react-bridge.service.js","sourceRoot":"","sources":["../../../src/lib/services/react-bridge.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAkB,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;;;AAEtF;;;GAGG;AAEH,MAAM,OAAO,kBA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AI,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;YACvD,CAAC;QACH,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,IAAY,EAAE,QAAgB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACnD,CAAC;IAED;;OAEG;IACK,OAAO;QACb,kCAAkC;QAClC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACnC,IAAI,CAAC;gBACH,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;YACvD,CAAC;QACH,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QAExB,wBAAwB;QACxB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,CAAC,uBAAuB,GAAG,KAAK,CAAC;QAErC,gFAAgF;QAChF,gBAAgB,CAAC,OAAO,EAAE,CAAC;QAE3B,mBAAmB;QACnB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC;IACtC,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;IAC9B,CAAC;mHAhSU,kBAAkB;uEAAlB,kBAAkB,WAAlB,kBAAkB,mBADL,MAAM;;iFACnB,kBAAkB;cAD9B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service to manage React and ReactDOM instances with proper lifecycle.\n * Bridges Angular components with React rendering capabilities.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\nimport { filter } from 'rxjs/operators';\nimport { AngularAdapterService } from './angular-adapter.service';\nimport { RuntimeContext, reactRootManager } from '@memberjunction/react-runtime';\nimport { ReactDebugConfig } from '../config/react-debug.config';\nimport { createAntdDropdownPositionHook } from '../hooks/antd-dropdown-position-hook';\n\n/**\n * Service to manage React and ReactDOM instances with proper lifecycle.\n * Provides methods for creating and managing React roots in Angular applications.\n */\n@Injectable({ providedIn: 'root' })\nexport class ReactBridgeService implements OnDestroy {\n private reactRoots = new Set<any>();\n\n // Track React readiness state\n private reactReadySubject = new BehaviorSubject<boolean>(false);\n public reactReady$ = this.reactReadySubject.asObservable();\n\n // Track if this is the first component trying to use React\n private firstComponentAttempted = false;\n private maxWaitTime = 5000; // Maximum 5 seconds wait time for createRoot poll\n private checkInterval = 200; // Check every 200ms\n private maxBootstrapRetries = 2; // Retry bootstrap up to 2 additional times\n private retryBaseDelay = 2000; // Base delay between bootstrap retries (ms)\n\n // Debug flag from project configuration\n public debug: boolean = ReactDebugConfig.getDebugMode();\n\n // The current bootstrap attempt — shared between constructor and getReactContext()\n private bootstrapPromise: Promise<void> | null = null;\n\n constructor(private adapter: AngularAdapterService) {\n // Bootstrap React immediately on service initialization\n this.bootstrapWithRetries();\n }\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Bootstrap React from CDN with automatic retries.\n * Deduplicates: concurrent callers share the same in-flight promise.\n * On failure, clears the promise so the next call can retry.\n */\n private bootstrapWithRetries(): Promise<void> {\n if (!this.bootstrapPromise) {\n this.bootstrapPromise = this.doBootstrapWithRetries();\n }\n return this.bootstrapPromise;\n }\n\n /**\n * Attempt to load the React ecosystem from CDN, retrying with exponential\n * backoff if the CDN is unreachable or returns an error.\n */\n private async doBootstrapWithRetries(): Promise<void> {\n console.log(`ReactBridgeService: Initializing React with debug mode = ${this.debug} (from ReactDebugConfig)`);\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= this.maxBootstrapRetries; attempt++) {\n try {\n if (attempt > 0) {\n const delay = this.retryBaseDelay * Math.pow(2, attempt - 1);\n console.warn(\n `React CDN bootstrap attempt ${attempt + 1} of ${this.maxBootstrapRetries + 1} — retrying in ${delay}ms...`\n );\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n\n await this.adapter.initialize(undefined, undefined, { debug: this.debug });\n\n // Validate that ReactDOM.createRoot is actually callable.\n // If CDN scripts loaded in the wrong order (ReactDOM before React),\n // the ReactDOM object exists but createRoot is broken.\n const ctx = this.adapter.getRuntimeContext();\n if (!ctx.ReactDOM?.createRoot || typeof ctx.ReactDOM.createRoot !== 'function') {\n throw new Error('ReactDOM loaded but createRoot is not available — possible script execution order issue');\n }\n\n // Register Angular-specific runtime hooks for library compatibility\n reactRootManager.RegisterHook(createAntdDropdownPositionHook());\n\n if (this.debug) {\n console.log('React ecosystem pre-loaded successfully with DEVELOPMENT builds (detailed error messages)');\n } else {\n console.log('React ecosystem pre-loaded successfully with PRODUCTION builds (minified)');\n }\n return; // Success\n } catch (error) {\n lastError = error;\n console.error(`React bootstrap attempt ${attempt + 1} failed:`, error);\n }\n }\n\n // All attempts exhausted — clear promise so future calls can retry\n this.bootstrapPromise = null;\n throw lastError;\n }\n\n /**\n * Wait for React to be ready, with special handling for first component.\n * If bootstrap succeeded but createRoot isn't usable (stale browser cache),\n * forces a re-bootstrap and retries.\n */\n async waitForReactReady(): Promise<void> {\n // If already ready, return immediately\n if (this.reactReadySubject.value) {\n return;\n }\n\n // Check if this is the first component attempting to use React\n const isFirstComponent = !this.firstComponentAttempted;\n this.firstComponentAttempted = true;\n\n if (isFirstComponent) {\n await this.pollForReactReadyWithRetries();\n } else {\n // Subsequent components wait for the ready signal\n await firstValueFrom(this.reactReady$.pipe(filter(ready => ready)));\n }\n }\n\n /**\n * Poll for ReactDOM.createRoot availability. If the poll window expires\n * (bootstrap succeeded but createRoot is broken, e.g. stale cache),\n * force a fresh re-bootstrap and retry.\n */\n private async pollForReactReadyWithRetries(): Promise<void> {\n const overallStart = Date.now();\n\n for (let attempt = 0; attempt <= this.maxBootstrapRetries; attempt++) {\n if (attempt > 0) {\n console.warn(\n `React createRoot check failed (attempt ${attempt}) — forcing fresh CDN re-bootstrap...`\n );\n // Clear the cached bootstrap promise so doBootstrapWithRetries runs fresh\n this.bootstrapPromise = null;\n this.adapter.destroy();\n try {\n await this.bootstrapWithRetries();\n } catch {\n // Bootstrap itself failed — continue to next poll attempt\n continue;\n }\n }\n\n const ready = await this.pollForCreateRoot();\n if (ready) {\n this.reactReadySubject.next(true);\n if (this.debug) {\n console.log(`React is fully ready after ${Date.now() - overallStart}ms (attempt ${attempt + 1})`);\n }\n return;\n }\n }\n\n // All attempts exhausted\n const totalTime = Date.now() - overallStart;\n console.error(\n `React readiness test failed after ${this.maxBootstrapRetries + 1} attempts (${totalTime}ms total)`\n );\n this.firstComponentAttempted = false;\n throw new Error(\n `ReactDOM.createRoot not available after ${this.maxBootstrapRetries + 1} attempts (${totalTime}ms). ` +\n `Try a hard refresh (Ctrl+Shift+R) to clear the browser cache.`\n );\n }\n\n /**\n * Poll for ReactDOM.createRoot for up to maxWaitTime ms.\n * @returns true if createRoot became available, false if the poll window expired.\n */\n private async pollForCreateRoot(): Promise<boolean> {\n const startTime = Date.now();\n\n while (Date.now() - startTime < this.maxWaitTime) {\n try {\n const testDiv = document.createElement('div');\n const context = this.adapter.getRuntimeContext();\n\n if (context.ReactDOM?.createRoot) {\n const testRoot = context.ReactDOM.createRoot(testDiv);\n if (testRoot) {\n testRoot.unmount();\n return true;\n }\n }\n } catch {\n // Not ready yet, continue checking\n }\n\n await new Promise(resolve => setTimeout(resolve, this.checkInterval));\n }\n\n return false;\n }\n\n /**\n * Get the current React context if loaded.\n * Awaits the bootstrap (with retries) rather than calling adapter.initialize() independently.\n * @returns React context with React, ReactDOM, Babel, and libraries\n */\n async getReactContext(): Promise<RuntimeContext> {\n await this.bootstrapWithRetries();\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Get the current React context synchronously\n * @returns React context or null if not loaded\n */\n getCurrentContext(): RuntimeContext | null {\n if (!this.adapter.isInitialized()) {\n return null;\n }\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Create a React root for rendering\n * @param container - DOM element to render into\n * @returns React root instance\n */\n createRoot(container: HTMLElement): any {\n const context = this.getCurrentContext();\n if (!context?.ReactDOM?.createRoot) {\n throw new Error('ReactDOM.createRoot not available');\n }\n\n const root = context.ReactDOM.createRoot(container);\n this.reactRoots.add(root);\n return root;\n }\n\n /**\n * Unmount and clean up a React root\n * @param root - React root to unmount\n */\n unmountRoot(root: any): void {\n if (root && typeof root.unmount === 'function') {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.delete(root);\n }\n\n /**\n * Transpile JSX code to JavaScript\n * @param code - JSX code to transpile\n * @param filename - Optional filename for error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename: string): string {\n return this.adapter.transpileJSX(code, filename);\n }\n\n /**\n * Clean up all React roots and reset context\n */\n private cleanup(): void {\n // Unmount all tracked React roots\n for (const root of this.reactRoots) {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.clear();\n \n // Reset readiness state\n this.reactReadySubject.next(false);\n this.firstComponentAttempted = false;\n\n // Clean up runtime hooks (disconnects observers, removes injected styles, etc.)\n reactRootManager.cleanup();\n\n // Clean up adapter\n this.adapter.destroy();\n }\n\n /**\n * Check if React is currently ready\n * @returns true if React is ready\n */\n isReady(): boolean {\n return this.reactReadySubject.value;\n }\n\n /**\n * Get the number of active React roots\n * @returns Number of active roots\n */\n getActiveRootsCount(): number {\n return this.reactRoots.size;\n }\n}"]}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality
|
|
3
3
|
* @module @memberjunction/ng-react/utilities
|
|
4
4
|
*/
|
|
5
|
+
import { IMetadataProvider } from '@memberjunction/core';
|
|
5
6
|
import { ComponentUtilities } from '@memberjunction/interactive-component-types';
|
|
6
7
|
/**
|
|
7
8
|
* Base class for providing runtime utilities to React components in Angular.
|
|
@@ -10,11 +11,21 @@ import { ComponentUtilities } from '@memberjunction/interactive-component-types'
|
|
|
10
11
|
*/
|
|
11
12
|
export declare class RuntimeUtilities {
|
|
12
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;
|
|
13
20
|
/**
|
|
14
21
|
* Builds the complete utilities object for React components
|
|
15
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()`.
|
|
16
27
|
*/
|
|
17
|
-
buildUtilities(debug?: boolean): ComponentUtilities;
|
|
28
|
+
buildUtilities(debug?: boolean, provider?: IMetadataProvider): ComponentUtilities;
|
|
18
29
|
/**
|
|
19
30
|
* Sets up the utilities object - copied from skip-chat implementation
|
|
20
31
|
*/
|
|
@@ -26,18 +26,22 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
26
26
|
/**
|
|
27
27
|
* Builds the complete utilities object for React components
|
|
28
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()`.
|
|
29
33
|
*/
|
|
30
|
-
buildUtilities(debug = false) {
|
|
34
|
+
buildUtilities(debug = false, provider) {
|
|
31
35
|
this.debug = debug;
|
|
32
|
-
|
|
33
|
-
return this.SetupUtilities(
|
|
36
|
+
this.provider = provider ?? Metadata.Provider;
|
|
37
|
+
return this.SetupUtilities(this.provider);
|
|
34
38
|
}
|
|
35
39
|
/**
|
|
36
40
|
* Sets up the utilities object - copied from skip-chat implementation
|
|
37
41
|
*/
|
|
38
42
|
SetupUtilities(md) {
|
|
39
|
-
const rv =
|
|
40
|
-
const rq = new RunQuery();
|
|
43
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
44
|
+
const rq = new RunQuery(md);
|
|
41
45
|
const u = {
|
|
42
46
|
md: this.CreateSimpleMetadata(md),
|
|
43
47
|
rv: this.CreateSimpleRunView(rv),
|
|
@@ -142,7 +146,7 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
142
146
|
*/
|
|
143
147
|
async listMLModels(filter, contextUser) {
|
|
144
148
|
try {
|
|
145
|
-
const rv =
|
|
149
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
146
150
|
const result = await rv.RunView({
|
|
147
151
|
EntityName: 'MJ: ML Models',
|
|
148
152
|
ExtraFilter: this.buildMLModelsFilter(filter),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-utilities.js","sourceRoot":"","sources":["../../../src/lib/utilities/runtime-utilities.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;AAEH,OAAO,EACL,QAAQ,EACR,OAAO,EACP,QAAQ,EAGR,QAAQ,EACR,UAAU,EAGX,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAiB9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAEL,uCAAuC,EAExC,MAAM,+BAA+B,CAAC;AAEvC;;;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,CAAC,CAAC;oBAC3F,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;wBACf,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;wBACrC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;oBAC1C,CAAC;oBACD,OAAO,OAAO,CAAC;gBACjB,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO,CAAC,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;oBACpD,QAAQ,CAAC,KAAK,CAAC,CAAC;oBAChB,MAAM,KAAK,CAAC,CAAC,sCAAsC;gBACrD,CAAC;YACH,CAAC;SACF,CAAA;IACH,CAAC;CACF,CAAA;AA7WY,gBAAgB;IAD5B,aAAa,CAAC,gBAAgB,EAAE,kBAAkB,CAAC;GACvC,gBAAgB,CA6W5B;;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB;IACpC,kEAAkE;IAClE,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,IAAI,CAAC;YACH,oFAAoF;YACpF,MAAM,GAAG,GAAG,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,cAAc,CAAmB,gBAAgB,CAAC,CAAC;YAC9F,IAAI,CAAC,GAAG,EAAE,CAAC;gBACT,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAChE,CAAC;YAED,uDAAuD;YACvD,OAAO,GAAG,CAAC;QACb,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,0BAA0B;QAC5B,CAAC;IACH,CAAC;IAED,mCAAmC;IACnC,OAAO,IAAI,gBAAgB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["/**\n * @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality\n * @module @memberjunction/ng-react/utilities\n */\n\nimport {\n Metadata,\n RunView,\n RunQuery,\n RunViewParams,\n RunQueryParams,\n LogError,\n BaseEntity,\n IEntityDataProvider,\n UserInfo\n} from '@memberjunction/core';\n\nimport { MJGlobal, RegisterClass } from '@memberjunction/global';\nimport { GeoDataEngine } from '@memberjunction/core-entities';\nimport {\n ComponentUtilities,\n SimpleAITools,\n SimpleGeoDataEngine,\n SimpleMetadata,\n SimpleMLTools,\n SimpleMLModelInfo,\n SimpleMLListModelsFilter,\n SimpleMLScoreResult,\n SimpleRunQuery,\n SimpleRunView,\n SimpleExecutePromptParams,\n SimpleExecutePromptResult,\n SimpleEmbedTextParams,\n SimpleEmbedTextResult\n} from '@memberjunction/interactive-component-types';\nimport { GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { SimpleVectorService } from '@memberjunction/ai-vectors-memory';\nimport {\n MJMLModelEntity,\n PredictiveStudioScoreRecordSetOperation,\n PredictiveStudioScoreRecordSetInput\n} from '@memberjunction/core-entities';\n\n/**\n * Base class for providing runtime utilities to React components in Angular.\n * This class can be extended and registered with MJ's ClassFactory\n * to provide custom implementations of data access methods.\n */\n@RegisterClass(RuntimeUtilities, 'RuntimeUtilities')\nexport class RuntimeUtilities {\n private debug: boolean = false;\n \n /**\n * Builds the complete utilities object for React components\n * This is the main method that components will use\n */\n public buildUtilities(debug: boolean = false): ComponentUtilities {\n this.debug = debug;\n const md = new Metadata(); // global-provider-ok: utility — single-provider context\n return this.SetupUtilities(md);\n }\n\n /**\n * Sets up the utilities object - copied from skip-chat implementation\n */\n private SetupUtilities(md: Metadata): ComponentUtilities {\n const rv = new RunView();\n const rq = new RunQuery();\n const u: ComponentUtilities = {\n md: this.CreateSimpleMetadata(md),\n rv: this.CreateSimpleRunView(rv),\n rq: this.CreateSimpleRunQuery(rq),\n ai: this.CreateSimpleAITools(),\n geoDataEngine: this.CreateSimpleGeoDataEngine(),\n ml: this.CreateSimpleMLTools()\n };\n return u;\n }\n\n private CreateSimpleAITools(): SimpleAITools {\n // Get the GraphQL provider - it's the same as the BaseEntity provider\n const provider = BaseEntity.Provider;\n \n // Check if it's a GraphQLDataProvider\n if (!(provider instanceof GraphQLDataProvider)) {\n throw new Error('Current data provider is not a GraphQLDataProvider. AI tools require GraphQL provider.');\n }\n\n const graphQLProvider = provider as GraphQLDataProvider;\n \n return {\n ExecutePrompt: async (params: SimpleExecutePromptParams): Promise<SimpleExecutePromptResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to execute simple prompt\n const result = await graphQLProvider.AI.ExecuteSimplePrompt({\n systemPrompt: params.systemPrompt,\n messages: params.messages,\n preferredModels: params.preferredModels,\n modelPower: params.modelPower\n });\n\n console.log(`🤖 ExecutePrompt succeeded!`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n\n return {\n success: result.success,\n result: result.result || '',\n resultObject: result.resultObject,\n modelName: result.modelName || ''\n };\n } catch (error) {\n LogError(error);\n return {\n success: false,\n result: 'Failed to execute prompt: ' + (error instanceof Error ? error.message : String(error)),\n modelName: ''\n };\n }\n },\n \n EmbedText: async (params: SimpleEmbedTextParams): Promise<SimpleEmbedTextResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to generate embeddings\n const result = await graphQLProvider.AI.EmbedText({\n textToEmbed: params.textToEmbed,\n modelSize: params.modelSize\n });\n \n if (result.error) {\n throw new Error(result.error || 'Failed to generate embeddings');\n }\n\n const numEmbeddings: number = Array.isArray(params.textToEmbed) ? result.embeddings?.length : 1;\n console.log(`🤖 EmbedText succeeded! ${numEmbeddings} embeddings returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n return {\n result: result.embeddings,\n modelName: result.modelName,\n vectorDimensions: result.vectorDimensions\n };\n } catch (error) {\n LogError(error);\n throw error; // Re-throw for embeddings as they're critical\n }\n },\n \n VectorService: new SimpleVectorService()\n };\n }\n\n /**\n * Creates the ML tools surface for components — listing trained models and scoring records.\n * `listModels` reads the `MJ: ML Models` catalog via RunView; `score` marshals the\n * `PredictiveStudio.ScoreRecordSet` Remote Operation over GraphQL to the server engine (the\n * Python sidecar lives server-side and cannot run in the browser). Returns `undefined` when no\n * GraphQL provider is available, so the `ml` capability degrades cleanly.\n */\n private CreateSimpleMLTools(): SimpleMLTools | undefined {\n const provider = BaseEntity.Provider;\n // Scoring requires a GraphQL provider to route the Remote Operation to the server engine.\n if (!(provider instanceof GraphQLDataProvider)) {\n return undefined;\n }\n const graphQLProvider = provider as GraphQLDataProvider;\n\n return {\n listModels: (filter?: SimpleMLListModelsFilter, contextUser?: UserInfo): Promise<SimpleMLModelInfo[]> =>\n this.listMLModels(filter, contextUser),\n\n score: (\n modelId: string,\n records: Array<Record<string, unknown> | string>,\n options?: { primaryKeyField?: string; contextUser?: UserInfo }\n ): Promise<SimpleMLScoreResult> => this.scoreMLRecords(graphQLProvider, modelId, records, options)\n };\n }\n\n /**\n * Loads the trained-model catalog from `MJ: ML Models`, newest version first, mapping each row\n * to a {@link SimpleMLModelInfo}. Resilient — logs and returns `[]` on any failure.\n */\n private async listMLModels(filter?: SimpleMLListModelsFilter, contextUser?: UserInfo): Promise<SimpleMLModelInfo[]> {\n try {\n const rv = new RunView();\n const result = await rv.RunView<MJMLModelEntity>(\n {\n EntityName: 'MJ: ML Models',\n ExtraFilter: this.buildMLModelsFilter(filter),\n OrderBy: 'Version DESC',\n MaxRows: filter?.maxResults,\n ResultType: 'entity_object'\n },\n contextUser\n );\n if (!result.Success) {\n console.error(`❌ listModels failed for MJ: ML Models: ${result.ErrorMessage}`);\n return [];\n }\n return result.Results.map((m) => this.mapMLModel(m));\n } catch (error) {\n LogError(error);\n return [];\n }\n }\n\n /**\n * Builds the ExtraFilter clause for {@link listMLModels}. Defaults to `Status='Published'` so\n * components only see promoted models unless the caller overrides the status.\n */\n private buildMLModelsFilter(filter?: SimpleMLListModelsFilter): string {\n const clauses: string[] = [];\n const status = filter?.status ?? 'Published';\n clauses.push(`Status='${this.escapeSqlLiteral(status)}'`);\n if (filter?.targetVariable) {\n clauses.push(`TargetVariable='${this.escapeSqlLiteral(filter.targetVariable)}'`);\n }\n return clauses.join(' AND ');\n }\n\n /** Maps a single `MJ: ML Models` row to the component-facing {@link SimpleMLModelInfo} shape. */\n private mapMLModel(m: MJMLModelEntity): SimpleMLModelInfo {\n return {\n id: m.ID,\n pipeline: m.Pipeline,\n version: m.Version,\n targetVariable: m.TargetVariable,\n problemType: m.ProblemType,\n status: m.Status,\n metrics: this.parseMLMetrics(m.Metrics),\n holdoutMetrics: this.parseMLMetrics(m.HoldoutMetrics)\n };\n }\n\n /** Defensively parses a JSON metrics blob; returns `undefined` for null/empty/invalid JSON. */\n private parseMLMetrics(raw: string | null): Record<string, unknown> | undefined {\n if (!raw) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Scores records with a trained model by invoking the `PredictiveStudio.ScoreRecordSet` Remote\n * Operation. Normalizes `records` to primary-key strings, requests ephemeral predictions (no\n * write-back), and maps the result. Resilient — logs and returns a zeroed result with the input\n * records counted as failed on any error.\n */\n private async scoreMLRecords(\n provider: GraphQLDataProvider,\n modelId: string,\n records: Array<Record<string, unknown> | string>,\n options?: { primaryKeyField?: string; contextUser?: UserInfo }\n ): Promise<SimpleMLScoreResult> {\n const keys = this.normalizeRecordKeys(records, options?.primaryKeyField ?? 'ID');\n try {\n const input: PredictiveStudioScoreRecordSetInput = {\n modelId,\n scope: { records: keys }\n // No writeBack → predictions are returned ephemerally.\n };\n const op = new PredictiveStudioScoreRecordSetOperation();\n const result = await op.Execute(input, { provider, user: options?.contextUser });\n if (!result.Success || !result.Output) {\n console.error(`❌ score failed for model ${modelId}: ${result.ErrorMessage}`);\n return { scoredCount: 0, failedCount: keys.length, skippedCount: 0, predictions: [] };\n }\n const out = result.Output;\n return {\n scoredCount: out.scored,\n failedCount: out.failed,\n skippedCount: out.skipped,\n predictions: (out.predictions ?? []).map((p) => ({\n recordId: p.recordId,\n score: p.score,\n class: p.class\n }))\n };\n } catch (error) {\n LogError(error);\n return { scoredCount: 0, failedCount: keys.length, skippedCount: 0, predictions: [] };\n }\n }\n\n /**\n * Normalizes a mixed array of primary-key strings and row objects into an array of primary-key\n * strings, reading `primaryKeyField` from objects. Drops entries without a resolvable key.\n */\n private normalizeRecordKeys(records: Array<Record<string, unknown> | string>, primaryKeyField: string): string[] {\n const keys: string[] = [];\n for (const r of records) {\n if (typeof r === 'string') {\n keys.push(r);\n } else if (r != null) {\n const value = r[primaryKeyField];\n if (value != null) {\n keys.push(String(value));\n }\n }\n }\n return keys;\n }\n\n /** Escapes single quotes for safe inlining into a RunView ExtraFilter SQL string literal. */\n private escapeSqlLiteral(value: string): string {\n return value.replace(/'/g, \"''\");\n }\n\n private CreateSimpleMetadata(md: Metadata): SimpleMetadata {\n return {\n Entities: md.Entities,\n GetEntityObject: (entityName: string) => {\n return md.GetEntityObject(entityName)\n }\n }\n }\n\n private CreateSimpleGeoDataEngine(): SimpleGeoDataEngine | undefined {\n try {\n const geo = GeoDataEngine.Instance;\n if (!geo) return undefined;\n return {\n ResolvePointToLocation: (lat: number, lng: number) => {\n return geo.ResolvePointToLocation(lat, lng);\n },\n // GeoDataEngine is on-demand load — callers must await before ResolvePointToLocation works.\n EnsureLoaded: () => geo.EnsureLoaded(),\n get Loaded() {\n return geo.Loaded;\n }\n };\n } catch {\n // GeoDataEngine may not be configured yet — return undefined\n return undefined;\n }\n }\n\n private CreateSimpleRunQuery(rq: RunQuery): SimpleRunQuery {\n return {\n RunQuery: async (params: RunQueryParams) => {\n // Run a single query and return the results\n try {\n const result = await rq.RunQuery(params);\n if (result.Success) {\n console.log(`✅ RunQuery \"${params.QueryName}\" succeeded: ${result.RowCount} rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n } else {\n console.error(`❌ RunQuery failed: ${result.ErrorMessage}`);\n }\n return result;\n } catch (error) {\n console.error(`❌ RunQuery threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n\n private CreateSimpleRunView(rv: RunView): SimpleRunView {\n return {\n RunView: async (params: RunViewParams) => {\n // Run a single view and return the results\n try {\n const result = await rv.RunView(params);\n if (result.Success) {\n console.log(`✅ RunView succeeded for ${params.EntityName}: ${result.TotalRowCount} rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n } else {\n console.error(`❌ RunView failed for ${params.EntityName}: ${result.ErrorMessage}`);\n }\n return result;\n } catch (error) {\n console.error(`❌ RunView threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n },\n RunViews: async (params: RunViewParams[]) => {\n // Runs multiple views and returns the results\n try {\n const results = await rv.RunViews(params);\n const entityNames = params.map(p => p.EntityName).join(', ');\n const totalRows = results.reduce((sum, r) => sum + (r.TotalRowCount || 0), 0);\n console.log(`✅ RunViews succeeded for [${entityNames}]: ${totalRows} total rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > results:', results);\n }\n return results;\n } catch (error) {\n console.error(`❌ RunViews threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n}\n\n/**\n * Factory function to create RuntimeUtilities\n * In a Node.js environment, this will use MJ's ClassFactory for runtime substitution\n * In a browser environment, it will use the base class directly\n */\nexport function createRuntimeUtilities(): RuntimeUtilities {\n // Check if we're in a Node.js environment with MJGlobal available\n if (typeof window === 'undefined') {\n try {\n // Use ClassFactory to get the registered class, defaulting to base RuntimeUtilities\n const obj = MJGlobal.Instance.ClassFactory.CreateInstance<RuntimeUtilities>(RuntimeUtilities);\n if (!obj) {\n throw new Error('Failed to create RuntimeUtilities instance');\n }\n\n // Ensure the object is an instance of RuntimeUtilities\n return obj;\n } catch (e) {\n // Fall through to default\n }\n }\n \n // Default: just use the base class\n return new RuntimeUtilities();\n}"]}
|
|
1
|
+
{"version":3,"file":"runtime-utilities.js","sourceRoot":"","sources":["../../../src/lib/utilities/runtime-utilities.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;AAEH,OAAO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cAAc,CAAmB,gBAAgB,CAAC,CAAC;YAC9F,IAAI,CAAC,GAAG,EAAE,CAAC;gBACT,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAChE,CAAC;YAED,uDAAuD;YACvD,OAAO,GAAG,CAAC;QACb,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,0BAA0B;QAC5B,CAAC;IACH,CAAC;IAED,mCAAmC;IACnC,OAAO,IAAI,gBAAgB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["/**\n * @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality\n * @module @memberjunction/ng-react/utilities\n */\n\nimport {\n Metadata,\n RunView,\n RunQuery,\n RunViewParams,\n RunQueryParams,\n LogError,\n BaseEntity,\n IEntityDataProvider,\n IMetadataProvider,\n IRunQueryProvider,\n UserInfo\n} from '@memberjunction/core';\n\nimport { MJGlobal, RegisterClass } from '@memberjunction/global';\nimport { GeoDataEngine } from '@memberjunction/core-entities';\nimport {\n ComponentUtilities,\n SimpleAITools,\n SimpleGeoDataEngine,\n SimpleMetadata,\n SimpleMLTools,\n SimpleMLModelInfo,\n SimpleMLListModelsFilter,\n SimpleMLScoreResult,\n SimpleRunQuery,\n SimpleRunView,\n SimpleExecutePromptParams,\n SimpleExecutePromptResult,\n SimpleEmbedTextParams,\n SimpleEmbedTextResult\n} from '@memberjunction/interactive-component-types';\nimport { GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { SimpleVectorService } from '@memberjunction/ai-vectors-memory';\nimport {\n MJMLModelEntity,\n PredictiveStudioScoreRecordSetOperation,\n PredictiveStudioScoreRecordSetInput\n} from '@memberjunction/core-entities';\n\n/**\n * Base class for providing runtime utilities to React components in Angular.\n * This class can be extended and registered with MJ's ClassFactory\n * to provide custom implementations of data access methods.\n */\n@RegisterClass(RuntimeUtilities, 'RuntimeUtilities')\nexport class RuntimeUtilities {\n private debug: boolean = false;\n /**\n * The provider every read in the built utilities goes through. Always set by\n * {@link buildUtilities} before use — falls back to the global provider there\n * (`provider ?? Metadata.Provider`) when the host doesn't supply one.\n */\n private provider!: IMetadataProvider;\n\n /**\n * Builds the complete utilities object for React components\n * This is the main method that components will use\n *\n * @param provider the host's provider. A React component mounted under a non-default provider\n * passes its own `ProviderToUse`; omitting it falls back to the global default, named\n * explicitly rather than reached for via `new Metadata()`.\n */\n public buildUtilities(debug: boolean = false, provider?: IMetadataProvider): ComponentUtilities {\n this.debug = debug;\n this.provider = provider ?? Metadata.Provider;\n return this.SetupUtilities(this.provider);\n }\n\n /**\n * Sets up the utilities object - copied from skip-chat implementation\n */\n private SetupUtilities(md: IMetadataProvider): ComponentUtilities {\n const rv = RunView.FromMetadataProvider(md);\n const rq = new RunQuery(md as unknown as IRunQueryProvider);\n const u: ComponentUtilities = {\n md: this.CreateSimpleMetadata(md),\n rv: this.CreateSimpleRunView(rv),\n rq: this.CreateSimpleRunQuery(rq),\n ai: this.CreateSimpleAITools(),\n geoDataEngine: this.CreateSimpleGeoDataEngine(),\n ml: this.CreateSimpleMLTools()\n };\n return u;\n }\n\n private CreateSimpleAITools(): SimpleAITools {\n // Get the GraphQL provider - it's the same as the BaseEntity provider\n const provider = BaseEntity.Provider;\n \n // Check if it's a GraphQLDataProvider\n if (!(provider instanceof GraphQLDataProvider)) {\n throw new Error('Current data provider is not a GraphQLDataProvider. AI tools require GraphQL provider.');\n }\n\n const graphQLProvider = provider as GraphQLDataProvider;\n \n return {\n ExecutePrompt: async (params: SimpleExecutePromptParams): Promise<SimpleExecutePromptResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to execute simple prompt\n const result = await graphQLProvider.AI.ExecuteSimplePrompt({\n systemPrompt: params.systemPrompt,\n messages: params.messages,\n preferredModels: params.preferredModels,\n modelPower: params.modelPower\n });\n\n console.log(`🤖 ExecutePrompt succeeded!`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n\n return {\n success: result.success,\n result: result.result || '',\n resultObject: result.resultObject,\n modelName: result.modelName || ''\n };\n } catch (error) {\n LogError(error);\n return {\n success: false,\n result: 'Failed to execute prompt: ' + (error instanceof Error ? error.message : String(error)),\n modelName: ''\n };\n }\n },\n \n EmbedText: async (params: SimpleEmbedTextParams): Promise<SimpleEmbedTextResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to generate embeddings\n const result = await graphQLProvider.AI.EmbedText({\n textToEmbed: params.textToEmbed,\n modelSize: params.modelSize\n });\n \n if (result.error) {\n throw new Error(result.error || 'Failed to generate embeddings');\n }\n\n const numEmbeddings: number = Array.isArray(params.textToEmbed) ? result.embeddings?.length : 1;\n console.log(`🤖 EmbedText succeeded! ${numEmbeddings} embeddings returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n return {\n result: result.embeddings,\n modelName: result.modelName,\n vectorDimensions: result.vectorDimensions\n };\n } catch (error) {\n LogError(error);\n throw error; // Re-throw for embeddings as they're critical\n }\n },\n \n VectorService: new SimpleVectorService()\n };\n }\n\n /**\n * Creates the ML tools surface for components — listing trained models and scoring records.\n * `listModels` reads the `MJ: ML Models` catalog via RunView; `score` marshals the\n * `PredictiveStudio.ScoreRecordSet` Remote Operation over GraphQL to the server engine (the\n * Python sidecar lives server-side and cannot run in the browser). Returns `undefined` when no\n * GraphQL provider is available, so the `ml` capability degrades cleanly.\n */\n private CreateSimpleMLTools(): SimpleMLTools | undefined {\n const provider = BaseEntity.Provider;\n // Scoring requires a GraphQL provider to route the Remote Operation to the server engine.\n if (!(provider instanceof GraphQLDataProvider)) {\n return undefined;\n }\n const graphQLProvider = provider as GraphQLDataProvider;\n\n return {\n listModels: (filter?: SimpleMLListModelsFilter, contextUser?: UserInfo): Promise<SimpleMLModelInfo[]> =>\n this.listMLModels(filter, contextUser),\n\n score: (\n modelId: string,\n records: Array<Record<string, unknown> | string>,\n options?: { primaryKeyField?: string; contextUser?: UserInfo }\n ): Promise<SimpleMLScoreResult> => this.scoreMLRecords(graphQLProvider, modelId, records, options)\n };\n }\n\n /**\n * Loads the trained-model catalog from `MJ: ML Models`, newest version first, mapping each row\n * to a {@link SimpleMLModelInfo}. Resilient — logs and returns `[]` on any failure.\n */\n private async listMLModels(filter?: SimpleMLListModelsFilter, contextUser?: UserInfo): Promise<SimpleMLModelInfo[]> {\n try {\n const rv = RunView.FromMetadataProvider(this.provider);\n const result = await rv.RunView<MJMLModelEntity>(\n {\n EntityName: 'MJ: ML Models',\n ExtraFilter: this.buildMLModelsFilter(filter),\n OrderBy: 'Version DESC',\n MaxRows: filter?.maxResults,\n ResultType: 'entity_object'\n },\n contextUser\n );\n if (!result.Success) {\n console.error(`❌ listModels failed for MJ: ML Models: ${result.ErrorMessage}`);\n return [];\n }\n return result.Results.map((m) => this.mapMLModel(m));\n } catch (error) {\n LogError(error);\n return [];\n }\n }\n\n /**\n * Builds the ExtraFilter clause for {@link listMLModels}. Defaults to `Status='Published'` so\n * components only see promoted models unless the caller overrides the status.\n */\n private buildMLModelsFilter(filter?: SimpleMLListModelsFilter): string {\n const clauses: string[] = [];\n const status = filter?.status ?? 'Published';\n clauses.push(`Status='${this.escapeSqlLiteral(status)}'`);\n if (filter?.targetVariable) {\n clauses.push(`TargetVariable='${this.escapeSqlLiteral(filter.targetVariable)}'`);\n }\n return clauses.join(' AND ');\n }\n\n /** Maps a single `MJ: ML Models` row to the component-facing {@link SimpleMLModelInfo} shape. */\n private mapMLModel(m: MJMLModelEntity): SimpleMLModelInfo {\n return {\n id: m.ID,\n pipeline: m.Pipeline,\n version: m.Version,\n targetVariable: m.TargetVariable,\n problemType: m.ProblemType,\n status: m.Status,\n metrics: this.parseMLMetrics(m.Metrics),\n holdoutMetrics: this.parseMLMetrics(m.HoldoutMetrics)\n };\n }\n\n /** Defensively parses a JSON metrics blob; returns `undefined` for null/empty/invalid JSON. */\n private parseMLMetrics(raw: string | null): Record<string, unknown> | undefined {\n if (!raw) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Scores records with a trained model by invoking the `PredictiveStudio.ScoreRecordSet` Remote\n * Operation. Normalizes `records` to primary-key strings, requests ephemeral predictions (no\n * write-back), and maps the result. Resilient — logs and returns a zeroed result with the input\n * records counted as failed on any error.\n */\n private async scoreMLRecords(\n provider: GraphQLDataProvider,\n modelId: string,\n records: Array<Record<string, unknown> | string>,\n options?: { primaryKeyField?: string; contextUser?: UserInfo }\n ): Promise<SimpleMLScoreResult> {\n const keys = this.normalizeRecordKeys(records, options?.primaryKeyField ?? 'ID');\n try {\n const input: PredictiveStudioScoreRecordSetInput = {\n modelId,\n scope: { records: keys }\n // No writeBack → predictions are returned ephemerally.\n };\n const op = new PredictiveStudioScoreRecordSetOperation();\n const result = await op.Execute(input, { provider, user: options?.contextUser });\n if (!result.Success || !result.Output) {\n console.error(`❌ score failed for model ${modelId}: ${result.ErrorMessage}`);\n return { scoredCount: 0, failedCount: keys.length, skippedCount: 0, predictions: [] };\n }\n const out = result.Output;\n return {\n scoredCount: out.scored,\n failedCount: out.failed,\n skippedCount: out.skipped,\n predictions: (out.predictions ?? []).map((p) => ({\n recordId: p.recordId,\n score: p.score,\n class: p.class\n }))\n };\n } catch (error) {\n LogError(error);\n return { scoredCount: 0, failedCount: keys.length, skippedCount: 0, predictions: [] };\n }\n }\n\n /**\n * Normalizes a mixed array of primary-key strings and row objects into an array of primary-key\n * strings, reading `primaryKeyField` from objects. Drops entries without a resolvable key.\n */\n private normalizeRecordKeys(records: Array<Record<string, unknown> | string>, primaryKeyField: string): string[] {\n const keys: string[] = [];\n for (const r of records) {\n if (typeof r === 'string') {\n keys.push(r);\n } else if (r != null) {\n const value = r[primaryKeyField];\n if (value != null) {\n keys.push(String(value));\n }\n }\n }\n return keys;\n }\n\n /** Escapes single quotes for safe inlining into a RunView ExtraFilter SQL string literal. */\n private escapeSqlLiteral(value: string): string {\n return value.replace(/'/g, \"''\");\n }\n\n private CreateSimpleMetadata(md: IMetadataProvider): SimpleMetadata {\n return {\n Entities: md.Entities,\n GetEntityObject: (entityName: string) => {\n return md.GetEntityObject(entityName)\n }\n }\n }\n\n private CreateSimpleGeoDataEngine(): SimpleGeoDataEngine | undefined {\n try {\n const geo = GeoDataEngine.Instance;\n if (!geo) return undefined;\n return {\n ResolvePointToLocation: (lat: number, lng: number) => {\n return geo.ResolvePointToLocation(lat, lng);\n },\n // GeoDataEngine is on-demand load — callers must await before ResolvePointToLocation works.\n EnsureLoaded: () => geo.EnsureLoaded(),\n get Loaded() {\n return geo.Loaded;\n }\n };\n } catch {\n // GeoDataEngine may not be configured yet — return undefined\n return undefined;\n }\n }\n\n private CreateSimpleRunQuery(rq: RunQuery): SimpleRunQuery {\n return {\n RunQuery: async (params: RunQueryParams) => {\n // Run a single query and return the results\n try {\n const result = await rq.RunQuery(params);\n if (result.Success) {\n console.log(`✅ RunQuery \"${params.QueryName}\" succeeded: ${result.RowCount} rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n } else {\n console.error(`❌ RunQuery failed: ${result.ErrorMessage}`);\n }\n return result;\n } catch (error) {\n console.error(`❌ RunQuery threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n\n private CreateSimpleRunView(rv: RunView): SimpleRunView {\n return {\n RunView: async (params: RunViewParams) => {\n // Run a single view and return the results\n try {\n const result = await rv.RunView(params);\n if (result.Success) {\n console.log(`✅ RunView succeeded for ${params.EntityName}: ${result.TotalRowCount} rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n } else {\n console.error(`❌ RunView failed for ${params.EntityName}: ${result.ErrorMessage}`);\n }\n return result;\n } catch (error) {\n console.error(`❌ RunView threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n },\n RunViews: async (params: RunViewParams[]) => {\n // Runs multiple views and returns the results\n try {\n const results = await rv.RunViews(params);\n const entityNames = params.map(p => p.EntityName).join(', ');\n const totalRows = results.reduce((sum, r) => sum + (r.TotalRowCount || 0), 0);\n console.log(`✅ RunViews succeeded for [${entityNames}]: ${totalRows} total rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > results:', results);\n }\n return results;\n } catch (error) {\n console.error(`❌ RunViews threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n}\n\n/**\n * Factory function to create RuntimeUtilities\n * In a Node.js environment, this will use MJ's ClassFactory for runtime substitution\n * In a browser environment, it will use the base class directly\n */\nexport function createRuntimeUtilities(): RuntimeUtilities {\n // Check if we're in a Node.js environment with MJGlobal available\n if (typeof window === 'undefined') {\n try {\n // Use ClassFactory to get the registered class, defaulting to base RuntimeUtilities\n const obj = MJGlobal.Instance.ClassFactory.CreateInstance<RuntimeUtilities>(RuntimeUtilities);\n if (!obj) {\n throw new Error('Failed to create RuntimeUtilities instance');\n }\n\n // Ensure the object is an instance of RuntimeUtilities\n return obj;\n } catch (e) {\n // Fall through to default\n }\n }\n \n // Default: just use the base class\n return new RuntimeUtilities();\n}"]}
|
package/package.json
CHANGED
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memberjunction/ng-react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "6.1.0-edge.0",
|
|
4
4
|
"description": "Angular components for hosting React components in MemberJunction applications",
|
|
5
|
-
"scripts": {
|
|
6
|
-
"build": "ngc -p tsconfig.json",
|
|
7
|
-
"watch": "ngc -p tsconfig.json --watch",
|
|
8
|
-
"test": "vitest run",
|
|
9
|
-
"patchVersion": "npm version patch",
|
|
10
|
-
"test:watch": "vitest"
|
|
11
|
-
},
|
|
12
5
|
"repository": {
|
|
13
6
|
"type": "git",
|
|
14
7
|
"url": "https://github.com/MemberJunction/MJ"
|
|
@@ -41,14 +34,14 @@
|
|
|
41
34
|
"styles"
|
|
42
35
|
],
|
|
43
36
|
"dependencies": {
|
|
44
|
-
"@memberjunction/ai-vectors-memory": "
|
|
45
|
-
"@memberjunction/core": "
|
|
46
|
-
"@memberjunction/core-entities": "
|
|
47
|
-
"@memberjunction/global": "
|
|
48
|
-
"@memberjunction/graphql-dataprovider": "
|
|
49
|
-
"@memberjunction/interactive-component-types": "
|
|
50
|
-
"@memberjunction/ng-notifications": "
|
|
51
|
-
"@memberjunction/react-runtime": "
|
|
37
|
+
"@memberjunction/ai-vectors-memory": "6.1.0-edge.0",
|
|
38
|
+
"@memberjunction/core": "6.1.0-edge.0",
|
|
39
|
+
"@memberjunction/core-entities": "6.1.0-edge.0",
|
|
40
|
+
"@memberjunction/global": "6.1.0-edge.0",
|
|
41
|
+
"@memberjunction/graphql-dataprovider": "6.1.0-edge.0",
|
|
42
|
+
"@memberjunction/interactive-component-types": "6.1.0-edge.0",
|
|
43
|
+
"@memberjunction/ng-notifications": "6.1.0-edge.0",
|
|
44
|
+
"@memberjunction/react-runtime": "6.1.0-edge.0",
|
|
52
45
|
"@angular/common": "21.1.3",
|
|
53
46
|
"@angular/core": "21.1.3",
|
|
54
47
|
"@angular/platform-browser": "21.1.3",
|
|
@@ -58,12 +51,21 @@
|
|
|
58
51
|
"rxjs": "^7.8.2",
|
|
59
52
|
"@types/react": "^19.2.13",
|
|
60
53
|
"@types/react-dom": "^19.2.3",
|
|
61
|
-
"@memberjunction/ng-base-types": "
|
|
54
|
+
"@memberjunction/ng-base-types": "6.1.0-edge.0"
|
|
62
55
|
},
|
|
63
56
|
"devDependencies": {
|
|
64
57
|
"@angular/compiler": "21.1.3",
|
|
65
58
|
"@angular/compiler-cli": "21.1.3",
|
|
66
59
|
"typescript": "5.9.3",
|
|
67
60
|
"vitest": "^4.0.18"
|
|
61
|
+
},
|
|
62
|
+
"mjUILayer": "widgets",
|
|
63
|
+
"scripts": {
|
|
64
|
+
"build": "ngc -p tsconfig.json",
|
|
65
|
+
"watch": "ngc -p tsconfig.json --watch",
|
|
66
|
+
"test": "vitest run",
|
|
67
|
+
"test:types": "tsc --noEmit -p tsconfig.spec.json",
|
|
68
|
+
"patchVersion": "npm version patch",
|
|
69
|
+
"test:watch": "vitest"
|
|
68
70
|
}
|
|
69
71
|
}
|