@memberjunction/ng-react 6.1.4 → 6.2.0-edge.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/__tests__/react-bridge.service.test.js +11 -3
  2. package/dist/__tests__/react-bridge.service.test.js.map +1 -1
  3. package/dist/lib/components/mj-react-component.component.d.ts +128 -14
  4. package/dist/lib/components/mj-react-component.component.js +313 -207
  5. package/dist/lib/components/mj-react-component.component.js.map +1 -1
  6. package/dist/lib/config/react-debug.config.d.ts +4 -0
  7. package/dist/lib/config/react-debug.config.js +10 -2
  8. package/dist/lib/config/react-debug.config.js.map +1 -1
  9. package/dist/lib/hooks/antd-dropdown-position-hook.d.ts +2 -0
  10. package/dist/lib/hooks/antd-dropdown-position-hook.js +5 -1
  11. package/dist/lib/hooks/antd-dropdown-position-hook.js.map +1 -1
  12. package/dist/lib/services/angular-adapter.service.d.ts +32 -0
  13. package/dist/lib/services/angular-adapter.service.js +78 -18
  14. package/dist/lib/services/angular-adapter.service.js.map +1 -1
  15. package/dist/lib/services/react-bridge.service.d.ts +26 -2
  16. package/dist/lib/services/react-bridge.service.js +66 -18
  17. package/dist/lib/services/react-bridge.service.js.map +1 -1
  18. package/dist/lib/services/script-loader.service.d.ts +17 -0
  19. package/dist/lib/services/script-loader.service.js +26 -6
  20. package/dist/lib/services/script-loader.service.js.map +1 -1
  21. package/package.json +10 -10
  22. package/dist/__tests__/runtime-utilities-ml.test.d.ts +0 -1
  23. package/dist/__tests__/runtime-utilities-ml.test.js +0 -170
  24. package/dist/__tests__/runtime-utilities-ml.test.js.map +0 -1
  25. package/dist/lib/utilities/runtime-utilities.d.ts +0 -80
  26. package/dist/lib/utilities/runtime-utilities.js +0 -396
  27. package/dist/lib/utilities/runtime-utilities.js.map +0 -1
@@ -9,7 +9,7 @@ import { filter } from 'rxjs/operators';
9
9
  import { AngularAdapterService } from './angular-adapter.service';
10
10
  import { reactRootManager } from '@memberjunction/react-runtime';
11
11
  import { ReactDebugConfig } from '../config/react-debug.config';
12
- import { createAntdDropdownPositionHook } from '../hooks/antd-dropdown-position-hook';
12
+ import { CreateAntdDropdownPositionHook } from '../hooks/antd-dropdown-position-hook';
13
13
  import * as i0 from "@angular/core";
14
14
  import * as i1 from "./angular-adapter.service";
15
15
  /**
@@ -17,12 +17,28 @@ import * as i1 from "./angular-adapter.service";
17
17
  * Provides methods for creating and managing React roots in Angular applications.
18
18
  */
