@capillarytech/creatives-library 9.2.1-alpha.sprint-cap-214249.42 → 9.2.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 (51) hide show
  1. package/AppRoot.js +4 -7
  2. package/constants/unified.js +1 -0
  3. package/package.json +1 -1
  4. package/utils/beePluginLoader.js +106 -0
  5. package/utils/common.js +6 -0
  6. package/utils/createMobilePushPayload.js +51 -56
  7. package/utils/tests/beePluginLoader.test.js +199 -0
  8. package/utils/tests/createMobilePushPayload.test.js +10 -162
  9. package/v2Components/CapMpushCTA/index.js +57 -47
  10. package/v2Components/CapMpushCTA/index.scss +5 -43
  11. package/v2Components/CommonTestAndPreview/UnifiedPreview/MobilePushPreviewContent.js +8 -11
  12. package/v2Components/CommonTestAndPreview/UnifiedPreview/_unifiedPreview.scss +1 -13
  13. package/v2Components/CommonTestAndPreview/constants.js +0 -2
  14. package/v2Components/CommonTestAndPreview/index.js +10 -48
  15. package/v2Components/CommonTestAndPreview/tests/UnifiedPreview/MobilePushPreviewContent.test.js +5 -83
  16. package/v2Components/CommonTestAndPreview/tests/index.test.js +0 -86
  17. package/v2Components/TemplatePreview/_templatePreview.scss +2 -12
  18. package/v2Components/TemplatePreview/index.js +12 -14
  19. package/v2Components/TemplatePreview/tests/index.test.js +0 -69
  20. package/v2Containers/BeeEditor/index.js +49 -22
  21. package/v2Containers/BeeEditor/index.scss +12 -0
  22. package/v2Containers/BeeEditor/messages.js +8 -0
  23. package/v2Containers/BeeEditor/test/index.test.js +78 -0
  24. package/v2Containers/BeePopupEditor/index.js +22 -11
  25. package/v2Containers/CreativesContainer/SlideBoxContent.js +9 -5
  26. package/v2Containers/CreativesContainer/index.js +1 -2
  27. package/v2Containers/CreativesContainer/tests/SlideBoxContent.test.js +0 -43
  28. package/v2Containers/Email/index.js +2 -2
  29. package/v2Containers/EmailWrapper/hooks/useEmailWrapper.js +25 -23
  30. package/v2Containers/MobilePushNew/components/CtaButtons.js +47 -52
  31. package/v2Containers/MobilePushNew/components/MediaUploaders.js +222 -314
  32. package/v2Containers/MobilePushNew/components/PlatformContentFields.js +130 -161
  33. package/v2Containers/MobilePushNew/components/tests/CtaButtons.test.js +208 -30
  34. package/v2Containers/MobilePushNew/components/tests/MediaUploaders.test.js +123 -484
  35. package/v2Containers/MobilePushNew/components/tests/PlatformContentFields.test.js +46 -152
  36. package/v2Containers/MobilePushNew/constants.js +0 -12
  37. package/v2Containers/MobilePushNew/hooks/tests/usePlatformSync.test.js +1 -63
  38. package/v2Containers/MobilePushNew/hooks/tests/useUpload.test.js +0 -78
  39. package/v2Containers/MobilePushNew/hooks/usePlatformSync.js +1 -40
  40. package/v2Containers/MobilePushNew/hooks/useUpload.js +46 -42
  41. package/v2Containers/MobilePushNew/index.js +273 -503
  42. package/v2Containers/MobilePushNew/index.scss +4 -215
  43. package/v2Containers/MobilePushNew/messages.js +6 -106
  44. package/v2Containers/MobilePushNew/tests/index.test.js +1 -482
  45. package/v2Containers/MobilePushNew/tests/utils.test.js +0 -122
  46. package/v2Containers/MobilePushNew/utils.js +0 -107
  47. package/v2Containers/Templates/_templates.scss +2 -10
  48. package/v2Containers/Templates/index.js +81 -83
  49. package/v2Containers/Templates/tests/index.test.js +0 -68
  50. package/v2Components/CapMpushCTA/tests/index.test.js +0 -150
  51. package/v2Containers/MobilePushNew/components/TapLinkActions.js +0 -76
