@applicaster/zapp-react-native-utils 13.0.0-alpha.1724095599 → 13.0.0-alpha.1753452014

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.
@@ -72,12 +72,14 @@ const mappedScreenPropertiesScreen = (
72
72
  screenData
73
73
  ): AnalyticsScreenProperties => {
74
74
  return {
75
- screen_name: screenData?.targetScreen?.name,
75
+ screen_name: screenData?.targetScreen?.name || screenData?.name,
76
76
  screen_entry_title: screenData?.title,
77
77
  screen_entry_id: R.isNil(screenData?.type) ? null : screenData?.id,
78
- screen_layout_id: screenData?.targetScreen?.id,
79
- screen_type: screenData?.targetScreen?.type,
80
- home_screen: screenData?.targetScreen?.home,
78
+ screen_layout_id: screenData?.targetScreen?.id || screenData?.id,
79
+ screen_type: screenData?.targetScreen?.type || screenData?.type,
80
+ home_screen: !R.isNil(screenData?.targetScreen?.home)
81
+ ? screenData?.targetScreen?.home
82
+ : screenData?.home,
81
83
  };
82
84
  };
83
85
 
@@ -84,7 +84,7 @@ export function HooksManager({
84
84
  plugins,
85
85
  startUpHooksData = {},
86
86
  }: HookManagerArgs): HookManager {
87
- hooksManagerLogger.addContext({ targetScreen });
87
+ hooksManagerLogger.addContext({ targetScreenId: targetScreen.id });
88
88
 
89
89
  function logHookEvent(func, message, data) {
90
90
  func({
@@ -334,16 +334,7 @@ export const focusManager = (function () {
334
334
  return { success: false };
335
335
  }
336
336
 
337
- function treeLoaded(val, node) {
338
- logger.log({
339
- message: "treeLoaded",
340
- data: {
341
- val,
342
- node,
343
- currentFocusNode,
344
- },
345
- });
346
- }
337
+ function treeLoaded(_val, _node) {}
347
338
 
348
339
  function pressIn() {
349
340
  const currentFocusable = getCurrentFocus();
@@ -1,5 +1,3 @@
1
- import * as R from "ramda";
2
-
3
1
  // more keys can be added here. Simply make sure
4
2
  // the key matches the code value
5
3
 
@@ -34,12 +32,18 @@ export function keyCode(key) {
34
32
  keyCode(keyEvent).matchesAny("Enter", "Backspace", KEYS.ArrowLeft, ...)
35
33
  */
36
34
 
37
- const matches = R.compose(
38
- R.either(R.eqProps("code", key), R.eqProps("keyCode", key)),
39
- R.when(R.is(String), R.prop(R.__, KEYS))
40
- );
35
+ const matches = (compareKey) => {
36
+ // If compareKey is a string, look it up in KEYS object
37
+ const keyToCompare =
38
+ typeof compareKey === "string" ? KEYS[compareKey] : compareKey;
39
+
40
+ // Compare either code or keyCode properties
41
+ return (
42
+ keyToCompare?.code === key.code || keyToCompare?.keyCode === key.keyCode
43
+ );
44
+ };
41
45
 
42
- const matchesAny = (...args) => R.any(matches, args);
46
+ const matchesAny = (...args) => args.some(matches);
43
47
 
44
48
  const direction = () =>
45
49
  matchesAny(...ARROW_KEYS) ? directionHelper(key) : null;
@@ -1,4 +1,3 @@
1
- /// <reference types="@types/react-native" />
2
1
  import * as ReactNative from "react-native";
3
2
  import { isTV, platformSelect } from "../reactUtils";
4
3
  import { usePickFromState } from "@applicaster/zapp-react-native-redux/hooks";
@@ -452,7 +452,7 @@ export class PlayerManager {
452
452
  if (this.castingReceiver) {
453
453
  this.castingReceiver.closeNativePlayer();
454
454
  } else {
455
- this.getActivePlayer().closeNativePlayer();
455
+ this.getActivePlayer()?.closeNativePlayer();
456
456
  this.invokeHandler("close");
457
457
  }
458
458
  }
@@ -1,5 +1,5 @@
1
1
  import * as R from "ramda";
2
- import { useRef } from "react";
2
+ import { useCallback, useEffect, useRef } from "react";
3
3
 
4
4
  /**
5
5
  *
@@ -9,31 +9,44 @@ import { useRef } from "react";
9
9
  */
10
10
  export const useThrottle = (callback: () => void, delay: number) => {
11
11
  const lastCallRef = useRef<number>(0);
12
- const timeoutRef = useRef<any | null>(null);
12
+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);
13
+ const callbackRef = useRef<() => void>(callback);
13
14
 
14
- const throttledFunction = () => {
15
+ useEffect(() => {
16
+ callbackRef.current = callback;
17
+ }, [callback]);
18
+
19
+ const throttledFunction = useCallback(() => {
15
20
  const now = Date.now();
16
21
 
17
22
  if (now - lastCallRef.current >= delay) {
18
- callback();
23
+ callbackRef.current();
19
24
  lastCallRef.current = now;
20
25
  } else if (!timeoutRef.current) {
21
26
  const remainingTime = delay - (now - lastCallRef.current);
22
27
 
23
28
  timeoutRef.current = setTimeout(() => {
24
- callback();
29
+ callbackRef.current();
25
30
  lastCallRef.current = Date.now();
26
31
  timeoutRef.current = null;
27
32
  }, remainingTime);
28
33
  }
29
- };
34
+ }, [delay]);
30
35
 
31
- const cancel = () => {
36
+ const cancel = useCallback(() => {
32
37
  if (timeoutRef.current) {
33
38
  clearTimeout(timeoutRef.current);
34
39
  timeoutRef.current = null;
35
40
  }
36
- };
41
+ }, []);
42
+
43
+ useEffect(() => {
44
+ return () => {
45
+ if (timeoutRef.current) {
46
+ clearTimeout(timeoutRef.current);
47
+ }
48
+ };
49
+ }, []);
37
50
 
38
51
  return { throttledFunction, cancel };
39
52
  };
@@ -224,12 +224,11 @@ function fontKey(label, defaults, conditionalField = null) {
224
224
  return fields;
225
225
  }
226
226
 
227
- function tvMenuLabel(label, description, defaults) {
228
- return fieldsGroup(
229
- label,
230
- description,
231
- generateFieldsFromDefaults(label, defaults, TV_MENU_LABEL_FIELDS)
232
- );
227
+ function tvMenuLabel(label, description, defaults, fields = []) {
228
+ return fieldsGroup(label, description, [
229
+ ...fields,
230
+ ...generateFieldsFromDefaults(label, defaults, TV_MENU_LABEL_FIELDS),
231
+ ]);
233
232
  }
234
233
 
235
234
  function mobileCellLabel(label, description, defaults, groupFolded) {
@@ -24,7 +24,7 @@ const componentConfigurationFields = [
24
24
  initial_value: "vertical",
25
25
  options: [
26
26
  { text: "Vertical", value: "vertical" },
27
- { text: "Horizontal (Beta)", value: "horizontal" },
27
+ { text: "Horizontal", value: "horizontal" },
28
28
  ],
29
29
  },
30
30
  {
@@ -3,7 +3,7 @@ import { logger } from "@applicaster/zapp-react-native-utils/logger";
3
3
 
4
4
  const numberUtilsLogger = logger?.addSubsystem("NumberUtils");
5
5
 
6
- export const toNumber = (value: any): number | undefined => {
6
+ export const toNumber = (value: unknown): number | undefined => {
7
7
  if (R.isNil(value) || R.isEmpty(value)) {
8
8
  return undefined;
9
9
  }
@@ -17,10 +17,12 @@ export const toNumber = (value: any): number | undefined => {
17
17
  return undefined;
18
18
  };
19
19
 
20
- export const toNumberWithDefault = (defaultValue: number, value: any): number =>
21
- toNumber(value) ?? defaultValue;
20
+ export const toNumberWithDefault = (
21
+ defaultValue: number,
22
+ value: unknown
23
+ ): number => toNumber(value) ?? defaultValue;
22
24
 
23
- export const toNumberWithDefaultZero = (value: any): number =>
25
+ export const toNumberWithDefaultZero = (value: unknown): number =>
24
26
  toNumberWithDefault(0, value);
25
27
 
26
28
  export const requireNumber = (obj, key: string) => {
@@ -39,7 +41,7 @@ export const requireNumber = (obj, key: string) => {
39
41
 
40
42
  export const toFiniteNumberWithDefault = (
41
43
  defaultValue: number,
42
- value: any
44
+ value: unknown
43
45
  ): number => {
44
46
  const possibleNumber = toNumberWithDefault(defaultValue, value);
45
47
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@applicaster/zapp-react-native-utils",
3
- "version": "13.0.0-alpha.1724095599",
3
+ "version": "13.0.0-alpha.1753452014",
4
4
  "description": "Applicaster Zapp React Native utilities package",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "homepage": "https://github.com/applicaster/quickbrick#readme",
30
30
  "dependencies": {
31
- "@applicaster/applicaster-types": "13.0.0-alpha.1724095599",
31
+ "@applicaster/applicaster-types": "13.0.0-alpha.1753452014",
32
32
  "buffer": "^5.2.1",
33
33
  "camelize": "^1.0.0",
34
34
  "dayjs": "^1.11.10",
@@ -45,8 +45,5 @@
45
45
  "uglify-js": "*",
46
46
  "validate-color": "*",
47
47
  "zustand": "*"
48
- },
49
- "devDependencies": {
50
- "@types/react-native": "0.69.6"
51
48
  }
52
49
  }
@@ -35,25 +35,23 @@ const Wrapper = ({ children }: { children: React.ReactChild }) => (
35
35
  const { useTrackedView } = require("../useTrackedView");
36
36
 
37
37
  describe("useTrackCurrentAutoScrollingElement", () => {
38
- it("should update position for selected component", async () => {
38
+ it("should update position for selected component - onViewportEnter", () => {
39
39
  const { result } = renderHook(() => useTrackedView("123"), {
40
40
  wrapper: Wrapper,
41
41
  });
42
42
 
43
- // Fast-forward until all timers have been executed
44
- jest.advanceTimersByTime(3000);
45
-
46
43
  expect(result.current.inViewPort).toBe(false);
47
44
 
48
45
  const mockRect = {
49
46
  rect: { left: 1, right: 1, top: 1, bottom: 1 },
50
47
  };
51
48
 
52
- act(() => {
53
- result.current.onPositionUpdated(mockRect);
49
+ act(async () => {
50
+ await result.current.onPositionUpdated(mockRect);
54
51
  });
55
52
 
56
- jest.advanceTimersByTime(3000);
53
+ // Fast-forward until all timers have been executed
54
+ jest.runAllTimers();
57
55
 
58
56
  expect(result.current.inViewPort).toBe(true);
59
57
 
@@ -2,6 +2,10 @@ import { useCallback, useEffect, useMemo, useState } from "react";
2
2
  import { useScreenTrackedViewPositionsContext } from "@applicaster/zapp-react-native-ui-components/Contexts/ScreenTrackedViewPositionsContext";
3
3
  import { useDimensions } from "@applicaster/zapp-react-native-utils/reactHooks/layout";
4
4
  import { findTrackedView } from "./utils/findTrackedView";
5
+ import { isNil } from "ramda";
6
+ import { withTimeout } from "@applicaster/zapp-react-native-utils/idleUtils";
7
+
8
+ const TIMEOUT_FOR_DELAY_ON_VIEWPORT_ENTER_EVENT = 500; // ms
5
9
 
6
10
  const getNormalizedRect = (rect, componentId, screenWidth, screenHeight) => {
7
11
  if (!rect) {
@@ -37,9 +41,16 @@ export const useTrackedView = (componentId: string) => {
37
41
  );
38
42
 
39
43
  const onPositionUpdated = useCallback(
40
- ({ rect }) => {
44
+ async ({ rect }) => {
41
45
  const currentPosition = normalizedRect(componentId, rect);
42
46
 
47
+ // There is an issue on the native side where they are unable to guarantee
48
+ // that the order of onViewportLeave and onViewportEnter events is always correct.
49
+ // This workaround/hack delays the onViewportEnter event to ensure it is received last.
50
+ if (!isNil(currentPosition)) {
51
+ await withTimeout(TIMEOUT_FOR_DELAY_ON_VIEWPORT_ENTER_EVENT);
52
+ }
53
+
43
54
  updateComponentsPositions(componentId, currentPosition as any);
44
55
 
45
56
  setInViewPort(!!currentPosition);
@@ -310,14 +310,14 @@ describe("navigation", () => {
310
310
  expect(navBarVisible).toBe(false);
311
311
  });
312
312
 
313
- it("returns false if it's secondary nav bar and hide_secondary_level_menu is true", () => {
313
+ it("returns false if it's secondary nav bar and show_secondary_level_menu is false", () => {
314
314
  const navBarVisible = isNavBarVisible(
315
315
  "",
316
316
  {
317
317
  navigations: [
318
318
  {
319
319
  styles: {
320
- hide_secondary_level_menu: true,
320
+ show_secondary_level_menu: false,
321
321
  },
322
322
  },
323
323
  ],
@@ -329,14 +329,14 @@ describe("navigation", () => {
329
329
  expect(navBarVisible).toBe(false);
330
330
  });
331
331
 
332
- it("returns true if it's secondary nav bar and hide_secondary_level_menu is false", () => {
332
+ it("returns true if it's secondary nav bar and show_secondary_level_menu is true", () => {
333
333
  const navBarVisible = isNavBarVisible(
334
334
  "",
335
335
  {
336
336
  navigations: [
337
337
  {
338
338
  styles: {
339
- hide_secondary_level_menu: false,
339
+ show_secondary_level_menu: true,
340
340
  },
341
341
  },
342
342
  ],
@@ -348,14 +348,14 @@ describe("navigation", () => {
348
348
  expect(navBarVisible).toBe(true);
349
349
  });
350
350
 
351
- it("returns true if it's first level menu and hide_secondary_level_menu is true", () => {
351
+ it("returns true if it's first level menu and show_secondary_level_menu is false", () => {
352
352
  const navBarVisible = isNavBarVisible(
353
353
  "",
354
354
  {
355
355
  navigations: [
356
356
  {
357
357
  styles: {
358
- hide_secondary_level_menu: true,
358
+ show_secondary_level_menu: false,
359
359
  },
360
360
  },
361
361
  ],
@@ -366,16 +366,5 @@ describe("navigation", () => {
366
366
 
367
367
  expect(navBarVisible).toBe(true);
368
368
  });
369
-
370
- it("returns true otherwise", () => {
371
- const navBarVisible = isNavBarVisible(
372
- "",
373
- { navigations: [] } as any,
374
- true,
375
- true
376
- );
377
-
378
- expect(navBarVisible).toBe(true);
379
- });
380
369
  });
381
370
  });
@@ -108,11 +108,11 @@ export function isNavBarVisible(
108
108
  return false;
109
109
  }
110
110
 
111
- const hideSecondaryLevel = screenData?.navigations?.some(
112
- (navigation) => navigation.styles?.hide_secondary_level_menu
111
+ const showSecondaryLevel = screenData?.navigations?.some(
112
+ (navigation) => navigation.styles?.show_secondary_level_menu
113
113
  );
114
114
 
115
- if (canGoBack && hideSecondaryLevel) {
115
+ if (canGoBack && !showSecondaryLevel) {
116
116
  return false;
117
117
  }
118
118
 
@@ -0,0 +1,673 @@
1
+ import { localStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/LocalStorage";
2
+ import { sessionStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/SessionStorage";
3
+ import { parseJsonIfNeeded } from "@applicaster/zapp-react-native-utils/functionUtils";
4
+
5
+ export const JS_BRIDGE_EVENTS = {
6
+ DISMISS_HOOK: "DISMISS_HOOK",
7
+ LOG: "LOG",
8
+ GET_SESSION_STORAGE: "GET_SESSION_STORAGE",
9
+ SET_SESSION_STORAGE: "SET_SESSION_STORAGE",
10
+ GET_LOCAL_STORAGE: "GET_LOCAL_STORAGE",
11
+ SET_LOCAL_STORAGE: "SET_LOCAL_STORAGE",
12
+ GET_SECURE_LOCAL_STORAGE: "GET_SECURE_LOCAL_STORAGE",
13
+ SET_SECURE_LOCAL_STORAGE: "SET_SECURE_LOCAL_STORAGE",
14
+ CLOSE_WEBVIEW: "CLOSE_WEBVIEW",
15
+ NAVIGATE_TO_SCREEN: "NAVIGATE_TO_SCREEN",
16
+ NAVIGATE_TO_ENTRY: "NAVIGATE_TO_ENTRY",
17
+ OPEN_URL_SCHEME: "OPEN_URL_SCHEME",
18
+ OPEN_NATIVE_SHARE: "OPEN_NATIVE_SHARE",
19
+ ADD_SESSION_STORAGE_LISTENER: "ADD_SESSION_STORAGE_LISTENER",
20
+ REMOVE_SESSION_STORAGE_LISTENER: "REMOVE_SESSION_STORAGE_LISTENER",
21
+ ADD_LOCAL_STORAGE_LISTENER: "ADD_LOCAL_STORAGE_LISTENER",
22
+ REMOVE_LOCAL_STORAGE_LISTENER: "REMOVE_LOCAL_STORAGE_LISTENER",
23
+ };
24
+
25
+ export const INVOKE_APPLICASTER_CALLBACK = "__invoke__applicaster__callback";
26
+
27
+ const APPLICASTER_CALLBACK_KEY = "__applicaster__js2native__callbacks";
28
+ const getSessionStorageItem = "getSessionStorageItem";
29
+ const setSessionStorageItem = "setSessionStorageItem";
30
+ const getLocalStorageItem = "getLocalStorageItem";
31
+ const setLocalStorageItem = "setLocalStorageItem";
32
+ const getSecureLocalStorageItem = "getSecureLocalStorageItem";
33
+ const setSecureLocalStorageItem = "setSecureLocalStorageItem";
34
+ const addSessionStorageListenerFn = "addSessionStorageListener";
35
+ const addLocalStorageListenerFn = "addLocalStorageListener";
36
+
37
+ const activeListeners: { [key: string]: () => void } = {};
38
+
39
+ const sendMessage = `
40
+ function sendMessage(type, payload, meta) {
41
+ if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === 'function') {
42
+ window.ReactNativeWebView.postMessage(JSON.stringify({
43
+ type: type,
44
+ payload: payload,
45
+ meta: meta
46
+ }));
47
+ }
48
+ }
49
+ `;
50
+
51
+ const consolePolyfill = `
52
+ var consoleLog = console.log;
53
+ var consoleWarn = console.warn;
54
+ var consoleError = console.error;
55
+
56
+ function logInConsole(level, args) {
57
+ var serializableArgs = [];
58
+ try {
59
+ serializableArgs = args.map(function(arg) {
60
+ try {
61
+ return JSON.parse(JSON.stringify(arg));
62
+ } catch (e) {
63
+ if (typeof arg === 'function') return '[Function]';
64
+ if (typeof arg === 'symbol') return String(arg);
65
+ if (arg instanceof Error) return { name: arg.name, message: arg.message, stack: arg.stack };
66
+ return '[Unserializable]';
67
+ }
68
+ });
69
+ } catch(e) {
70
+ serializableArgs = ['Error processing console arguments'];
71
+ }
72
+
73
+ sendMessage("${JS_BRIDGE_EVENTS.LOG}", {
74
+ level: level,
75
+ messages: JSON.stringify(serializableArgs)
76
+ });
77
+ }
78
+
79
+ function log() {
80
+ var args = [].slice.call(arguments);
81
+ consoleLog.apply(null, args);
82
+ try {
83
+ logInConsole("log", args);
84
+ } catch (e) {
85
+ consoleError("Error in custom console.log:", e);
86
+ }
87
+ };
88
+
89
+ function warn() {
90
+ var args = [].slice.call(arguments);
91
+ consoleWarn.apply(null, args);
92
+ try {
93
+ logInConsole("warn", args);
94
+ } catch (e) {
95
+ consoleError("Error in custom console.warn:", e);
96
+ }
97
+ }
98
+
99
+ function error() {
100
+ var args = [].slice.call(arguments);
101
+ consoleError.apply(null, args);
102
+ try {
103
+ logInConsole("error", args);
104
+ } catch (e) {
105
+ consoleError("Error in custom console.error:", e);
106
+ }
107
+ }
108
+
109
+ setTimeout(function() {
110
+ console.log = log;
111
+ console.warn = warn;
112
+ console.error = error;
113
+ }, 0);
114
+ `;
115
+
116
+ const callbackHandling = `
117
+ window.Applicaster = window.Applicaster || {};
118
+ window.Applicaster.${APPLICASTER_CALLBACK_KEY} = window.Applicaster.${APPLICASTER_CALLBACK_KEY} || {};
119
+
120
+ var ${INVOKE_APPLICASTER_CALLBACK} = function(key, args) {
121
+ var callback = window.Applicaster.${APPLICASTER_CALLBACK_KEY}[key];
122
+
123
+ var deleteCallback = true;
124
+ if (typeof callback === "function") {
125
+ var result = callback.apply(null, args);
126
+ if (result === false) {
127
+ deleteCallback = false;
128
+ }
129
+ }
130
+ if(deleteCallback) {
131
+ delete window.Applicaster.${APPLICASTER_CALLBACK_KEY}[key];
132
+ }
133
+ }
134
+
135
+ window.Applicaster.${INVOKE_APPLICASTER_CALLBACK} = ${INVOKE_APPLICASTER_CALLBACK};
136
+ `;
137
+
138
+ export function invokeWebCallback(key, args) {
139
+ const argsArray = Array.isArray(args) ? args : [args];
140
+ let stringifiedArgs = "[]";
141
+
142
+ try {
143
+ stringifiedArgs = JSON.stringify(argsArray);
144
+ } catch (e) {
145
+ try {
146
+ stringifiedArgs = JSON.stringify([
147
+ { error: "Failed to stringify arguments", details: e.message },
148
+ ]);
149
+ } catch {
150
+ stringifiedArgs = "[]";
151
+ }
152
+ }
153
+
154
+ return `
155
+ (function() {
156
+ var callbackFn = window.Applicaster && window.Applicaster.${APPLICASTER_CALLBACK_KEY};
157
+ if (callbackFn && typeof callbackFn["${key}"] === 'function') {
158
+ try {
159
+ setTimeout(function() {
160
+ callbackFn["${key}"].apply(null, ${stringifiedArgs});
161
+ }, 0);
162
+ } catch (e) {
163
+ console.error("Error invoking web callback ${key}:", e);
164
+ }
165
+ } else {
166
+ // console.warn("Web callback ${key} not found or not a function.");
167
+ }
168
+ return true;
169
+ })();
170
+ `;
171
+ }
172
+
173
+ const hookCallback = `
174
+ function hookCallback(options) {
175
+ var _opts = {};
176
+
177
+ if (typeof options !== "undefined") {
178
+ _opts = options;
179
+ }
180
+
181
+ var success = typeof _opts.success === 'boolean' ? _opts.success : false;
182
+ var error = _opts.error || undefined;
183
+ var payload = _opts.payload || undefined;
184
+
185
+ sendMessage("${JS_BRIDGE_EVENTS.DISMISS_HOOK}", {
186
+ success: success,
187
+ error: error,
188
+ payload: payload
189
+ })
190
+ };
191
+ `;
192
+
193
+ const uuid = `
194
+ function uuid() {
195
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
196
+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
197
+ return v.toString(16);
198
+ });
199
+ }
200
+ `;
201
+
202
+ const registerCallback = `
203
+ function registerCallback(cb, persistent) {
204
+ var index = uuid();
205
+ window.Applicaster = window.Applicaster || {};
206
+ window.Applicaster.${APPLICASTER_CALLBACK_KEY} = window.Applicaster.${APPLICASTER_CALLBACK_KEY} || {};
207
+
208
+ window.Applicaster.${APPLICASTER_CALLBACK_KEY}[index] = function() {
209
+ var result = cb.apply(null, arguments);
210
+ return persistent ? false : result;
211
+ };
212
+ return index;
213
+ }
214
+ `;
215
+
216
+ const getSetStorage = `
217
+ function getSetStorage(type, payload) {
218
+ return new Promise(function(resolve, reject) {
219
+ var index = registerCallback(function(result) {
220
+ if (result && result.success === false) {
221
+ reject(result.error || new Error("Storage operation failed"));
222
+ } else {
223
+ resolve(result);
224
+ }
225
+ });
226
+ sendMessage(type, payload, index);
227
+ });
228
+ }
229
+ `;
230
+
231
+ const getInSessionStorage = `
232
+ function ${getSessionStorageItem}(key, namespace) {
233
+ return getSetStorage(
234
+ "${JS_BRIDGE_EVENTS.GET_SESSION_STORAGE}",
235
+ { key: key, namespace: namespace }
236
+ );
237
+ }
238
+ `;
239
+
240
+ const setInSessionStorage = `
241
+ function ${setSessionStorageItem}(key, value, namespace) {
242
+ try {
243
+ JSON.stringify(value);
244
+ return getSetStorage(
245
+ "${JS_BRIDGE_EVENTS.SET_SESSION_STORAGE}",
246
+ { key: key, value: value, namespace: namespace }
247
+ );
248
+ } catch (e) {
249
+ return Promise.reject(new Error("Value is not serializable: " + e.message));
250
+ }
251
+ }
252
+ `;
253
+
254
+ const getInLocalStorage = `
255
+ function ${getLocalStorageItem}(key, namespace) {
256
+ return getSetStorage(
257
+ "${JS_BRIDGE_EVENTS.GET_LOCAL_STORAGE}",
258
+ { key: key, namespace: namespace }
259
+ );
260
+ }
261
+ `;
262
+
263
+ const setInLocalStorage = `
264
+ function ${setLocalStorageItem}(key, value, namespace) {
265
+ try {
266
+ JSON.stringify(value);
267
+ return getSetStorage(
268
+ "${JS_BRIDGE_EVENTS.SET_LOCAL_STORAGE}",
269
+ { key: key, value: value, namespace: namespace }
270
+ );
271
+ } catch (e) {
272
+ return Promise.reject(new Error("Value is not serializable: " + e.message));
273
+ }
274
+ }
275
+ `;
276
+
277
+ const getInSecureLocalStorage = `
278
+ function ${getSecureLocalStorageItem}(key, namespace) {
279
+ return getSetStorage(
280
+ "${JS_BRIDGE_EVENTS.GET_SECURE_LOCAL_STORAGE}",
281
+ { key: key, namespace: namespace }
282
+ );
283
+ }
284
+ `;
285
+
286
+ const setInSecureLocalStorage = `
287
+ function ${setSecureLocalStorageItem}(key, value, namespace) {
288
+ try {
289
+ JSON.stringify(value);
290
+ return getSetStorage(
291
+ "${JS_BRIDGE_EVENTS.SET_SECURE_LOCAL_STORAGE}",
292
+ { key: key, value: value, namespace: namespace }
293
+ );
294
+ } catch (e) {
295
+ return Promise.reject(new Error("Value is not serializable: " + e.message));
296
+ }
297
+ }
298
+ `;
299
+
300
+ const addSessionStorageListener = `
301
+ function ${addSessionStorageListenerFn}(optionsOrCallback, callback) {
302
+ var opts = {};
303
+ var cb = callback;
304
+
305
+ if (typeof optionsOrCallback === 'function') {
306
+ cb = optionsOrCallback;
307
+ } else if (typeof optionsOrCallback === 'object' && optionsOrCallback !== null) {
308
+ opts = optionsOrCallback;
309
+ } else if (optionsOrCallback !== undefined && optionsOrCallback !== null) {
310
+ console.error("Invalid arguments for addSessionStorageListener. Expected ({ key, namespace }, callback) or (callback).");
311
+ return function() {};
312
+ }
313
+
314
+ if (typeof cb !== 'function') {
315
+ console.error("addSessionStorageListener requires a callback function.");
316
+ return function() {};
317
+ }
318
+
319
+ var listenerId = registerCallback(cb, true);
320
+
321
+ sendMessage("${JS_BRIDGE_EVENTS.ADD_SESSION_STORAGE_LISTENER}", { key: opts.key, namespace: opts.namespace }, listenerId);
322
+
323
+ return function removeListener() {
324
+ sendMessage("${JS_BRIDGE_EVENTS.REMOVE_SESSION_STORAGE_LISTENER}", { listenerId: listenerId });
325
+ if (window.Applicaster && window.Applicaster.${APPLICASTER_CALLBACK_KEY}) {
326
+ delete window.Applicaster.${APPLICASTER_CALLBACK_KEY}[listenerId];
327
+ }
328
+ };
329
+ }
330
+ `;
331
+
332
+ const addLocalStorageListener = `
333
+ function ${addLocalStorageListenerFn}(optionsOrCallback, callback) {
334
+ var opts = {};
335
+ var cb = callback;
336
+
337
+ if (typeof optionsOrCallback === 'function') {
338
+ cb = optionsOrCallback;
339
+ } else if (typeof optionsOrCallback === 'object' && optionsOrCallback !== null) {
340
+ opts = optionsOrCallback;
341
+ } else if (optionsOrCallback !== undefined && optionsOrCallback !== null) {
342
+ console.error("Invalid arguments for addLocalStorageListener. Expected ({ key, namespace }, callback) or (callback).");
343
+ return function() {};
344
+ }
345
+
346
+ if (typeof cb !== 'function') {
347
+ console.error("addLocalStorageListener requires a callback function.");
348
+ return function() {};
349
+ }
350
+
351
+ var listenerId = registerCallback(cb, true);
352
+
353
+ sendMessage("${JS_BRIDGE_EVENTS.ADD_LOCAL_STORAGE_LISTENER}", { key: opts.key, namespace: opts.namespace }, listenerId);
354
+
355
+ return function removeListener() {
356
+ sendMessage("${JS_BRIDGE_EVENTS.REMOVE_LOCAL_STORAGE_LISTENER}", { listenerId: listenerId });
357
+ if (window.Applicaster && window.Applicaster.${APPLICASTER_CALLBACK_KEY}) {
358
+ delete window.Applicaster.${APPLICASTER_CALLBACK_KEY}[listenerId];
359
+ }
360
+ };
361
+ }
362
+ `;
363
+
364
+ const closeWebview = `
365
+ function closeWebview() {
366
+ sendMessage("${JS_BRIDGE_EVENTS.CLOSE_WEBVIEW}")
367
+ }
368
+ `;
369
+
370
+ const navigateToScreen = `
371
+ function navigateToScreen(screenId) {
372
+ if(!screenId) { console.error("navigateToScreen requires a screenId"); return; }
373
+ sendMessage("${JS_BRIDGE_EVENTS.NAVIGATE_TO_SCREEN}", { screenId: screenId });
374
+ }
375
+ `;
376
+
377
+ const navigateToEntry = `
378
+ function navigateToEntry(entry) {
379
+ if(!entry) { console.error("navigateToEntry requires an entry object"); return; }
380
+ sendMessage("${JS_BRIDGE_EVENTS.NAVIGATE_TO_ENTRY}", { entry: entry });
381
+ }
382
+ `;
383
+
384
+ const openUrlScheme = `
385
+ function openUrlScheme(url) {
386
+ if(!url || typeof url !== 'string') { console.error("openUrlScheme requires a valid URL string"); return; }
387
+ sendMessage("${JS_BRIDGE_EVENTS.OPEN_URL_SCHEME}", { url: url });
388
+ }
389
+ `;
390
+
391
+ const runInvokeShare = `
392
+ function invokeShare(item, options) {
393
+ if(!item) { console.error("invokeShare requires an item object"); return; }
394
+ sendMessage("${JS_BRIDGE_EVENTS.OPEN_NATIVE_SHARE}", { item: item, options: options });
395
+ }
396
+ `;
397
+
398
+ const initializeBridge = (payload, hookPlugin, screens, safeAreaInsets) => `
399
+ (function() {
400
+ window.Applicaster = window.Applicaster || {};
401
+
402
+ ${sendMessage}
403
+ ${consolePolyfill}
404
+ ${hookCallback}
405
+ ${uuid}
406
+ ${callbackHandling}
407
+ ${registerCallback}
408
+ ${getSetStorage}
409
+ ${getInSessionStorage}
410
+ ${setInSessionStorage}
411
+ ${getInLocalStorage}
412
+ ${setInLocalStorage}
413
+ ${getInSecureLocalStorage}
414
+ ${setInSecureLocalStorage}
415
+ ${addSessionStorageListener}
416
+ ${addLocalStorageListener}
417
+ ${closeWebview}
418
+ ${navigateToScreen}
419
+ ${navigateToEntry}
420
+ ${openUrlScheme}
421
+ ${runInvokeShare}
422
+
423
+ var JS2Native = {
424
+ screenHook: {
425
+ data: {
426
+ payload: (function() { try { return JSON.parse(${payload}); } catch(e) { console.error('Failed to parse screenHook payload:', e); return null; } })(),
427
+ plugin: (function() { try { return JSON.parse(${hookPlugin}); } catch(e) { console.error('Failed to parse screenHook plugin:', e); return null; } })()
428
+ },
429
+ callback: hookCallback
430
+ },
431
+ sessionStorage: {
432
+ getItem: ${getSessionStorageItem},
433
+ setItem: ${setSessionStorageItem},
434
+ addListener: ${addSessionStorageListenerFn}
435
+ },
436
+ localStorage: {
437
+ getItem: ${getLocalStorageItem},
438
+ setItem: ${setLocalStorageItem},
439
+ getSecuredItem: ${getSecureLocalStorageItem},
440
+ setSecuredItem: ${setSecureLocalStorageItem},
441
+ addListener: ${addLocalStorageListenerFn}
442
+ },
443
+ nativeEnvironment: true,
444
+ navigation: {
445
+ closeWebview: closeWebview,
446
+ navigateToScreen: navigateToScreen,
447
+ navigateToEntry: navigateToEntry,
448
+ screens: (function() { try { return JSON.parse(${screens}); } catch(e) { console.error('Failed to parse navigation screens:', e); return []; } })(),
449
+ openUrlScheme: openUrlScheme
450
+ },
451
+ safeAreaInsets: (function() { try { return JSON.parse(${safeAreaInsets}); } catch(e) { console.error('Failed to parse safeAreaInsets:', e); return {}; } })(),
452
+ nativeShare: invokeShare
453
+ };
454
+
455
+ window.Applicaster.JS2Native = JS2Native;
456
+ window.JS2Native = JS2Native;
457
+
458
+ return JS2Native;
459
+ })();
460
+ `;
461
+
462
+ export const jsBridge = (hooksProps, screens, safeAreaInsets) => `
463
+ var Applicaster = window.Applicaster || {};
464
+ window.Applicaster = Applicaster;
465
+
466
+ ${initializeBridge(
467
+ JSON.stringify(hooksProps?.payload),
468
+ JSON.stringify(hooksProps?.hookPlugin),
469
+ JSON.stringify(Object.values(screens || {})),
470
+ JSON.stringify(safeAreaInsets || {})
471
+ )}
472
+
473
+ true;
474
+ `;
475
+
476
+ // handler for removing listeners
477
+ async function removeStorageListenerHandler(payload: { listenerId?: string }) {
478
+ const { listenerId } = payload || {};
479
+
480
+ if (!listenerId) {
481
+ return;
482
+ }
483
+
484
+ const removeListener = activeListeners[listenerId];
485
+
486
+ if (removeListener) {
487
+ try {
488
+ removeListener();
489
+ delete activeListeners[listenerId];
490
+ } catch (error) {
491
+ //
492
+ }
493
+ }
494
+ }
495
+
496
+ function log({ level, messages }) {
497
+ try {
498
+ const parsedMessages = parseJsonIfNeeded(messages);
499
+ const logFn = console[level] || console.log;
500
+
501
+ if (Array.isArray(parsedMessages)) {
502
+ logFn("JS LOG:", ...parsedMessages);
503
+ } else {
504
+ logFn("JS LOG:", parsedMessages);
505
+ }
506
+ } catch (e) {
507
+ // console.error("Error parsing or logging JS message:", e, messages);
508
+ }
509
+ }
510
+
511
+ async function storageGetItem({ key, namespace }) {
512
+ try {
513
+ const result = await sessionStorage.getItem(key, namespace);
514
+
515
+ return { success: true, value: result };
516
+ } catch (error) {
517
+ return { success: false, error: error.message };
518
+ }
519
+ }
520
+
521
+ async function storageSetItem({ key, value, namespace }) {
522
+ try {
523
+ const result = await sessionStorage.setItem(key, value, namespace);
524
+
525
+ return { success: !!result };
526
+ } catch (error) {
527
+ return { success: false, error: error.message };
528
+ }
529
+ }
530
+
531
+ async function localStorageGetItem({ key, namespace }) {
532
+ try {
533
+ const result = await localStorage.getItem(key, namespace);
534
+
535
+ return { success: true, value: result };
536
+ } catch (error) {
537
+ return { success: false, error: error.message };
538
+ }
539
+ }
540
+
541
+ async function localStorageSetItem({ key, value, namespace }) {
542
+ try {
543
+ const result = await localStorage.setItem(key, value, namespace);
544
+
545
+ return { success: !!result };
546
+ } catch (error) {
547
+ return { success: false, error: error.message };
548
+ }
549
+ }
550
+
551
+ async function secureStorageGetItem({ key, namespace }) {
552
+ try {
553
+ const result = await localStorage.getKeychainItem(key, namespace);
554
+
555
+ return { success: true, value: result };
556
+ } catch (error) {
557
+ return { success: false, error: error.message };
558
+ }
559
+ }
560
+
561
+ async function secureStorageSetItem({ key, value, namespace }) {
562
+ try {
563
+ const result = await localStorage.setKeychainItem(key, value, namespace);
564
+
565
+ return { success: !!result };
566
+ } catch (error) {
567
+ return { success: false, error: error.message };
568
+ }
569
+ }
570
+
571
+ // handler for adding listeners
572
+ async function addStorageListenerHandler(
573
+ storageType: "local" | "session",
574
+ payload: { key?: string; namespace?: string },
575
+ callbackKey: string,
576
+ webViewRef: React.RefObject<any>
577
+ ) {
578
+ if (!webViewRef?.current?.injectJavaScript) {
579
+ return;
580
+ }
581
+
582
+ const storage = storageType === "local" ? localStorage : sessionStorage;
583
+ const { key, namespace } = payload || {};
584
+
585
+ const listenerCallback = (eventData: {
586
+ key: string;
587
+ namespace: string;
588
+ value: any;
589
+ }) => {
590
+ const run = invokeWebCallback(callbackKey, [eventData]);
591
+
592
+ if (webViewRef?.current?.injectJavaScript) {
593
+ webViewRef.current.injectJavaScript(run);
594
+ } else {
595
+ removeStorageListenerHandler({ listenerId: callbackKey });
596
+ }
597
+ };
598
+
599
+ try {
600
+ const removeListener = storage.addListener(
601
+ { key, namespace },
602
+ listenerCallback
603
+ );
604
+
605
+ activeListeners[callbackKey] = removeListener;
606
+ } catch (error) {
607
+ const errorRun = invokeWebCallback(callbackKey, [
608
+ { success: false, error: `Failed to add listener: ${error.message}` },
609
+ ]);
610
+
611
+ if (webViewRef?.current?.injectJavaScript) {
612
+ webViewRef.current.injectJavaScript(errorRun);
613
+
614
+ webViewRef.current.injectJavaScript(
615
+ `delete window.Applicaster.${APPLICASTER_CALLBACK_KEY}['${callbackKey}']; true;`
616
+ );
617
+ }
618
+
619
+ delete activeListeners[callbackKey];
620
+ }
621
+ }
622
+
623
+ export function resolveBridgeAction(
624
+ type: string,
625
+ webViewRef: React.RefObject<any>
626
+ ) {
627
+ switch (type) {
628
+ case JS_BRIDGE_EVENTS.LOG:
629
+ return (payload) => log(payload);
630
+
631
+ case JS_BRIDGE_EVENTS.GET_SESSION_STORAGE:
632
+ return storageGetItem;
633
+ case JS_BRIDGE_EVENTS.SET_SESSION_STORAGE:
634
+ return storageSetItem;
635
+ case JS_BRIDGE_EVENTS.GET_LOCAL_STORAGE:
636
+ return localStorageGetItem;
637
+ case JS_BRIDGE_EVENTS.SET_LOCAL_STORAGE:
638
+ return localStorageSetItem;
639
+ case JS_BRIDGE_EVENTS.GET_SECURE_LOCAL_STORAGE:
640
+ return secureStorageGetItem;
641
+ case JS_BRIDGE_EVENTS.SET_SECURE_LOCAL_STORAGE:
642
+ return secureStorageSetItem;
643
+
644
+ case JS_BRIDGE_EVENTS.ADD_LOCAL_STORAGE_LISTENER:
645
+ return (payload, callbackKey) =>
646
+ addStorageListenerHandler("local", payload, callbackKey, webViewRef);
647
+
648
+ case JS_BRIDGE_EVENTS.REMOVE_LOCAL_STORAGE_LISTENER:
649
+ return (payload) => removeStorageListenerHandler(payload);
650
+
651
+ case JS_BRIDGE_EVENTS.ADD_SESSION_STORAGE_LISTENER:
652
+ return (payload, callbackKey) =>
653
+ addStorageListenerHandler("session", payload, callbackKey, webViewRef);
654
+
655
+ case JS_BRIDGE_EVENTS.REMOVE_SESSION_STORAGE_LISTENER:
656
+ return (payload) => removeStorageListenerHandler(payload);
657
+
658
+ default:
659
+ return async (_payload, callbackKey) => {
660
+ if (callbackKey && webViewRef?.current?.injectJavaScript) {
661
+ const errorResult = {
662
+ success: false,
663
+ error: `Unknown action type: ${type}`,
664
+ };
665
+
666
+ const errorRun = invokeWebCallback(callbackKey, [errorResult]);
667
+ webViewRef.current.injectJavaScript(errorRun);
668
+ }
669
+
670
+ return Promise.reject(new Error(`Unknown action type: ${type}`));
671
+ };
672
+ }
673
+ }