19
19
  export class ReactBridgeService {
20
+ /** @deprecated Use {@link ReactReady$}. */
21
+ get reactReady$() {
22
+ return this.ReactReady$;
23
+ }
24
+ /** @deprecated Use {@link ReactReady$}. */
25
+ set reactReady$(value) {
26
+ this.ReactReady$ = value;
27
+ }
28
+ /** @deprecated Use {@link Debug}. */
29
+ get debug() {
30
+ return this.Debug;
31
+ }
32
+ /** @deprecated Use {@link Debug}. */
33
+ set debug(value) {
34
+ this.Debug = value;
35
+ }
20
36
  constructor(adapter) {
21
37
  this.adapter = adapter;
22
38
  this.reactRoots = new Set();
23
39
  // Track React readiness state
24
40
  this.reactReadySubject = new BehaviorSubject(false);
25
- this.reactReady$ = this.reactReadySubject.asObservable();
41
+ this.ReactReady$ = this.reactReadySubject.asObservable();
26
42
  // Track if this is the first component trying to use React
27
43
  this.firstComponentAttempted = false;
28
44
  this.maxWaitTime = 5000; // Maximum 5 seconds wait time for createRoot poll
@@ -30,7 +46,7 @@ export class ReactBridgeService {
30
46
  this.maxBootstrapRetries = 2; // Retry bootstrap up to 2 additional times
31
47
  this.retryBaseDelay = 2000; // Base delay between bootstrap retries (ms)
32
48
  // Debug flag from project configuration
33
- this.debug = ReactDebugConfig.getDebugMode();
49
+ this.Debug = ReactDebugConfig.getDebugMode();
34
50
  // The current bootstrap attempt — shared between constructor and getReactContext()
35
51
  this.bootstrapPromise = null;
36
52
  // Bootstrap React immediately on service initialization
@@ -55,7 +71,7 @@ export class ReactBridgeService {
55
71
  * backoff if the CDN is unreachable or returns an error.
56
72
  */
57
73
  async doBootstrapWithRetries() {
58
- console.log(`ReactBridgeService: Initializing React with debug mode = ${this.debug} (from ReactDebugConfig)`);
74
+ console.log(`ReactBridgeService: Initializing React with debug mode = ${this.Debug} (from ReactDebugConfig)`);
59
75
  let lastError;
60
76
  for (let attempt = 0; attempt <= this.maxBootstrapRetries; attempt++) {
61
77
  try {
@@ -64,7 +80,7 @@ export class ReactBridgeService {
64
80
  console.warn(`React CDN bootstrap attempt ${attempt + 1} of ${this.maxBootstrapRetries + 1} — retrying in ${delay}ms...`);
65
81
  await new Promise(resolve => setTimeout(resolve, delay));
66
82
  }
67
- await this.adapter.initialize(undefined, undefined, { debug: this.debug });
83
+ await this.adapter.initialize(undefined, undefined, { debug: this.Debug });
68
84
  // Validate that ReactDOM.createRoot is actually callable.
69
85
  // If CDN scripts loaded in the wrong order (ReactDOM before React),
70
86
  // the ReactDOM object exists but createRoot is broken.
@@ -73,8 +89,8 @@ export class ReactBridgeService {
73
89
  throw new Error('ReactDOM loaded but createRoot is not available — possible script execution order issue');
74
90
  }
75
91
  // Register Angular-specific runtime hooks for library compatibility
76
- reactRootManager.RegisterHook(createAntdDropdownPositionHook());
77
- if (this.debug) {
92
+ reactRootManager.RegisterHook(CreateAntdDropdownPositionHook());
93
+ if (this.Debug) {
78
94
  console.log('React ecosystem pre-loaded successfully with DEVELOPMENT builds (detailed error messages)');
79
95
  }
80
96
  else {
@@ -96,7 +112,7 @@ export class ReactBridgeService {
96
112
  * If bootstrap succeeded but createRoot isn't usable (stale browser cache),
97
113
  * forces a re-bootstrap and retries.
98
114
  */
99
- async waitForReactReady() {
115
+ async WaitForReactReady() {
100
116
  // If already ready, return immediately
101
117
  if (this.reactReadySubject.value) {
102
118
  return;
@@ -109,9 +125,13 @@ export class ReactBridgeService {
109
125
  }
110
126
  else {
111
127
  // Subsequent components wait for the ready signal
112
- await firstValueFrom(this.reactReady$.pipe(filter(ready => ready)));
128
+ await firstValueFrom(this.ReactReady$.pipe(filter(ready => ready)));
113
129
  }
114
130
  }
131
+ /** @deprecated Use {@link WaitForReactReady}. */
132
+ async waitForReactReady() {
133
+ return this.WaitForReactReady();
134
+ }
115
135
  /**
116
136
  * Poll for ReactDOM.createRoot availability. If the poll window expires
117
137
  * (bootstrap succeeded but createRoot is broken, e.g. stale cache),
@@ -136,7 +156,7 @@ export class ReactBridgeService {
136
156
  const ready = await this.pollForCreateRoot();
137
157
  if (ready) {
138
158
  this.reactReadySubject.next(true);
139
- if (this.debug) {
159
+ if (this.Debug) {
140
160
  console.log(`React is fully ready after ${Date.now() - overallStart}ms (attempt ${attempt + 1})`);
141
161
  }
142
162
  return;
@@ -179,27 +199,35 @@ export class ReactBridgeService {
179
199
  * Awaits the bootstrap (with retries) rather than calling adapter.initialize() independently.
180
200
  * @returns React context with React, ReactDOM, Babel, and libraries
181
201
  */
182
- async getReactContext() {
202
+ async GetReactContext() {
183
203
  await this.bootstrapWithRetries();
184
204
  return this.adapter.getRuntimeContext();
185
205
  }
206
+ /** @deprecated Use {@link GetReactContext}. */
207
+ async getReactContext() {
208
+ return this.GetReactContext();
209
+ }
186
210
  /**
187
211
  * Get the current React context synchronously
188
212
  * @returns React context or null if not loaded
189
213
  */
190
- getCurrentContext() {
214
+ GetCurrentContext() {
191
215
  if (!this.adapter.isInitialized()) {
192
216
  return null;
193
217
  }
194
218
  return this.adapter.getRuntimeContext();
195
219
  }
220
+ /** @deprecated Use {@link GetCurrentContext}. */
221
+ getCurrentContext() {
222
+ return this.GetCurrentContext();
223
+ }
196
224
  /**
197
225
  * Create a React root for rendering
198
226
  * @param container - DOM element to render into
199
227
  * @returns React root instance
200
228
  */
201
- createRoot(container) {
202
- const context = this.getCurrentContext();
229
+ CreateRoot(container) {
230
+ const context = this.GetCurrentContext();
203
231
  if (!context?.ReactDOM?.createRoot) {
204
232
  throw new Error('ReactDOM.createRoot not available');
205
233
  }
@@ -207,11 +235,15 @@ export class ReactBridgeService {
207
235
  this.reactRoots.add(root);
208
236
  return root;
209
237
  }
238
+ /** @deprecated Use {@link CreateRoot}. */
239
+ createRoot(container) {
240
+ return this.CreateRoot(container);
241
+ }
210
242
  /**
211
243
  * Unmount and clean up a React root
212
244
  * @param root - React root to unmount
213
245
  */
214
- unmountRoot(root) {
246
+ UnmountRoot(root) {
215
247
  if (root && typeof root.unmount === 'function') {
216
248
  try {
217
249
  root.unmount();
@@ -222,15 +254,23 @@ export class ReactBridgeService {
222
254
  }
223
255
  this.reactRoots.delete(root);
224
256
  }
257
+ /** @deprecated Use {@link UnmountRoot}. */
258
+ unmountRoot(root) {
259
+ return this.UnmountRoot(root);
260
+ }
225
261
  /**
226
262
  * Transpile JSX code to JavaScript
227
263
  * @param code - JSX code to transpile
228
264
  * @param filename - Optional filename for error messages
229
265
  * @returns Transpiled JavaScript code
230
266
  */
231
- transpileJSX(code, filename) {
267
+ TranspileJSX(code, filename) {
232
268
  return this.adapter.transpileJSX(code, filename);
233
269
  }
270
+ /** @deprecated Use {@link TranspileJSX}. */
271
+ transpileJSX(code, filename) {
272
+ return this.TranspileJSX(code, filename);
273
+ }
234
274
  /**
235
275
  * Clean up all React roots and reset context
236
276
  */
@@ -257,16 +297,24 @@ export class ReactBridgeService {
257
297
  * Check if React is currently ready
258
298
  * @returns true if React is ready
259
299
  */
260
- isReady() {
300
+ IsReady() {
261
301
  return this.reactReadySubject.value;
262
302
  }
303
+ /** @deprecated Use {@link IsReady}. */
304
+ isReady() {
305
+ return this.IsReady();
306
+ }
263
307
  /**
264
308
  * Get the number of active React roots
265
309
  * @returns Number of active roots
266
310
  */
267
- getActiveRootsCount() {
311
+ GetActiveRootsCount() {
268
312
  return this.reactRoots.size;
269
313
  }
314
+ /** @deprecated Use {@link GetActiveRootsCount}. */
315
+ getActiveRootsCount() {
316
+ return this.GetActiveRootsCount();
317
+ }
270
318
  static { this.ɵfac = function ReactBridgeService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ReactBridgeService)(i0.ɵɵinject(i1.AngularAdapterService)); }; }
271
319
  static { this.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: ReactBridgeService, factory: ReactBridgeService.ɵfac, providedIn: 'root' }); }
272
320
  }
@@ -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,CAAC;AAChE,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;;;AAEtF;;;GAGG;AAEH,MAAM,OAAO,kBAAkB;IAoB7B,YAAoB,OAA8B;QAA9B,YAAO,GAAP,OAAO,CAAuB;QAnB1C,eAAU,GAAG,IAAI,GAAG,EAAO,CAAC;QAEpC,8BAA8B;QACtB,sBAAiB,GAAG,IAAI,eAAe,CAAU,KAAK,CAAC,CAAC;QACzD,gBAAW,GAAG,IAAI,CAAC,iBAAiB,CAAC,YAAY,EAAE,CAAC;QAE3D,2DAA2D;QACnD,4BAAuB,GAAG,KAAK,CAAC;QAChC,gBAAW,GAAG,IAAI,CAAC,CAAC,kDAAkD;QACtE,kBAAa,GAAG,GAAG,CAAC,CAAC,oBAAoB;QACzC,wBAAmB,GAAG,CAAC,CAAC,CAAC,2CAA2C;QACpE,mBAAc,GAAG,IAAI,CAAC,CAAC,4CAA4C;QAE3E,wCAAwC;QACjC,UAAK,GAAY,gBAAgB,CAAC,YAAY,EAAE,CAAC;QAExD,mFAAmF;QAC3E,qBAAgB,GAAyB,IAAI,CAAC;QAGpD,wDAAwD;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;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}"]}
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,kBAAkB;IAO7B,2CAA2C;IAC3C,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IACD,2CAA2C;IAC3C,IAAW,WAAW,CAAC,KAAK;QAC1B,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;IAC3B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AAC;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,uCAAuC;IACvC,OAAO;QACL,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;IAC9B,CAAC;IAED,mDAAmD;IACnD,mBAAmB;QACjB,OAAO,IAAI,CAAC,mBAAmB,EAAE,CAAC;IACpC,CAAC;mHA1VU,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 /** @deprecated Use {@link ReactReady$}. */\n public get reactReady$() {\n return this.ReactReady$;\n }\n /** @deprecated Use {@link ReactReady$}. */\n public set reactReady$(value) {\n this.ReactReady$ = value;\n }\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 /** @deprecated Use {@link Debug}. */\n public get debug(): boolean {\n return this.Debug;\n }\n /** @deprecated Use {@link Debug}. */\n public set debug(value: boolean) {\n this.Debug = value;\n }\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 /** @deprecated Use {@link WaitForReactReady}. */\n async waitForReactReady(): Promise<void> {\n return this.WaitForReactReady();\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 /** @deprecated Use {@link GetReactContext}. */\n async getReactContext(): Promise<RuntimeContext> {\n return this.GetReactContext();\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 /** @deprecated Use {@link GetCurrentContext}. */\n getCurrentContext(): RuntimeContext | null {\n return this.GetCurrentContext();\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 /** @deprecated Use {@link CreateRoot}. */\n createRoot(container: HTMLElement): any {\n return this.CreateRoot(container);\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 /** @deprecated Use {@link UnmountRoot}. */\n unmountRoot(root: any): void {\n return this.UnmountRoot(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 /** @deprecated Use {@link TranspileJSX}. */\n transpileJSX(code: string, filename: string): string {\n return this.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 /** @deprecated Use {@link IsReady}. */\n isReady(): boolean {\n return this.IsReady();\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\n /** @deprecated Use {@link GetActiveRootsCount}. */\n getActiveRootsCount(): number {\n return this.GetActiveRootsCount();\n }\n}"]}
@@ -21,6 +21,8 @@ export declare class ScriptLoaderService implements OnDestroy {
21
21
  * @param autoCleanup - Whether to cleanup on service destroy
22
22
  * @returns Promise resolving to the global object
23
23
  */
24
+ LoadScript(url: string, globalName: string, autoCleanup?: boolean): Promise<any>;
25
+ /** @deprecated Use {@link LoadScript}. */
24
26
  loadScript(url: string, globalName: string, autoCleanup?: boolean): Promise<any>;
25
27
  /**
26
28
  * Load a script with additional validation function
@@ -30,11 +32,15 @@ export declare class ScriptLoaderService implements OnDestroy {
30
32
  * @param autoCleanup - Whether to cleanup on service destroy
31
33
  * @returns Promise resolving to the validated global object
32
34
  */
35
+ LoadScriptWithValidation(url: string, globalName: string, validator: (obj: any) => boolean, autoCleanup?: boolean): Promise<any>;
36
+ /** @deprecated Use {@link LoadScriptWithValidation}. */
33
37
  loadScriptWithValidation(url: string, globalName: string, validator: (obj: any) => boolean, autoCleanup?: boolean): Promise<any>;
34
38
  /**
35
39
  * Load CSS from URL
36
40
  * @param url - CSS URL to load
37
41
  */
42
+ LoadCSS(url: string): void;
43
+ /** @deprecated Use {@link LoadCSS}. */
38
44
  loadCSS(url: string): void;
39
45
  /**
40
46
  * Load common React libraries and UI frameworks
@@ -43,6 +49,15 @@ export declare class ScriptLoaderService implements OnDestroy {
43
49
  * @param options Optional options including debug flag
44
50
  * @returns Promise resolving to React ecosystem objects
45
51
  */
52
+ LoadReactEcosystem(config?: LibraryConfiguration, additionalLibraries?: ExternalLibraryConfig[], options?: {
53
+ debug?: boolean;
54
+ }): Promise<{
55
+ React: any;
56
+ ReactDOM: any;
57
+ Babel: any;
58
+ libraries: any;
59
+ }>;
60
+ /** @deprecated Use {@link LoadReactEcosystem}. */
46
61
  loadReactEcosystem(config?: LibraryConfiguration, additionalLibraries?: ExternalLibraryConfig[], options?: {
47
62
  debug?: boolean;
48
63
  }): Promise<{
@@ -61,6 +76,8 @@ export declare class ScriptLoaderService implements OnDestroy {
61
76
  * Remove a specific loaded resource
62
77
  * @param url - URL of resource to remove
63
78
  */
79
+ RemoveResource(url: string): void;
80
+ /** @deprecated Use {@link RemoveResource}. */
64
81
  removeResource(url: string): void;
65
82
  /**
66
83
  * Clean up all resources marked for auto-cleanup
@@ -25,7 +25,7 @@ export class ScriptLoaderService {
25
25
  * @param autoCleanup - Whether to cleanup on service destroy
26
26
  * @returns Promise resolving to the global object
27
27
  */
28
- async loadScript(url, globalName, autoCleanup = false) {
28
+ async LoadScript(url, globalName, autoCleanup = false) {
29
29
  const existing = this.loadedResources.get(url);
30
30
  if (existing) {
31
31
  return existing.promise;
@@ -40,6 +40,10 @@ export class ScriptLoaderService {
40
40
  }
41
41
  return promise;
42
42
  }
43
+ /** @deprecated Use {@link LoadScript}. */
44
+ async loadScript(url, globalName, autoCleanup = false) {
45
+ return this.LoadScript(url, globalName, autoCleanup);
46
+ }
43
47
  /**
44
48
  * Load a script with additional validation function
45
49
  * @param url - Script URL to load
@@ -48,7 +52,7 @@ export class ScriptLoaderService {
48
52
  * @param autoCleanup - Whether to cleanup on service destroy
49
53
  * @returns Promise resolving to the validated global object
50
54
  */
51
- async loadScriptWithValidation(url, globalName, validator, autoCleanup = false) {
55
+ async LoadScriptWithValidation(url, globalName, validator, autoCleanup = false) {
52
56
  const existing = this.loadedResources.get(url);
53
57
  if (existing) {
54
58
  const obj = await existing.promise;
@@ -68,11 +72,15 @@ export class ScriptLoaderService {
68
72
  }
69
73
  return promise;
70
74
  }
75
+ /** @deprecated Use {@link LoadScriptWithValidation}. */
76
+ async loadScriptWithValidation(url, globalName, validator, autoCleanup = false) {
77
+ return this.LoadScriptWithValidation(url, globalName, validator, autoCleanup);
78
+ }
71
79
  /**
72
80
  * Load CSS from URL
73
81
  * @param url - CSS URL to load
74
82
  */
75
- loadCSS(url) {
83
+ LoadCSS(url) {
76
84
  if (this.loadedResources.has(url)) {
77
85
  return;
78
86
  }
@@ -89,6 +97,10 @@ export class ScriptLoaderService {
89
97
  promise: Promise.resolve()
90
98
  });
91
99
  }
100
+ /** @deprecated Use {@link LoadCSS}. */
101
+ loadCSS(url) {
102
+ return this.LoadCSS(url);
103
+ }
92
104
  /**
93
105
  * Load common React libraries and UI frameworks
94
106
  * @param config Optional library configuration
@@ -96,7 +108,7 @@ export class ScriptLoaderService {
96
108
  * @param options Optional options including debug flag
97
109
  * @returns Promise resolving to React ecosystem objects
98
110
  */
99
- async loadReactEcosystem(config, additionalLibraries, options) {
111
+ async LoadReactEcosystem(config, additionalLibraries, options) {
100
112
  // Use the new LibraryLoader from react-runtime for consistency
101
113
  const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries, options);
102
114
  // The LibraryLoader handles all the loading, but we need to ensure
@@ -108,6 +120,10 @@ export class ScriptLoaderService {
108
120
  });
109
121
  return result;
110
122
  }
123
+ /** @deprecated Use {@link LoadReactEcosystem}. */
124
+ async loadReactEcosystem(config, additionalLibraries, options) {
125
+ return this.LoadReactEcosystem(config, additionalLibraries, options);
126
+ }
111
127
  /**
112
128
  * Get library name from URL for global variable mapping
113
129
  * @param url - Library URL
@@ -141,7 +157,7 @@ export class ScriptLoaderService {
141
157
  * Remove a specific loaded resource
142
158
  * @param url - URL of resource to remove
143
159
  */
144
- removeResource(url) {
160
+ RemoveResource(url) {
145
161
  const resource = this.loadedResources.get(url);
146
162
  if (resource?.element && resource.element.parentNode) {
147
163
  resource.element.parentNode.removeChild(resource.element);
@@ -149,12 +165,16 @@ export class ScriptLoaderService {
149
165
  this.loadedResources.delete(url);
150
166
  this.cleanupOnDestroy.delete(url);
151
167
  }
168
+ /** @deprecated Use {@link RemoveResource}. */
169
+ removeResource(url) {
170
+ return this.RemoveResource(url);
171
+ }
152
172
  /**
153
173
  * Clean up all resources marked for auto-cleanup
154
174
  */
155
175
  cleanup() {
156
176
  for (const url of this.cleanupOnDestroy) {
157
- this.removeResource(url);
177
+ this.RemoveResource(url);
158
178
  }
159
179
  this.cleanupOnDestroy.clear();
160
180
  }
@@ -1 +1 @@
1
- {"version":3,"file":"script-loader.service.js","sourceRoot":"","sources":["../../../src/lib/services/script-loader.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EACL,aAAa,EAGd,MAAM,+BAA+B,CAAC;;AAUvC;;;GAGG;AAEH,MAAM,OAAO,mBAAmB;IADhC;QAEU,oBAAe,GAAG,IAAI,GAAG,EAAwB,CAAC;QACzC,qBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;KAoYvD;IAlYC,WAAW;QACT,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CAAC,GAAW,EAAE,UAAkB,EAAE,WAAW,GAAG,KAAK;QACnE,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/C,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC,OAAO,CAAC;QAC1B,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,mBAAmB,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;QAC1D,MAAM,OAAO,GAAG,QAAQ,CAAC,aAAa,CAAC,eAAe,GAAG,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E,WAAW,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACK,+BAA+B,CACrC,MAAyB,EACzB,UAAkB,EAClB,SAAgC,EAChC,OAA6B,EAC7B,MAA6B;QAE7B,MAAM,WAAW,GAAG,GAAG,EAAE;YACvB,IAAI,CAAC,iBAAiB,CAAC,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QACjE,CAAC,CAAC;QAEF,IAAI,YAAY,IAAI,MAAM,EAAE,CAAC;YAC3B,aAAa;YACZ,MAAc,CAAC,kBAAkB,GAAG,GAAG,EAAE;gBACxC,IAAK,MAAc,CAAC,UAAU,KAAK,QAAQ,IAAK,MAAc,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;oBACxF,MAAc,CAAC,kBAAkB,GAAG,IAAI,CAAC;oBAC1C,WAAW,EAAE,CAAC;gBAChB,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,kBAAkB;YAClB,MAAM,WAAW,GAAG,GAAG,EAAE;gBACvB,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;gBAChD,WAAW,EAAE,CAAC;YAChB,CAAC,CAAC;YACF,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;oHArYU,mBAAmB;uEAAnB,mBAAmB,WAAnB,mBAAmB,mBADN,MAAM;;iFACnB,mBAAmB;cAD/B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service for loading external scripts and CSS in Angular applications.\n * Manages the lifecycle of dynamically loaded resources with proper cleanup.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { \n LibraryLoader,\n LibraryConfiguration,\n ExternalLibraryConfig\n} from '@memberjunction/react-runtime';\n\n/**\n * Represents a loaded script or CSS resource\n */\ninterface LoadedScript {\n element: HTMLScriptElement | HTMLLinkElement;\n promise: Promise<any>;\n}\n\n/**\n * Service for loading external scripts and CSS with proper cleanup.\n * Provides methods to dynamically load React and related libraries from CDN.\n */\n@Injectable({ providedIn: 'root' })\nexport class ScriptLoaderService implements OnDestroy {\n private loadedResources = new Map<string, LoadedScript>();\n private readonly cleanupOnDestroy = new Set<string>();\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Load a script from URL with automatic cleanup tracking\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the global object\n */\n async loadScript(url: string, globalName: string, autoCleanup = false): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n return existing.promise;\n }\n\n const promise = this.createScriptPromise(url, globalName);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /**\n * Load a script with additional validation function\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param validator - Function to validate the loaded object\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the validated global object\n */\n async loadScriptWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean,\n autoCleanup = false\n ): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n const obj = await existing.promise;\n // Re-validate even for cached resources\n if (!validator(obj)) {\n throw new Error(`${globalName} loaded but failed validation`);\n }\n return obj;\n }\n\n const promise = this.createScriptPromiseWithValidation(url, globalName, validator);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /**\n * Load CSS from URL\n * @param url - CSS URL to load\n */\n loadCSS(url: string): void {\n if (this.loadedResources.has(url)) {\n return;\n }\n\n const existingLink = document.querySelector(`link[href=\"${url}\"]`);\n if (existingLink) {\n return;\n }\n\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = url;\n document.head.appendChild(link);\n\n this.loadedResources.set(url, {\n element: link,\n promise: Promise.resolve()\n });\n }\n\n /**\n * Load common React libraries and UI frameworks\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 to React ecosystem objects\n */\n async loadReactEcosystem(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<{\n React: any;\n ReactDOM: any;\n Babel: any;\n libraries: any;\n }> {\n // Use the new LibraryLoader from react-runtime for consistency\n const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries, options);\n \n // The LibraryLoader handles all the loading, but we need to ensure\n // ReactDOM.createRoot is available for Angular's specific needs\n // The ReactBridgeService will handle the delayed validation\n \n // Track loaded resources for cleanup\n LibraryLoader.getLoadedResources().forEach((resource, url) => {\n this.loadedResources.set(url, resource);\n });\n \n return result;\n }\n\n /**\n * Get library name from URL for global variable mapping\n * @param url - Library URL\n * @returns Global variable name\n */\n private getLibraryNameFromUrl(url: string): string {\n // Map known URLs to their global variable names\n if (url.includes('lodash')) return '_';\n if (url.includes('d3')) return 'd3';\n if (url.includes('Chart.js') || url.includes('chart')) return 'Chart';\n if (url.includes('dayjs')) return 'dayjs';\n if (url.includes('antd')) return 'antd';\n if (url.includes('react-bootstrap')) return 'ReactBootstrap';\n if (url.includes('react-dom')) return 'ReactDOM';\n if (url.includes('react')) return 'React';\n if (url.includes('babel')) return 'Babel';\n \n // Default: extract library name from filename\n const match = url.match(/\\/([^/]+?)(?:\\.min)?\\.js$/i);\n return match ? match[1] : 'UnknownLibrary';\n }\n\n /**\n * Remove a specific loaded resource\n * @param url - URL of resource to remove\n */\n removeResource(url: string): void {\n const resource = this.loadedResources.get(url);\n if (resource?.element && resource.element.parentNode) {\n resource.element.parentNode.removeChild(resource.element);\n }\n this.loadedResources.delete(url);\n this.cleanupOnDestroy.delete(url);\n }\n\n /**\n * Clean up all resources marked for auto-cleanup\n */\n private cleanup(): void {\n for (const url of this.cleanupOnDestroy) {\n this.removeResource(url);\n }\n this.cleanupOnDestroy.clear();\n }\n\n /**\n * Create a promise that resolves when script loads\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @returns Promise resolving to global object\n */\n private createScriptPromise(url: string, globalName: string): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoad(existingScript as HTMLScriptElement, globalName, resolve, reject);\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n const global = (window as any)[globalName];\n if (global) {\n resolve(global);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Create a promise that resolves when script loads and passes validation\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @returns Promise resolving to validated global object\n */\n private createScriptPromiseWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded and valid\n const existingGlobal = (window as any)[globalName];\n if (existingGlobal && validator(existingGlobal)) {\n resolve(existingGlobal);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoadWithValidation(\n existingScript as HTMLScriptElement, \n globalName, \n validator,\n resolve, \n reject\n );\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Wait for global object to be available and valid\n * @param globalName - Global variable name\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n * @param attempts - Current attempt number\n * @param maxAttempts - Maximum attempts before failing\n */\n private waitForValidation(\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void,\n attempts = 0,\n maxAttempts = 50 // 5 seconds total with 100ms intervals\n ): void {\n const global = (window as any)[globalName];\n \n if (global && validator(global)) {\n resolve(global);\n return;\n }\n\n if (attempts >= maxAttempts) {\n if (global) {\n reject(new Error(`${globalName} loaded but validation failed after ${maxAttempts} attempts`));\n } else {\n reject(new Error(`${globalName} not found after ${maxAttempts} attempts`));\n }\n return;\n }\n\n // Retry with exponential backoff for first few attempts, then fixed interval\n const delay = attempts < 5 ? Math.min(100 * Math.pow(1.5, attempts), 500) : 100;\n setTimeout(() => {\n this.waitForValidation(globalName, validator, resolve, reject, attempts + 1, maxAttempts);\n }, delay);\n }\n\n /**\n * Wait for existing script to load\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoad(\n script: HTMLScriptElement,\n globalName: string,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n // Give it a moment for the global to be defined\n setTimeout(() => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n }, 100);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n\n /**\n * Wait for existing script to load with validation\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoadWithValidation(\n script: HTMLScriptElement,\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n}"]}
1
+ {"version":3,"file":"script-loader.service.js","sourceRoot":"","sources":["../../../src/lib/services/script-loader.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EACL,aAAa,EAGd,MAAM,+BAA+B,CAAC;;AAUvC;;;GAGG;AAEH,MAAM,OAAO,mBAAmB;IADhC;QAEU,oBAAe,GAAG,IAAI,GAAG,EAAwB,CAAC;QACzC,qBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;KA2avD;IAzaC,WAAW;QACT,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CAAC,GAAW,EAAE,UAAkB,EAAE,WAAW,GAAG,KAAK;QACnE,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/C,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC,OAAO,CAAC;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,IAAI,MAAM,EAAE,CAAC;YAC3B,aAAa;YACZ,MAAc,CAAC,kBAAkB,GAAG,GAAG,EAAE;gBACxC,IAAK,MAAc,CAAC,UAAU,KAAK,QAAQ,IAAK,MAAc,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;oBACxF,MAAc,CAAC,kBAAkB,GAAG,IAAI,CAAC;oBAC1C,WAAW,EAAE,CAAC;gBAChB,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,kBAAkB;YAClB,MAAM,WAAW,GAAG,GAAG,EAAE;gBACvB,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;gBAChD,WAAW,EAAE,CAAC;YAChB,CAAC,CAAC;YACF,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;oHA5aU,mBAAmB;uEAAnB,mBAAmB,WAAnB,mBAAmB,mBADN,MAAM;;iFACnB,mBAAmB;cAD/B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service for loading external scripts and CSS in Angular applications.\n * Manages the lifecycle of dynamically loaded resources with proper cleanup.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { \n LibraryLoader,\n LibraryConfiguration,\n ExternalLibraryConfig\n} from '@memberjunction/react-runtime';\n\n/**\n * Represents a loaded script or CSS resource\n */\ninterface LoadedScript {\n element: HTMLScriptElement | HTMLLinkElement;\n promise: Promise<any>;\n}\n\n/**\n * Service for loading external scripts and CSS with proper cleanup.\n * Provides methods to dynamically load React and related libraries from CDN.\n */\n@Injectable({ providedIn: 'root' })\nexport class ScriptLoaderService implements OnDestroy {\n private loadedResources = new Map<string, LoadedScript>();\n private readonly cleanupOnDestroy = new Set<string>();\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Load a script from URL with automatic cleanup tracking\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the global object\n */\n async LoadScript(url: string, globalName: string, autoCleanup = false): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n return existing.promise;\n }\n\n const promise = this.createScriptPromise(url, globalName);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /** @deprecated Use {@link LoadScript}. */\n async loadScript(url: string, globalName: string, autoCleanup = false): Promise<any> {\n return this.LoadScript(url, globalName, autoCleanup);\n }\n\n /**\n * Load a script with additional validation function\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param validator - Function to validate the loaded object\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the validated global object\n */\n async LoadScriptWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean,\n autoCleanup = false\n ): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n const obj = await existing.promise;\n // Re-validate even for cached resources\n if (!validator(obj)) {\n throw new Error(`${globalName} loaded but failed validation`);\n }\n return obj;\n }\n\n const promise = this.createScriptPromiseWithValidation(url, globalName, validator);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /** @deprecated Use {@link LoadScriptWithValidation}. */\n async loadScriptWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean,\n autoCleanup = false\n ): Promise<any> {\n return this.LoadScriptWithValidation(url, globalName, validator, autoCleanup);\n }\n\n /**\n * Load CSS from URL\n * @param url - CSS URL to load\n */\n LoadCSS(url: string): void {\n if (this.loadedResources.has(url)) {\n return;\n }\n\n const existingLink = document.querySelector(`link[href=\"${url}\"]`);\n if (existingLink) {\n return;\n }\n\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = url;\n document.head.appendChild(link);\n\n this.loadedResources.set(url, {\n element: link,\n promise: Promise.resolve()\n });\n }\n\n /** @deprecated Use {@link LoadCSS}. */\n loadCSS(url: string): void {\n return this.LoadCSS(url);\n }\n\n /**\n * Load common React libraries and UI frameworks\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 to React ecosystem objects\n */\n async LoadReactEcosystem(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<{\n React: any;\n ReactDOM: any;\n Babel: any;\n libraries: any;\n }> {\n // Use the new LibraryLoader from react-runtime for consistency\n const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries, options);\n \n // The LibraryLoader handles all the loading, but we need to ensure\n // ReactDOM.createRoot is available for Angular's specific needs\n // The ReactBridgeService will handle the delayed validation\n \n // Track loaded resources for cleanup\n LibraryLoader.getLoadedResources().forEach((resource, url) => {\n this.loadedResources.set(url, resource);\n });\n \n return result;\n }\n\n /** @deprecated Use {@link LoadReactEcosystem}. */\n async loadReactEcosystem(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<{\n React: any;\n ReactDOM: any;\n Babel: any;\n libraries: any;\n }> {\n return this.LoadReactEcosystem(config, additionalLibraries, options);\n }\n\n /**\n * Get library name from URL for global variable mapping\n * @param url - Library URL\n * @returns Global variable name\n */\n private getLibraryNameFromUrl(url: string): string {\n // Map known URLs to their global variable names\n if (url.includes('lodash')) return '_';\n if (url.includes('d3')) return 'd3';\n if (url.includes('Chart.js') || url.includes('chart')) return 'Chart';\n if (url.includes('dayjs')) return 'dayjs';\n if (url.includes('antd')) return 'antd';\n if (url.includes('react-bootstrap')) return 'ReactBootstrap';\n if (url.includes('react-dom')) return 'ReactDOM';\n if (url.includes('react')) return 'React';\n if (url.includes('babel')) return 'Babel';\n \n // Default: extract library name from filename\n const match = url.match(/\\/([^/]+?)(?:\\.min)?\\.js$/i);\n return match ? match[1] : 'UnknownLibrary';\n }\n\n /**\n * Remove a specific loaded resource\n * @param url - URL of resource to remove\n */\n RemoveResource(url: string): void {\n const resource = this.loadedResources.get(url);\n if (resource?.element && resource.element.parentNode) {\n resource.element.parentNode.removeChild(resource.element);\n }\n this.loadedResources.delete(url);\n this.cleanupOnDestroy.delete(url);\n }\n\n /** @deprecated Use {@link RemoveResource}. */\n removeResource(url: string): void {\n return this.RemoveResource(url);\n }\n\n /**\n * Clean up all resources marked for auto-cleanup\n */\n private cleanup(): void {\n for (const url of this.cleanupOnDestroy) {\n this.RemoveResource(url);\n }\n this.cleanupOnDestroy.clear();\n }\n\n /**\n * Create a promise that resolves when script loads\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @returns Promise resolving to global object\n */\n private createScriptPromise(url: string, globalName: string): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoad(existingScript as HTMLScriptElement, globalName, resolve, reject);\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n const global = (window as any)[globalName];\n if (global) {\n resolve(global);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Create a promise that resolves when script loads and passes validation\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @returns Promise resolving to validated global object\n */\n private createScriptPromiseWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded and valid\n const existingGlobal = (window as any)[globalName];\n if (existingGlobal && validator(existingGlobal)) {\n resolve(existingGlobal);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoadWithValidation(\n existingScript as HTMLScriptElement, \n globalName, \n validator,\n resolve, \n reject\n );\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Wait for global object to be available and valid\n * @param globalName - Global variable name\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n * @param attempts - Current attempt number\n * @param maxAttempts - Maximum attempts before failing\n */\n private waitForValidation(\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void,\n attempts = 0,\n maxAttempts = 50 // 5 seconds total with 100ms intervals\n ): void {\n const global = (window as any)[globalName];\n \n if (global && validator(global)) {\n resolve(global);\n return;\n }\n\n if (attempts >= maxAttempts) {\n if (global) {\n reject(new Error(`${globalName} loaded but validation failed after ${maxAttempts} attempts`));\n } else {\n reject(new Error(`${globalName} not found after ${maxAttempts} attempts`));\n }\n return;\n }\n\n // Retry with exponential backoff for first few attempts, then fixed interval\n const delay = attempts < 5 ? Math.min(100 * Math.pow(1.5, attempts), 500) : 100;\n setTimeout(() => {\n this.waitForValidation(globalName, validator, resolve, reject, attempts + 1, maxAttempts);\n }, delay);\n }\n\n /**\n * Wait for existing script to load\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoad(\n script: HTMLScriptElement,\n globalName: string,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n // Give it a moment for the global to be defined\n setTimeout(() => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n }, 100);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n\n /**\n * Wait for existing script to load with validation\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoadWithValidation(\n script: HTMLScriptElement,\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n}"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memberjunction/ng-react",
3
- "version": "6.1.4",
3
+ "version": "6.2.0-edge.1",
4
4
  "description": "Angular components for hosting React components in MemberJunction applications",
5
5
  "repository": {
6
6
  "type": "git",
@@ -34,21 +34,21 @@
34
34
  "styles"
35
35
  ],
36
36
  "dependencies": {
37
- "@memberjunction/ai-vectors-memory": "6.1.4",
38
- "@memberjunction/core": "6.1.4",
39
- "@memberjunction/core-entities": "6.1.4",
40
- "@memberjunction/global": "6.1.4",
41
- "@memberjunction/graphql-dataprovider": "6.1.4",
42
- "@memberjunction/interactive-component-types": "6.1.4",
43
- "@memberjunction/ng-notifications": "6.1.4",
44
- "@memberjunction/react-runtime": "6.1.4",
37
+ "@memberjunction/ai-vectors-memory": "6.2.0-edge.1",
38
+ "@memberjunction/core": "6.2.0-edge.1",
39
+ "@memberjunction/core-entities": "6.2.0-edge.1",
40
+ "@memberjunction/global": "6.2.0-edge.1",
41
+ "@memberjunction/graphql-dataprovider": "6.2.0-edge.1",
42
+ "@memberjunction/interactive-component-types": "6.2.0-edge.1",
43
+ "@memberjunction/ng-notifications": "6.2.0-edge.1",
44
+ "@memberjunction/react-runtime": "6.2.0-edge.1",
45
45
  "@babel/standalone": "^7.29.1",
46
46
  "react": "^19.2.4",
47
47
  "react-dom": "^19.2.4",
48
48
  "rxjs": "^7.8.2",
49
49
  "@types/react": "^19.2.13",
50
50
  "@types/react-dom": "^19.2.3",
51
- "@memberjunction/ng-base-types": "6.1.4"
51
+ "@memberjunction/ng-base-types": "6.2.0-edge.1"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@angular/compiler": "21.2.22",
@@ -1 +0,0 @@
1
- export {};