package/AppRoot.js CHANGED
@@ -14,6 +14,7 @@ import { translationMessages } from './i18n';
14
14
  import initialState from './initialState';
15
15
  import pathConfig from './config/path';
16
16
  import { isMFEMode } from './utils/mfeDetect';
17
+ import { loadBeePlugin } from './utils/beePluginLoader';
17
18
  import { emitFirstPaintReadyIfNotDataLanding } from './utils/mfeFirstPaintReady';
18
19
  import rebaseHistory from './utils/mfeHistory';
19
20
  import { MFEEventBus } from '@capillarytech/cap-ui-utils';
@@ -86,14 +87,10 @@ const AppRoot = ({ basename: _basename = '/creatives/ui', history: hostHistory }
86
87
  }
87
88
  }, []);
88
89
 
89
- // In MFE mode the HOST's index.html is served, not creatives' — so BeePlugin.js
90
- // (declared in creatives/index.html) is never loaded. Inject it here so BeeEditor works.
90
+ // Preload BeePlugin.js in MFE mode (host index.html lacks it); the editors also load it on demand
91
91
  useEffect(() => {
92
- if (isMFEMode() && !window.BeePlugin && !document.querySelector('script[src*="BeePlugin.js"]')) {
93
- const script = document.createElement('script');
94
- script.src = 'https://app-rsrc.getbee.io/plugin/BeePlugin.js';
95
- script.type = 'text/javascript';
96
- document.head.appendChild(script);
92
+ if (isMFEMode()) {
93
+ loadBeePlugin().catch(() => {});
97
94
  }
98
95
  }, []);
99
96
 
@@ -46,6 +46,7 @@ export const HOSPITALITY_BASED_SCOPE = 'HOSPITALITY_BASED_SCOPE';
46
46
  export const REGISTRATION_CUSTOM_FIELD = 'Registration custom fields';
47
47
  export const GIFT_CARDS = 'GIFT_CARDS';
48
48
  export const PROMO_ENGINE = 'PROMO_ENGINE';
49
+ export const ENABLE_NEW_MPUSH = 'ENABLE_NEW_MPUSH';
49
50
  export const ENABLE_NEW_EDITOR_FLOW_INAPP = 'ENABLE_NEW_EDITOR_FLOW_INAPP';
50
51
  // Per-channel flags for the FormBuilder V3 migration. Each routes its channel to
51
52
  // the new functional FormBuilder; later channels get their own flags (…_EMAIL).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capillarytech/creatives-library",
3
3
  "author": "meharaj",
4
- "version": "9.2.1-alpha.sprint-cap-214249.42",
4
+ "version": "9.2.1",
5
5
  "description": "Capillary creatives ui",
6
6
  "main": "./index.js",
7
7
  "module": "./index.es.js",
@@ -0,0 +1,106 @@
1
+ export const BEE_PLUGIN_SCRIPT_URL = 'https://app-rsrc.getbee.io/plugin/BeePlugin.js';
2
+ export const BEE_PLUGIN_LOAD_TIMEOUT_MS = 30000;
3
+
4
+ let beePluginPromise = null;
5
+
6
+ // Hosts consuming creatives as a library or MFE may not ship BeePlugin.js, so load it on demand
7
+ export const loadBeePlugin = () => {
8
+ if (window.BeePlugin) {
9
+ return Promise.resolve(window.BeePlugin);
10
+ }
11
+ if (beePluginPromise) {
12
+ return beePluginPromise;
13
+ }
14
+ beePluginPromise = new Promise((resolve, reject) => {
15
+ const existingScript = document.querySelector('script[src*="BeePlugin.js"]');
16
+ const script = existingScript || document.createElement('script');
17
+ let timeoutId = null;
18
+ const fail = (error) => {
19
+ clearTimeout(timeoutId);
20
+ beePluginPromise = null;
21
+ // Drop the tag so a retry injects a fresh one instead of waiting on a dead script
22
+ script.remove();
23
+ reject(error);
24
+ };
25
+ const onLoad = () => {
26
+ if (window.BeePlugin) {
27
+ clearTimeout(timeoutId);
28
+ resolve(window.BeePlugin);
29
+ return;
30
+ }
31
+ fail(new Error('BeePlugin.js loaded but window.BeePlugin is undefined'));
32
+ };
33
+ const onError = () => fail(new Error(`Failed to load ${BEE_PLUGIN_SCRIPT_URL}`));
34
+ timeoutId = setTimeout(
35
+ () => fail(new Error(`Timed out loading ${BEE_PLUGIN_SCRIPT_URL}`)),
36
+ BEE_PLUGIN_LOAD_TIMEOUT_MS,
37
+ );
38
+ script.addEventListener('load', onLoad, { once: true });
39
+ script.addEventListener('error', onError, { once: true });
40
+ if (!existingScript) {
41
+ script.src = BEE_PLUGIN_SCRIPT_URL;
42
+ script.type = 'text/javascript';
43
+ script.async = true;
44
+ document.head.appendChild(script);
45
+ }
46
+ });
47
+ return beePluginPromise;
48
+ };
49
+
50
+ // Tears down an editor that will not be used; destroy can throw if BEE never finished mounting
51
+ export const destroyBeeInstance = (instance) => {
52
+ try {
53
+ if (typeof instance?.destroy === 'function') {
54
+ instance.destroy();
55
+ }
56
+ } catch (error) {
57
+ console.warn('[beePluginLoader] Error destroying BEE plugin:', error);
58
+ }
59
+ };
60
+
61
+ // Creates a BEE editor and starts it with the template JSON (string or object) returned by getBeeJson
62
+ export const startBeePlugin = (BeePlugin, {
63
+ tokenData, beeConfig, getBeeJson, isCancelled = () => false,
64
+ }) => new Promise((resolve, reject) => {
65
+ BeePlugin.create(tokenData, beeConfig, (instance) => {
66
+ // create calls back asynchronously; never start an obsolete editor into the shared container
67
+ if (isCancelled()) {
68
+ destroyBeeInstance(instance);
69
+ resolve(null);
70
+ return;
71
+ }
72
+ try {
73
+ const beeJson = getBeeJson();
74
+ instance.start(typeof beeJson === 'string' ? JSON.parse(beeJson) : beeJson);
75
+ resolve(instance);
76
+ } catch (error) {
77
+ destroyBeeInstance(instance);
78
+ reject(error);
79
+ }
80
+ });
81
+ });
82
+
83
+ // Loads BeePlugin.js and starts the editor; resolves null when the caller was cleaned up in the meantime
84
+ export const initBeeEditor = ({
85
+ tokenData,
86
+ beeConfig,
87
+ getBeeJson,
88
+ isCancelled,
89
+ onPluginLoaded = () => {},
90
+ }) => loadBeePlugin()
91
+ .then((BeePlugin) => {
92
+ if (isCancelled()) {
93
+ return null;
94
+ }
95
+ onPluginLoaded();
96
+ return startBeePlugin(BeePlugin, {
97
+ tokenData, beeConfig, getBeeJson, isCancelled,
98
+ });
99
+ })
100
+ .then((instance) => {
101
+ if (instance && isCancelled()) {
102
+ destroyBeeInstance(instance);
103
+ return null;
104
+ }
105
+ return instance;
106
+ });
package/utils/common.js CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  ENABLE_WECHAT,
25
25
  ENABLE_WEBPUSH,
26
26
  SUPPORT_CK_EDITOR,
27
+ ENABLE_NEW_MPUSH,
27
28
  ENABLE_NEW_EDITOR_FLOW_INAPP,
28
29
  ENABLE_NEW_FORMBUILDER_SMS,
29
30
  ENABLE_NEW_FORMBUILDER_MPUSH,
@@ -143,6 +144,11 @@ export const isEmailUnsubscribeTagOptional = Auth.hasFeatureAccess.bind(
143
144
  EMAIL_UNSUBSCRIBE_TAG_MANDATORY,
144
145
  );
145
146
 
147
+ export const hasNewMobilePushFeatureEnabled = Auth.hasFeatureAccess.bind(
148
+ null,
149
+ ENABLE_NEW_MPUSH,
150
+ );
151
+
146
152
  export const hasNewEditorFlowInAppEnabled = Auth.hasFeatureAccess.bind(
147
153
  null,
148
154
  ENABLE_NEW_EDITOR_FLOW_INAPP,
@@ -11,7 +11,6 @@ import {
11
11
  TEXT,
12
12
  } from "../v2Containers/MobilePushNew/constants";
13
13
  import messages from '../v2Containers/MobilePushNew/messages';
14
- import { appendDeepLinkParams } from '../v2Containers/MobilePushNew/utils';
15
14
 
16
15
  /**
17
16
  * Constructs the payload for Mobile Push, supporting both legacy and rich media as per backend contract.
@@ -28,7 +27,6 @@ import { appendDeepLinkParams } from '../v2Containers/MobilePushNew/utils';
28
27
  * @param {Object} params.accountData - Account data for the payload
29
28
  * @param {boolean} params.sameContent - Whether content is shared between platforms
30
29
  * @param {Object} params.options - Additional options
31
- * @param {string} [params.options.skipPlatform] - ANDROID or IOS: leave out a supported platform the user chose not to configure
32
30
  * @param {Object} params.intl - Internationalization object for messages
33
31
  */
34
32
  const createMobilePushPayload = ({
@@ -43,8 +41,8 @@ const createMobilePushPayload = ({
43
41
  intl,
44
42
  }) => {
45
43
  // Platform support checks must be at the top
46
- const isAndroidSupported = accountData?.configs?.android === '1' && options?.skipPlatform !== ANDROID;
47
- const isIosSupported = accountData?.configs?.ios === '1' && options?.skipPlatform !== IOS;
44
+ const isAndroidSupported = accountData?.configs?.android === '1';
45
+ const isIosSupported = accountData?.configs?.ios === '1';
48
46
 
49
47
  const {
50
48
  accountId: accountIdFromAccountData, id, licenseCode: licenseCodeFromAccountData, sourceAccountIdentifier, sourceType: sourceTypeFromAccountData, sourceTypeName,
@@ -123,47 +121,6 @@ const createMobilePushPayload = ({
123
121
  return payload;
124
122
  };
125
123
 
126
- /**
127
- * Carousel cards as Save sends them (also used by the Test & Preview payload)
128
- * @param {Array} carouselData - Editor carousel cards
129
- * @returns {Array} Cards with deep link keys appended to button links
130
- */
131
- export function buildCarouselCards(carouselData = []) {
132
- return (carouselData || []).map((card) => {
133
- const {
134
- mediaType,
135
- imageUrl,
136
- videoSrc,
137
- videoPreviewImg,
138
- buttons,
139
- } = card || {};
140
-
141
- return {
142
- mediaType: mediaType || IMAGE.toLowerCase(),
143
- imageUrl: imageUrl || '',
144
- videoSrc: videoSrc || '',
145
- // Thumbnail, so the phone preview can show the video card when editing
146
- ...(videoPreviewImg && { videoPreviewImg }),
147
- buttons: buttons ? buttons.map((button) => {
148
- if (!button) return button;
149
- // isSaved is the editor's own Save state; it doesn't go to the backend
150
- const { isSaved, ...buttonData } = button;
151
- const { linkType: buttonLinkType, deepLinkKeys, deepLinkValue: buttonDeepLinkValue } = buttonData;
152
- if (buttonLinkType === DEEP_LINK && deepLinkKeys && buttonDeepLinkValue) {
153
- const deepLinkKeysArray = Array.isArray(deepLinkKeys) ? deepLinkKeys : [deepLinkKeys];
154
- const updatedDeepLinkValue = appendDeepLinkKeysToUrl(buttonDeepLinkValue, deepLinkKeysArray);
155
-
156
- return {
157
- ...buttonData,
158
- deepLinkValue: updatedDeepLinkValue,
159
- };
160
- }
161
- return buttonData;
162
- }) : [],
163
- };
164
- });
165
- }
166
-
167
124
  /**
168
125
  * Builds platform-specific content for the payload
169
126
  * @param {Object} content - Platform content (Android/iOS)
@@ -172,7 +129,7 @@ export function buildCarouselCards(carouselData = []) {
172
129
  * @param {string} platform - Platform (ANDROID/IOS)
173
130
  * @returns {Object} Platform-specific content
174
131
  */
175
- export function buildPlatformContent(content, imageSrc, mpushVideoSrcAndPreview, platform) {
132
+ function buildPlatformContent(content, imageSrc, mpushVideoSrcAndPreview, platform) {
176
133
  const {
177
134
  title = '',
178
135
  message = '',
@@ -196,7 +153,13 @@ export function buildPlatformContent(content, imageSrc, mpushVideoSrcAndPreview,
196
153
  let finalDeepLinkValue = deepLinkValue;
197
154
 
198
155
  if (linkType === DEEP_LINK && deepLinkKeysValue?.length > 0) {
199
- finalDeepLinkValue = appendDeepLinkKeysToUrl(deepLinkValue, deepLinkKeysValue);
156
+ // Check if the URL already contains the keys
157
+ const urlHasKeys = deepLinkKeysValue?.some((key) => deepLinkValue?.includes(`${key}=${key}`));
158
+
159
+ // Only append keys if they're not already in the URL
160
+ if (!urlHasKeys) {
161
+ finalDeepLinkValue = appendDeepLinkKeysToUrl(deepLinkValue, deepLinkKeysValue);
162
+ }
200
163
  }
201
164
 
202
165
  platformContent.cta = {
@@ -221,8 +184,7 @@ export function buildPlatformContent(content, imageSrc, mpushVideoSrcAndPreview,
221
184
  platformContent.expandableDetails.style = VIDEO;
222
185
  platformContent.expandableDetails.message = message;
223
186
  platformContent.expandableDetails.media = [{
224
- // This platform's own video; mpushVideoSrcAndPreview is shared by both tabs
225
- url: content?.videoSrc || content?.mediaList?.[0]?.url || '',
187
+ url: mpushVideoSrcAndPreview.mpushVideoSrc || (content?.mediaList?.[0]?.url || ''),
226
188
  text: content?.mediaList?.[0]?.text || '',
227
189
  type: VIDEO,
228
190
  }];
@@ -239,11 +201,11 @@ export function buildPlatformContent(content, imageSrc, mpushVideoSrcAndPreview,
239
201
  type: type.toLowerCase(),
240
202
  }];
241
203
  } else {
242
- // No mediaList: use this platform's own GIF
204
+ // If no mediaList but mpushVideoSrc exists
243
205
  platformContent.expandableDetails.style = GIF;
244
206
  platformContent.expandableDetails.message = message;
245
207
  platformContent.expandableDetails.media = [{
246
- url: content?.videoSrc || '',
208
+ url: mpushVideoSrcAndPreview.mpushVideoSrc,
247
209
  text: '',
248
210
  type: GIF, // Backend expects GIF type for GIFs
249
211
  }];
@@ -256,7 +218,33 @@ export function buildPlatformContent(content, imageSrc, mpushVideoSrcAndPreview,
256
218
 
257
219
  // Handle carouselData
258
220
  if (content?.carouselData?.length > 0) {
259
- platformContent.expandableDetails.carouselData = buildCarouselCards(content.carouselData);
221
+ platformContent.expandableDetails.carouselData = content.carouselData.map((card) => {
222
+ const {
223
+ mediaType,
224
+ imageUrl,
225
+ videoSrc,
226
+ buttons,
227
+ } = card || {};
228
+
229
+ return {
230
+ mediaType: mediaType || IMAGE.toLowerCase(),
231
+ imageUrl: imageUrl || '',
232
+ videoSrc: videoSrc || '',
233
+ buttons: buttons ? buttons.map((button) => {
234
+ const { linkType: buttonLinkType, deepLinkKeys, deepLinkValue: buttonDeepLinkValue } = button || {};
235
+ if (buttonLinkType === DEEP_LINK && deepLinkKeys && buttonDeepLinkValue) {
236
+ const deepLinkKeysArray = Array.isArray(deepLinkKeys) ? deepLinkKeys : [deepLinkKeys];
237
+ const updatedDeepLinkValue = appendDeepLinkKeysToUrl(buttonDeepLinkValue, deepLinkKeysArray);
238
+
239
+ return {
240
+ ...button,
241
+ deepLinkValue: updatedDeepLinkValue,
242
+ };
243
+ }
244
+ return button;
245
+ }) : [],
246
+ };
247
+ });
260
248
  }
261
249
 
262
250
  // Handle mediaList
@@ -317,14 +305,21 @@ function buildCustomFields(content) {
317
305
  }
318
306
 
319
307
  /**
320
- * Appends deep link params to URL
308
+ * Appends deep link keys to URL
321
309
  * @param {string} url - Base URL
322
- * @param {Array} keys - "key=value" entries (an old entry without "=" means key=key)
323
- * @returns {string} URL with the params
310
+ * @param {Array} keys - Deep link keys
311
+ * @returns {string} URL with appended keys
324
312
  */
325
313
  export function appendDeepLinkKeysToUrl(url, keys) {
326
314
  if (!url || !keys || !Array.isArray(keys) || keys?.length === 0) return url;
327
- return appendDeepLinkParams(url, keys);
315
+
316
+ const separator = url.includes('?') ? '&' : '?';
317
+ const validKeys = keys.filter((key) => typeof key === 'string' && key?.length > 0);
318
+ if (validKeys?.length === 0) return url;
319
+
320
+ const keyParams = validKeys.map((key) => `${key}=${key}`).join('&');
321
+
322
+ return `${url}${separator}${keyParams}`;
328
323
  }
329
324
 
330
325
  export default createMobilePushPayload;
@@ -0,0 +1,199 @@
1
+ const SCRIPT_SELECTOR = 'script[src*="BeePlugin.js"]';
2
+
3
+ const getLoader = () => {
4
+ let loader;
5
+ jest.isolateModules(() => {
6
+ // Fresh module per test so the cached script promise does not leak between tests
7
+ // eslint-disable-next-line global-require
8
+ loader = require('../beePluginLoader');
9
+ });
10
+ return loader;
11
+ };
12
+
13
+ describe('loadBeePlugin', () => {
14
+ const mockBeePlugin = { create: jest.fn() };
15
+
16
+ beforeEach(() => {
17
+ delete window.BeePlugin;
18
+ document.head.innerHTML = '';
19
+ });
20
+
21
+ afterEach(() => {
22
+ jest.useRealTimers();
23
+ delete window.BeePlugin;
24
+ });
25
+
26
+ it('resolves immediately without injecting a script when BeePlugin is already loaded', async () => {
27
+ window.BeePlugin = mockBeePlugin;
28
+ const { loadBeePlugin } = getLoader();
29
+ await expect(loadBeePlugin()).resolves.toBe(mockBeePlugin);
30
+ expect(document.querySelector(SCRIPT_SELECTOR)).toBeNull();
31
+ });
32
+
33
+ it('injects the script once and resolves when it loads', async () => {
34
+ const { loadBeePlugin, BEE_PLUGIN_SCRIPT_URL } = getLoader();
35
+ const firstLoad = loadBeePlugin();
36
+ const secondLoad = loadBeePlugin();
37
+ const scripts = document.querySelectorAll(SCRIPT_SELECTOR);
38
+ expect(scripts).toHaveLength(1);
39
+ expect(scripts[0].src).toBe(BEE_PLUGIN_SCRIPT_URL);
40
+ expect(secondLoad).toBe(firstLoad);
41
+ window.BeePlugin = mockBeePlugin;
42
+ scripts[0].dispatchEvent(new Event('load'));
43
+ await expect(firstLoad).resolves.toBe(mockBeePlugin);
44
+ });
45
+
46
+ it('waits on a host-provided script instead of injecting another', async () => {
47
+ const hostScript = document.createElement('script');
48
+ hostScript.src = 'https://app-rsrc.getbee.io/plugin/BeePlugin.js';
49
+ document.head.appendChild(hostScript);
50
+ const { loadBeePlugin } = getLoader();
51
+ const load = loadBeePlugin();
52
+ expect(document.querySelectorAll(SCRIPT_SELECTOR)).toHaveLength(1);
53
+ window.BeePlugin = mockBeePlugin;
54
+ hostScript.dispatchEvent(new Event('load'));
55
+ await expect(load).resolves.toBe(mockBeePlugin);
56
+ });
57
+
58
+ it('rejects on script error, removes the tag and allows a retry', async () => {
59
+ const { loadBeePlugin } = getLoader();
60
+ const failedLoad = loadBeePlugin();
61
+ document.querySelector(SCRIPT_SELECTOR).dispatchEvent(new Event('error'));
62
+ await expect(failedLoad).rejects.toThrow('Failed to load');
63
+ expect(document.querySelector(SCRIPT_SELECTOR)).toBeNull();
64
+
65
+ const retryLoad = loadBeePlugin();
66
+ expect(retryLoad).not.toBe(failedLoad);
67
+ window.BeePlugin = mockBeePlugin;
68
+ document.querySelector(SCRIPT_SELECTOR).dispatchEvent(new Event('load'));
69
+ await expect(retryLoad).resolves.toBe(mockBeePlugin);
70
+ });
71
+
72
+ it('rejects when the script loads but does not define BeePlugin', async () => {
73
+ const { loadBeePlugin } = getLoader();
74
+ const load = loadBeePlugin();
75
+ document.querySelector(SCRIPT_SELECTOR).dispatchEvent(new Event('load'));
76
+ await expect(load).rejects.toThrow('window.BeePlugin is undefined');
77
+ });
78
+
79
+ it('rejects after the timeout when the script never settles', async () => {
80
+ jest.useFakeTimers();
81
+ const { loadBeePlugin, BEE_PLUGIN_LOAD_TIMEOUT_MS } = getLoader();
82
+ const load = loadBeePlugin();
83
+ jest.advanceTimersByTime(BEE_PLUGIN_LOAD_TIMEOUT_MS);
84
+ await expect(load).rejects.toThrow('Timed out');
85
+ expect(document.querySelector(SCRIPT_SELECTOR)).toBeNull();
86
+ });
87
+ });
88
+
89
+ describe('startBeePlugin', () => {
90
+ const tokenData = { access_token: 'token' };
91
+ const beeConfig = { uid: 'uid' };
92
+ let instance;
93
+ let BeePlugin;
94
+
95
+ beforeEach(() => {
96
+ instance = { start: jest.fn(), destroy: jest.fn() };
97
+ BeePlugin = { create: jest.fn((token, config, onCreated) => onCreated(instance)) };
98
+ });
99
+
100
+ it('creates the editor and starts it with parsed JSON when given a string', async () => {
101
+ const { startBeePlugin } = getLoader();
102
+ const result = await startBeePlugin(BeePlugin, { tokenData, beeConfig, getBeeJson: () => '{"page":{}}' });
103
+ expect(BeePlugin.create).toHaveBeenCalledWith(tokenData, beeConfig, expect.any(Function));
104
+ expect(instance.start).toHaveBeenCalledWith({ page: {} });
105
+ expect(result).toBe(instance);
106
+ });
107
+
108
+ it('starts the editor with an object template as-is', async () => {
109
+ const { startBeePlugin } = getLoader();
110
+ const template = { page: { rows: [] } };
111
+ await startBeePlugin(BeePlugin, { tokenData, beeConfig, getBeeJson: () => template });
112
+ expect(instance.start).toHaveBeenCalledWith(template);
113
+ });
114
+
115
+ it('rejects without starting when the template JSON is invalid', async () => {
116
+ const { startBeePlugin } = getLoader();
117
+ await expect(
118
+ startBeePlugin(BeePlugin, { tokenData, beeConfig, getBeeJson: () => '{invalid' }),
119
+ ).rejects.toThrow(SyntaxError);
120
+ expect(instance.start).not.toHaveBeenCalled();
121
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
122
+ });
123
+ });
124
+
125
+ describe('destroyBeeInstance', () => {
126
+ it('destroys the editor and tolerates a missing or failing destroy', () => {
127
+ const { destroyBeeInstance } = getLoader();
128
+ const instance = { destroy: jest.fn() };
129
+ destroyBeeInstance(instance);
130
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
131
+
132
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
133
+ expect(() => destroyBeeInstance({ destroy: () => { throw new Error('not mounted'); } })).not.toThrow();
134
+ expect(() => destroyBeeInstance(undefined)).not.toThrow();
135
+ warn.mockRestore();
136
+ });
137
+ });
138
+
139
+ describe('initBeeEditor', () => {
140
+ const tokenData = { access_token: 'token' };
141
+ const beeConfig = { uid: 'uid' };
142
+ let instance;
143
+
144
+ beforeEach(() => {
145
+ instance = { start: jest.fn(), destroy: jest.fn() };
146
+ window.BeePlugin = { create: jest.fn((token, config, onCreated) => onCreated(instance)) };
147
+ });
148
+
149
+ afterEach(() => {
150
+ delete window.BeePlugin;
151
+ });
152
+
153
+ it('loads the plugin, reports it, and resolves the started editor', async () => {
154
+ const { initBeeEditor } = getLoader();
155
+ const onPluginLoaded = jest.fn();
156
+ const result = await initBeeEditor({
157
+ tokenData, beeConfig, getBeeJson: () => '{"page":{}}', isCancelled: () => false, onPluginLoaded,
158
+ });
159
+ expect(onPluginLoaded).toHaveBeenCalledTimes(1);
160
+ expect(instance.start).toHaveBeenCalledWith({ page: {} });
161
+ expect(result).toBe(instance);
162
+ });
163
+
164
+ it('does not create the editor when cancelled before the plugin loads', async () => {
165
+ const { initBeeEditor } = getLoader();
166
+ const result = await initBeeEditor({
167
+ tokenData, beeConfig, getBeeJson: () => '{}', isCancelled: () => true,
168
+ });
169
+ expect(window.BeePlugin.create).not.toHaveBeenCalled();
170
+ expect(result).toBeNull();
171
+ });
172
+
173
+ it('destroys an editor created after cancellation without starting it', async () => {
174
+ const { initBeeEditor } = getLoader();
175
+ let cancelled = false;
176
+ window.BeePlugin.create.mockImplementation((token, config, onCreated) => {
177
+ cancelled = true;
178
+ onCreated(instance);
179
+ });
180
+ const result = await initBeeEditor({
181
+ tokenData, beeConfig, getBeeJson: () => '{}', isCancelled: () => cancelled,
182
+ });
183
+ expect(instance.start).not.toHaveBeenCalled();
184
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
185
+ expect(result).toBeNull();
186
+ });
187
+
188
+ it('destroys an editor cancelled after it started', async () => {
189
+ const { initBeeEditor } = getLoader();
190
+ let cancelled = false;
191
+ instance.start.mockImplementation(() => { cancelled = true; });
192
+ const result = await initBeeEditor({
193
+ tokenData, beeConfig, getBeeJson: () => '{}', isCancelled: () => cancelled,
194
+ });
195
+ expect(instance.start).toHaveBeenCalledTimes(1);
196
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
197
+ expect(result).toBeNull();
198
+ });
199
+ });