catalyst-core 0.0.3-canary.9 → 0.1.0-beta.2

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 (182) hide show
  1. package/README.md +4 -5
  2. package/bin/catalyst.js +28 -15
  3. package/changelog.md +139 -30
  4. package/dist/native/androidProject/app/build.gradle.kts +125 -15
  5. package/dist/native/androidProject/app/proguard-rules.pro +85 -14
  6. package/dist/native/androidProject/app/src/debug/res/xml/network_security_config.xml +8 -0
  7. package/dist/native/androidProject/app/src/main/AndroidManifest.xml +10 -3
  8. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/BridgeMessageValidator.kt +552 -0
  9. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/CatalystConstants.kt +109 -0
  10. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/CustomWebview.kt +605 -124
  11. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/MainActivity.kt +405 -47
  12. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/MetricsMonitor.kt +341 -0
  13. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/NativeBridge.kt +954 -71
  14. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/SplashActivity.kt +111 -0
  15. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/URLWhitelistManager.kt +231 -0
  16. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/Utils.kt +49 -55
  17. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/WebCacheManager.kt +81 -8
  18. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/design/DesignTokens.kt +307 -0
  19. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/EmulatorDetector.kt +203 -0
  20. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/FridaDetector.kt +187 -0
  21. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityAlertHandler.kt +170 -0
  22. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityAlertUI.kt +366 -0
  23. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityBottomSheet.kt +138 -0
  24. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityCheckManager.kt +511 -0
  25. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityCheckScheduler.kt +68 -0
  26. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/BridgeUtils.kt +47 -11
  27. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/DeviceInfoUtils.kt +38 -13
  28. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/DownloadUtils.kt +36 -14
  29. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/FileUtils.kt +3 -2
  30. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/FrameworkServerUtils.kt +57 -8
  31. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/IntentUtils.kt +31 -6
  32. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/KeyboardUtil.kt +82 -0
  33. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/NetworkUtils.kt +105 -0
  34. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/NotificationConstants.kt +28 -0
  35. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/NotificationUtils.kt +639 -0
  36. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/SafeAreaUtils.kt +62 -0
  37. package/dist/native/androidProject/app/src/main/res/drawable/splashscreen_fallback.png +0 -0
  38. package/dist/native/androidProject/app/src/main/res/layout/activity_main.xml +1 -0
  39. package/dist/native/androidProject/app/src/main/res/layout/activity_splash.xml +20 -0
  40. package/dist/native/androidProject/app/src/main/res/values/themes.xml +23 -0
  41. package/dist/native/androidProject/app/src/main/res/values-night/themes.xml +11 -0
  42. package/dist/native/androidProject/app/src/main/res/xml/network_security_config.xml +12 -0
  43. package/dist/native/androidProject/app/src/noFcm/java/io/yourname/androidproject/utils/NotificationManager.kt +166 -0
  44. package/dist/native/androidProject/app/src/noFcm/java/io/yourname/androidproject/utils/PushNotificationUtils.kt +94 -0
  45. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/BridgeMessageValidatorTest.kt +267 -0
  46. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/BridgeUtilsTest.kt +286 -0
  47. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/CameraUtilsTest.kt +296 -0
  48. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/ConfigMappingTest.kt +594 -0
  49. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/CustomWebviewTest.kt +466 -0
  50. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/DeviceInfoUtilsTest.kt +187 -0
  51. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/FileUtilsTest.kt +304 -0
  52. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/NativeBridgeTest.kt +424 -0
  53. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/NotificationUtilsTest.kt +469 -0
  54. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/SecurityBridgeTest.kt +199 -0
  55. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/URLWhitelistManagerTest.kt +462 -0
  56. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/WebCacheManagerTest.kt +391 -0
  57. package/dist/native/androidProject/app/src/withFcm/java/io/yourname/androidproject/utils/NotificationManager.kt +224 -0
  58. package/dist/native/androidProject/app/src/withFcm/java/io/yourname/androidproject/utils/PushNotificationUtils.kt +399 -0
  59. package/dist/native/androidProject/build.gradle.kts +6 -0
  60. package/dist/native/androidProject/gradle/libs.versions.toml +8 -2
  61. package/dist/native/androidSetup.js +4 -3
  62. package/dist/native/assets/catalyst.png +0 -0
  63. package/dist/native/bridge/WebBridge.js +16 -3
  64. package/dist/native/bridge/constants/NativeInterfaces.js +28 -10
  65. package/dist/native/bridge/errors.js +1 -1
  66. package/dist/native/bridge/hooks.js +76 -16
  67. package/dist/native/bridge/safeArea.js +5 -0
  68. package/dist/native/bridge/standardizedHooks.js +23 -5
  69. package/dist/native/bridge/useBaseHook.js +7 -9
  70. package/dist/native/bridge/utils/CameraUtils.js +58 -0
  71. package/dist/native/bridge/utils/FileObjectConverter.js +40 -0
  72. package/dist/native/bridge/utils/NativeBridge.js +57 -8
  73. package/dist/native/buildAppAndroid.js +115 -43
  74. package/dist/native/buildAppIos.js +291 -26
  75. package/dist/native/iosnativeWebView/Configurations/Debug.xcconfig +21 -0
  76. package/dist/native/iosnativeWebView/Configurations/Release.xcconfig +24 -0
  77. package/dist/native/iosnativeWebView/Configurations/Shared.xcconfig +50 -0
  78. package/dist/native/iosnativeWebView/Package.resolved +32 -0
  79. package/dist/native/iosnativeWebView/Package.swift +37 -0
  80. package/dist/native/iosnativeWebView/Sources/CatalystNotifications/LocalNotificationHandler.swift +293 -0
  81. package/dist/native/iosnativeWebView/Sources/CatalystNotifications/NotificationManager.swift +299 -0
  82. package/dist/native/iosnativeWebView/Sources/CatalystNotifications/PushNotificationHandler.swift +199 -0
  83. package/dist/native/iosnativeWebView/Sources/Core/Constants/CatalystConstants.swift +125 -0
  84. package/dist/native/iosnativeWebView/Sources/Core/Constants/ConfigConstants.swift +70 -0
  85. package/dist/native/iosnativeWebView/Sources/Core/Notifications/NotificationModels.swift +156 -0
  86. package/dist/native/iosnativeWebView/Sources/Core/Protocols/NotificationHandlerProtocol.swift +35 -0
  87. package/dist/native/iosnativeWebView/Sources/Core/Utils/BootTimingUtility.swift +26 -0
  88. package/dist/native/iosnativeWebView/{iosnativeWebView → Sources/Core/Utils}/CacheManager.swift +69 -36
  89. package/dist/native/iosnativeWebView/Sources/Core/Utils/CameraTransportUtils.swift +363 -0
  90. package/dist/native/iosnativeWebView/Sources/Core/Utils/DeviceInfoUtils.swift +67 -0
  91. package/dist/native/iosnativeWebView/Sources/Core/Utils/FilePickerHandler.swift +1053 -0
  92. package/dist/native/iosnativeWebView/Sources/Core/Utils/FrameworkServerUtils.swift +901 -0
  93. package/dist/native/iosnativeWebView/{iosnativeWebView → Sources/Core/Utils}/ImageHandler.swift +206 -20
  94. package/dist/native/iosnativeWebView/Sources/Core/Utils/NetworkMonitor.swift +112 -0
  95. package/dist/native/iosnativeWebView/Sources/Core/Utils/NotificationHandlerProvider.swift +20 -0
  96. package/dist/native/iosnativeWebView/Sources/Core/Utils/NullNotificationHandler.swift +85 -0
  97. package/dist/native/iosnativeWebView/{iosnativeWebView → Sources/Core/Utils}/ResourceURLProtocol.swift +60 -25
  98. package/dist/native/iosnativeWebView/Sources/Core/Utils/SafeAreaUtils.swift +132 -0
  99. package/dist/native/iosnativeWebView/Sources/Core/Utils/ScreenSecureManager.swift +131 -0
  100. package/dist/native/iosnativeWebView/Sources/Core/Utils/URLWhitelistManager.swift +224 -0
  101. package/dist/native/iosnativeWebView/Sources/Core/Utils/WebKitConfig.swift +43 -0
  102. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeCommandHandler.swift +991 -0
  103. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeDelegateHandler.swift +166 -0
  104. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeFileHandler.swift +340 -0
  105. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeJavaScriptInterface.swift +149 -0
  106. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeMessageValidator.swift +611 -0
  107. package/dist/native/iosnativeWebView/Sources/Core/WebView/NativeBridge.swift +334 -0
  108. package/dist/native/iosnativeWebView/Sources/Core/WebView/SplashView.swift +95 -0
  109. package/dist/native/iosnativeWebView/Sources/Core/WebView/SplashViewModel.swift +86 -0
  110. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebView.swift +181 -0
  111. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebViewModel.swift +182 -0
  112. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebViewNavigationDelegate.swift +395 -0
  113. package/dist/native/iosnativeWebView/iosnativeWebView/AppDelegate.swift +84 -0
  114. package/dist/native/iosnativeWebView/iosnativeWebView/Assets.xcassets/AccentColor.colorset/Contents.json +8 -8
  115. package/dist/native/iosnativeWebView/iosnativeWebView/Assets.xcassets/AppIcon.appiconset/Contents.json +10 -10
  116. package/dist/native/iosnativeWebView/iosnativeWebView/Assets.xcassets/Contents.json +4 -4
  117. package/dist/native/iosnativeWebView/iosnativeWebView/ContentView.swift +65 -10
  118. package/dist/native/iosnativeWebView/iosnativeWebView/Info-Release.plist +21 -0
  119. package/dist/native/iosnativeWebView/iosnativeWebView/Info.plist +13 -0
  120. package/dist/native/iosnativeWebView/iosnativeWebView/Preview Content/Preview Assets.xcassets/Contents.json +4 -4
  121. package/dist/native/iosnativeWebView/iosnativeWebView/iosnativeWebView.entitlements +12 -0
  122. package/dist/native/iosnativeWebView/iosnativeWebView/iosnativeWebViewApp.swift +80 -0
  123. package/dist/native/iosnativeWebView/iosnativeWebView/localhost.p12 +0 -0
  124. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/project.pbxproj +118 -100
  125. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +69 -0
  126. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/xcshareddata/xcschemes/iosnativeWebView.xcscheme +9 -4
  127. package/dist/native/iosnativeWebView/iosnativeWebView.xctestplan +47 -0
  128. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BootTimingUtilityTests.swift +236 -0
  129. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BridgeCommandHandlerSecurityTests.swift +212 -0
  130. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BridgeMessageValidatorTests.swift +418 -0
  131. package/dist/native/iosnativeWebView/iosnativeWebViewTests/CacheManagerTests.swift +390 -0
  132. package/dist/native/iosnativeWebView/iosnativeWebViewTests/ConfigMappingTests.swift +299 -0
  133. package/dist/native/iosnativeWebView/iosnativeWebViewTests/FilePickerHandlerTests.swift +383 -0
  134. package/dist/native/iosnativeWebView/iosnativeWebViewTests/FrameworkServerUtilsTests.swift +391 -0
  135. package/dist/native/iosnativeWebView/iosnativeWebViewTests/NativeBridgeTests.swift +581 -0
  136. package/dist/native/iosnativeWebView/iosnativeWebViewTests/NotificationHandlerTests.swift +430 -0
  137. package/dist/native/iosnativeWebView/iosnativeWebViewTests/ScreenSecureManagerTests.swift +121 -0
  138. package/dist/native/iosnativeWebView/iosnativeWebViewTests/URLWhitelistManagerTests.swift +367 -0
  139. package/dist/native/iosnativeWebView/iosnativeWebViewTests/WebViewTests.swift +440 -0
  140. package/dist/native/renameAndroidProject.js +80 -70
  141. package/dist/native/setupEmulatorIos.js +22 -5
  142. package/dist/native/setupServer.js +11 -10
  143. package/dist/native/terminalProgress.js +10 -10
  144. package/dist/native/utils.js +4 -5
  145. package/dist/otel.js +4 -0
  146. package/dist/scripts/build.js +2 -2
  147. package/dist/scripts/devBuild.js +2 -2
  148. package/dist/scripts/loadEnvironmentVariables.js +3 -1
  149. package/dist/scripts/scriptUtils.js +2 -2
  150. package/dist/sentry.js +4 -1
  151. package/dist/server/renderer/document/Body.js +4 -4
  152. package/dist/server/renderer/handler.js +7 -5
  153. package/dist/webpack/development.client.babel.js +1 -1
  154. package/mcp_v2/conversion-tasks.json +326 -0
  155. package/mcp_v2/knowledge-base.json +1068 -0
  156. package/mcp_v2/lib/helpers.js +165 -0
  157. package/mcp_v2/mcp.js +563 -0
  158. package/mcp_v2/package.json +13 -0
  159. package/mcp_v2/schema.sql +88 -0
  160. package/mcp_v2/setup.js +278 -0
  161. package/mcp_v2/tools/build.js +686 -0
  162. package/mcp_v2/tools/config.js +453 -0
  163. package/mcp_v2/tools/conversion.js +799 -0
  164. package/mcp_v2/tools/debug.js +113 -0
  165. package/mcp_v2/tools/knowledge.js +219 -0
  166. package/mcp_v2/tools/sync.js +23 -0
  167. package/mcp_v2/tools/tasks.js +945 -0
  168. package/package.json +11 -15
  169. package/dist/native/androidProject/.idea/.name +0 -1
  170. package/dist/native/androidProject/.idea/AndroidProjectSystem.xml +0 -6
  171. package/dist/native/androidProject/.idea/compiler.xml +0 -6
  172. package/dist/native/androidProject/.idea/deploymentTargetSelector.xml +0 -10
  173. package/dist/native/androidProject/.idea/gradle.xml +0 -18
  174. package/dist/native/androidProject/.idea/migrations.xml +0 -10
  175. package/dist/native/androidProject/.idea/misc.xml +0 -10
  176. package/dist/native/androidProject/.idea/runConfigurations.xml +0 -17
  177. package/dist/native/androidProject/.idea/vcs.xml +0 -6
  178. package/dist/native/iosnativeWebView/iosnativeWebView/NativeBridge.swift +0 -217
  179. package/dist/native/iosnativeWebView/iosnativeWebView/WebView.swift +0 -96
  180. package/dist/native/iosnativeWebView/iosnativeWebView/WebViewModel.swift +0 -47
  181. package/dist/native/iosnativeWebView/iosnativeWebView/WebViewNavigationDelegate.swift +0 -140
  182. package/license +0 -10
@@ -0,0 +1,991 @@
1
+ //
2
+ // BridgeCommandHandler.swift
3
+ // iosnativeWebView
4
+ //
5
+ // Native command implementations for WebView bridge
6
+ // Extracted from NativeBridge.swift for better separation of concerns
7
+ //
8
+
9
+ import Foundation
10
+ import UIKit
11
+ import AVFoundation
12
+ import WebKit
13
+ import os
14
+ import UserNotifications
15
+ #if canImport(GoogleSignIn)
16
+ import GoogleSignIn
17
+ #endif
18
+
19
+ private let commandLogger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "com.app", category: CatalystConstants.Logging.Categories.commandHandler)
20
+
21
+ // MARK: - Command Handler Delegate
22
+
23
+ protocol BridgeCommandHandlerDelegate: AnyObject {
24
+ func sendStringCallback(eventName: String, data: String)
25
+ func sendJSONCallback(eventName: String, data: [String: Any])
26
+ func sendErrorCallback(eventName: String, error: String, code: String)
27
+ }
28
+
29
+ // MARK: - Bridge Command Handler
30
+
31
+ class BridgeCommandHandler {
32
+
33
+ private weak var viewController: UIViewController?
34
+ private weak var webView: WKWebView?
35
+ private let imageHandler: ImageHandler
36
+ private let filePickerHandler: FilePickerHandler
37
+ private weak var delegate: BridgeCommandHandlerDelegate?
38
+
39
+ // Notification handler - injected, defaults to null implementation
40
+ private var notificationHandler: NotificationHandlerProtocol = NullNotificationHandler.shared
41
+ private var isGoogleSignInInProgress = false
42
+ private var hasAttemptedGoogleRestore = false
43
+ private var lastConfiguredGoogleClientId: String?
44
+
45
+ private struct GoogleSignInOptions {
46
+ let clientId: String?
47
+ let nonce: String?
48
+ let hint: String?
49
+ let additionalScopes: [String]?
50
+ let autoSelect: Bool
51
+ let filterByAuthorizedAccounts: Bool
52
+
53
+ static func from(params: Any?) -> GoogleSignInOptions {
54
+ if let stringParam = params as? String, !stringParam.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
55
+ if let data = stringParam.data(using: .utf8),
56
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
57
+ return GoogleSignInOptions.fromDictionary(json)
58
+ }
59
+
60
+ let trimmed = stringParam.trimmingCharacters(in: .whitespacesAndNewlines)
61
+ return GoogleSignInOptions(
62
+ clientId: trimmed,
63
+ nonce: nil,
64
+ hint: nil,
65
+ additionalScopes: nil,
66
+ autoSelect: false,
67
+ filterByAuthorizedAccounts: false
68
+ )
69
+ }
70
+
71
+ if let dict = params as? [String: Any] {
72
+ return GoogleSignInOptions.fromDictionary(dict)
73
+ }
74
+
75
+ return GoogleSignInOptions(
76
+ clientId: nil,
77
+ nonce: nil,
78
+ hint: nil,
79
+ additionalScopes: nil,
80
+ autoSelect: false,
81
+ filterByAuthorizedAccounts: false
82
+ )
83
+ }
84
+
85
+ private static func fromDictionary(_ dict: [String: Any]) -> GoogleSignInOptions {
86
+ func clean(_ value: String?) -> String? {
87
+ guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { return nil }
88
+ return value
89
+ }
90
+
91
+ let resolvedClientId = clean(dict["clientId"] as? String) ??
92
+ clean(dict["webClientId"] as? String)
93
+
94
+ let nonce = clean(dict["nonce"] as? String)
95
+ let hint = clean(dict["hint"] as? String ?? dict["email"] as? String)
96
+ var scopes: [String]?
97
+
98
+ if let scopesArray = dict["additionalScopes"] as? [String] {
99
+ let filtered = scopesArray.compactMap { clean($0) }
100
+ scopes = filtered.isEmpty ? nil : filtered
101
+ } else if let scopesString = clean(dict["additionalScopes"] as? String) {
102
+ let splitScopes = scopesString.split(separator: ",").map { clean(String($0)) }.compactMap { $0 }
103
+ scopes = splitScopes.isEmpty ? nil : splitScopes
104
+ }
105
+
106
+ return GoogleSignInOptions(
107
+ clientId: resolvedClientId,
108
+ nonce: nonce,
109
+ hint: hint,
110
+ additionalScopes: scopes,
111
+ autoSelect: dict["autoSelect"] as? Bool ?? false,
112
+ filterByAuthorizedAccounts: dict["filterByAuthorizedAccounts"] as? Bool ?? false
113
+ )
114
+ }
115
+ }
116
+
117
+ init(viewController: UIViewController, imageHandler: ImageHandler, filePickerHandler: FilePickerHandler) {
118
+ self.viewController = viewController
119
+ self.imageHandler = imageHandler
120
+ self.filePickerHandler = filePickerHandler
121
+
122
+ commandLogger.debug("BridgeCommandHandler initialized")
123
+ commandLogger.debug("Notifications enabled: \(ConfigConstants.Notifications.enabled)")
124
+ }
125
+
126
+ // Inject webView reference for commands that need direct WKWebView access
127
+ func setWebView(_ webView: WKWebView) {
128
+ self.webView = webView
129
+ }
130
+
131
+ // Inject notification handler (called from AppDelegate when notifications enabled)
132
+ func setNotificationHandler(_ handler: NotificationHandlerProtocol) {
133
+ self.notificationHandler = handler
134
+ commandLogger.debug("Notification handler injected: \(type(of: handler))")
135
+ }
136
+
137
+ deinit {
138
+ commandLogger.debug("BridgeCommandHandler deallocated")
139
+ }
140
+
141
+ // MARK: - Delegate Management
142
+
143
+ func setDelegate(_ delegate: BridgeCommandHandlerDelegate) {
144
+ self.delegate = delegate
145
+ }
146
+
147
+ // MARK: - Command Implementations
148
+
149
+ // Open camera and capture image
150
+ func openCamera(options: String? = nil) {
151
+ commandLogger.debug("openCamera called with options: \(options ?? "nil")")
152
+
153
+ // Parse options if provided
154
+ let cameraOptions = parseCameraOptions(from: options)
155
+ commandLogger.debug("Parsed camera options: \(cameraOptions)")
156
+
157
+ // Try to find a valid UIViewController from the window hierarchy
158
+ var presentingViewController: UIViewController?
159
+
160
+ if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
161
+ let rootVC = scene.windows.first?.rootViewController {
162
+ // Use the root view controller or find a presented controller
163
+ presentingViewController = rootVC.presentedViewController ?? rootVC
164
+ } else {
165
+ // Fallback to the provided viewController
166
+ presentingViewController = viewController
167
+ }
168
+
169
+ guard let presentingVC = presentingViewController else {
170
+ commandLogger.error("No valid view controller available")
171
+ delegate?.sendErrorCallback(eventName: "ON_CAMERA_ERROR", error: "No valid view controller available", code: "VIEW_CONTROLLER_UNAVAILABLE")
172
+ return
173
+ }
174
+
175
+ imageHandler.checkCameraPermission { [weak self] granted in
176
+ guard let self = self else { return }
177
+
178
+ if granted {
179
+ self.imageHandler.presentCamera(from: presentingVC, options: cameraOptions)
180
+ } else {
181
+ commandLogger.error("Camera permission denied")
182
+ self.delegate?.sendJSONCallback(eventName: "CAMERA_PERMISSION_STATUS", data: ["status": "DENIED"])
183
+ self.imageHandler.presentPermissionAlert(from: presentingVC)
184
+ }
185
+ }
186
+ }
187
+
188
+ func requestCameraPermission(config: String? = nil) {
189
+ commandLogger.debug("Camera permission requested with config: \(config ?? "nil")")
190
+
191
+ // Parse config if provided
192
+ let permissionConfig = parsePermissionConfig(from: config)
193
+ commandLogger.debug("Parsed permission config: \(permissionConfig)")
194
+
195
+ imageHandler.checkCameraPermission { [weak self] granted in
196
+ guard let self = self else { return }
197
+
198
+ let permissionStatus = granted ? "GRANTED" : "DENIED"
199
+ commandLogger.debug("Camera permission status: \(permissionStatus)")
200
+
201
+ // Create enhanced response with config consideration
202
+ var response: [String: Any] = [
203
+ "status": permissionStatus,
204
+ "timestamp": ISO8601DateFormatter().string(from: Date()),
205
+ "platform": "ios"
206
+ ]
207
+
208
+ // Add additional info if config requested it
209
+ if let includeDetails = permissionConfig["includeDetails"] as? Bool, includeDetails {
210
+ response["authorizationStatus"] = self.getCameraAuthorizationStatusString()
211
+ response["cameraAvailable"] = UIImagePickerController.isSourceTypeAvailable(.camera)
212
+ }
213
+
214
+ self.delegate?.sendJSONCallback(eventName: "CAMERA_PERMISSION_STATUS", data: response)
215
+ }
216
+ }
217
+
218
+ // Request haptic feedback
219
+ func requestHapticFeedback(feedbackType: String = "VIRTUAL_KEY") {
220
+ commandLogger.debug("requestHapticFeedback called with type: \(feedbackType)")
221
+
222
+ // Check if device supports haptics (iOS 10+)
223
+ guard #available(iOS 10.0, *) else {
224
+ commandLogger.warning("Haptic feedback not supported on this iOS version")
225
+ delegate?.sendErrorCallback(eventName: "HAPTIC_FEEDBACK", error: "Haptic feedback not supported on this iOS version", code: "HAPTIC_NOT_SUPPORTED")
226
+ return
227
+ }
228
+
229
+ DispatchQueue.main.async {
230
+ let type = feedbackType.uppercased()
231
+ let feedbackGenerator: UIImpactFeedbackGenerator
232
+
233
+ switch type {
234
+ case "VIRTUAL_KEY":
235
+ feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
236
+ case "LONG_PRESS":
237
+ feedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
238
+ case "DEFAULT":
239
+ feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
240
+ default:
241
+ commandLogger.debug("Unknown haptic type '\(type)', using default (.light)")
242
+ feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
243
+ }
244
+
245
+ // Prepare and trigger haptic feedback
246
+ feedbackGenerator.prepare()
247
+ feedbackGenerator.impactOccurred()
248
+
249
+ commandLogger.debug("Haptic feedback performed: \(type)")
250
+ self.delegate?.sendJSONCallback(eventName: "HAPTIC_FEEDBACK", data: [
251
+ "status": "success",
252
+ "type": type,
253
+ "platform": "ios"
254
+ ])
255
+ }
256
+ }
257
+
258
+ func googleSignIn(params: Any?) {
259
+ #if canImport(GoogleSignIn)
260
+ guard ConfigConstants.GoogleSignIn.enabled else {
261
+ delegate?.sendErrorCallback(
262
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
263
+ error: "Google Sign-In is disabled in config",
264
+ code: "GOOGLE_SIGN_IN_ERROR"
265
+ )
266
+ return
267
+ }
268
+
269
+ let options = GoogleSignInOptions.from(params: params)
270
+
271
+ let resolvedClientId = (options.clientId ?? ConfigConstants.GoogleSignIn.clientId)
272
+ .trimmingCharacters(in: .whitespacesAndNewlines)
273
+
274
+ guard !resolvedClientId.isEmpty else {
275
+ delegate?.sendErrorCallback(
276
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
277
+ error: "clientId is required for Google Sign-In",
278
+ code: "GOOGLE_SIGN_IN_ERROR"
279
+ )
280
+ return
281
+ }
282
+
283
+ guard !isGoogleSignInInProgress else {
284
+ delegate?.sendErrorCallback(
285
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
286
+ error: "A Google Sign-In request is already in progress",
287
+ code: "GOOGLE_SIGN_IN_ERROR"
288
+ )
289
+ return
290
+ }
291
+
292
+ guard let presentingVC = resolvePresentingViewController() else {
293
+ delegate?.sendErrorCallback(
294
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
295
+ error: "No valid view controller available for Google Sign-In",
296
+ code: "GOOGLE_SIGN_IN_ERROR"
297
+ )
298
+ return
299
+ }
300
+
301
+ isGoogleSignInInProgress = true
302
+ commandLogger.debug("Starting Google Sign-In with clientId prefix: \(resolvedClientId.prefix(12))...")
303
+
304
+ configureGoogleSignIn(clientId: resolvedClientId)
305
+
306
+ if options.autoSelect || options.filterByAuthorizedAccounts {
307
+ commandLogger.debug("Google Sign-In options autoSelect/filterByAuthorizedAccounts are not supported on iOS SDK and will be ignored")
308
+ }
309
+
310
+ DispatchQueue.main.async { [weak self] in
311
+ guard let self = self else { return }
312
+ GIDSignIn.sharedInstance.signIn(
313
+ withPresenting: presentingVC,
314
+ hint: options.hint,
315
+ additionalScopes: options.additionalScopes
316
+ ) { [weak self] result, error in
317
+ guard let self = self else { return }
318
+ self.isGoogleSignInInProgress = false
319
+
320
+ let hasValidUserData = result?.user != nil && result?.user.idToken?.tokenString != nil
321
+
322
+ if let error = error as NSError? {
323
+ if self.isCancelledGoogleError(error) {
324
+ self.delegate?.sendErrorCallback(
325
+ eventName: "ON_GOOGLE_SIGN_IN_CANCELLED",
326
+ error: "User cancelled Google sign-in",
327
+ code: "OPERATION_CANCELLED"
328
+ )
329
+ return
330
+ }
331
+
332
+ let errorDescription = error.localizedDescription.lowercased()
333
+ let isKeychainError = errorDescription.contains("keychain")
334
+
335
+ if isKeychainError && hasValidUserData {
336
+ commandLogger.warning("Google Sign-In keychain error (common on simulators), but user data is valid: \(error.localizedDescription)")
337
+ } else {
338
+ commandLogger.error("Google Sign-In error: \(error.localizedDescription)")
339
+ self.delegate?.sendErrorCallback(
340
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
341
+ error: error.localizedDescription,
342
+ code: "GOOGLE_SIGN_IN_ERROR"
343
+ )
344
+ return
345
+ }
346
+ }
347
+
348
+ guard let user = result?.user, let idToken = user.idToken?.tokenString else {
349
+ self.delegate?.sendErrorCallback(
350
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
351
+ error: "No ID token returned from Google sign-in",
352
+ code: "GOOGLE_SIGN_IN_ERROR"
353
+ )
354
+ return
355
+ }
356
+
357
+ var payload: [String: Any] = [
358
+ "idToken": idToken,
359
+ "provider": "google"
360
+ ]
361
+
362
+ if let email = user.profile?.email, !email.isEmpty {
363
+ payload["email"] = email
364
+ }
365
+
366
+ if let name = user.profile?.name, !name.isEmpty {
367
+ payload["name"] = name
368
+ }
369
+
370
+ if let photoUrl = user.profile?.imageURL(withDimension: 160)?.absoluteString, !photoUrl.isEmpty {
371
+ payload["photoUrl"] = photoUrl
372
+ }
373
+
374
+ if let serverAuthCode = result?.serverAuthCode, !serverAuthCode.isEmpty {
375
+ payload["serverAuthCode"] = serverAuthCode
376
+ }
377
+
378
+ commandLogger.debug("Google Sign-In success (idToken length: \(idToken.count))")
379
+ self.delegate?.sendJSONCallback(eventName: "ON_GOOGLE_SIGN_IN_SUCCESS", data: payload)
380
+ }
381
+ }
382
+ #else
383
+ delegate?.sendErrorCallback(
384
+ eventName: "ON_GOOGLE_SIGN_IN_ERROR",
385
+ error: "Google Sign-In SDK not available on this build",
386
+ code: "GOOGLE_SIGN_IN_UNAVAILABLE"
387
+ )
388
+ #endif
389
+ }
390
+
391
+ // Get device information
392
+ func getDeviceInfo() {
393
+ commandLogger.debug("getDeviceInfo called")
394
+
395
+ let deviceInfo = DeviceInfoUtils.getDeviceInfo()
396
+
397
+ // Check if there was an error
398
+ if let error = deviceInfo["error"] as? String {
399
+ commandLogger.error("Failed to get device info: \(error)")
400
+ delegate?.sendErrorCallback(
401
+ eventName: "ON_DEVICE_INFO_ERROR",
402
+ error: error,
403
+ code: "DEVICE_INFO_ERROR"
404
+ )
405
+ return
406
+ }
407
+
408
+ delegate?.sendJSONCallback(eventName: "ON_DEVICE_INFO_SUCCESS", data: deviceInfo)
409
+ }
410
+
411
+ // Log message (test function)
412
+ func logger() {
413
+ commandLogger.debug("Message from native")
414
+ delegate?.sendJSONCallback(eventName: "ON_LOGGER", data: ["message": "From native, with regards"])
415
+ }
416
+
417
+ // Pick file from device storage
418
+ func pickFile(options optionsString: String? = nil) {
419
+ commandLogger.debug("pickFile called with options: \(optionsString ?? "nil")")
420
+ let options = FilePickerOptions.from(raw: optionsString)
421
+ commandLogger.debug("Parsed file picker options: \(options)")
422
+
423
+ // Try to find a valid UIViewController from the window hierarchy
424
+ var presentingViewController: UIViewController?
425
+
426
+ if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
427
+ let rootVC = scene.windows.first?.rootViewController {
428
+ // Use the root view controller or find a presented controller
429
+ presentingViewController = rootVC.presentedViewController ?? rootVC
430
+ } else {
431
+ // Fallback to the provided viewController
432
+ presentingViewController = viewController
433
+ }
434
+
435
+ guard let presentingVC = presentingViewController else {
436
+ commandLogger.error("No valid view controller available")
437
+ delegate?.sendErrorCallback(eventName: "ON_FILE_PICK_ERROR", error: "No valid view controller available", code: "VIEW_CONTROLLER_UNAVAILABLE")
438
+ return
439
+ }
440
+
441
+ filePickerHandler.presentFilePicker(from: presentingVC, options: options)
442
+ }
443
+
444
+ // MARK: - Security Methods
445
+
446
+ /// Enable or disable screen-secure mode (app-switcher overlay).
447
+ /// Payload: { "enable": true/false } or bare boolean string.
448
+ func setScreenSecure(params: Any?) {
449
+ let enable: Bool
450
+
451
+ if let dict = params as? [String: Any], let val = dict["enable"] as? Bool {
452
+ enable = val
453
+ } else if let str = params as? String,
454
+ let jsonData = str.data(using: .utf8),
455
+ let dict = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],
456
+ let val = dict["enable"] as? Bool {
457
+ // params arrived as JSON string e.g. '{"enable":true}' — parse it
458
+ enable = val
459
+ commandLogger.debug("setScreenSecure: parsed enable from JSON string → \(enable)")
460
+ } else if let str = params as? String {
461
+ enable = str.lowercased() == "true" || str == "1"
462
+ } else {
463
+ commandLogger.error("setScreenSecure: invalid or missing params")
464
+ delegate?.sendJSONCallback(eventName: "ON_SCREEN_SECURE_ERROR", data: [
465
+ "success": false,
466
+ "error": "Invalid params: expected {enable: bool}"
467
+ ])
468
+ return
469
+ }
470
+
471
+ DispatchQueue.main.async { [weak self] in
472
+ guard let self else { return }
473
+ ScreenSecureManager.shared.setScreenSecure(enable)
474
+ let secure = ScreenSecureManager.shared.isScreenSecure
475
+ commandLogger.debug("setScreenSecure → \(secure)")
476
+ self.delegate?.sendJSONCallback(eventName: "ON_SCREEN_SECURE_SET", data: [
477
+ "secure": secure,
478
+ "success": true
479
+ ])
480
+ }
481
+ }
482
+
483
+ /// Query whether screen-secure mode is currently active.
484
+ func getScreenSecure() {
485
+ DispatchQueue.main.async { [weak self] in
486
+ guard let self else { return }
487
+ let secure = ScreenSecureManager.shared.isScreenSecure
488
+ commandLogger.debug("getScreenSecure → \(secure)")
489
+ self.delegate?.sendJSONCallback(eventName: "ON_SCREEN_SECURE_STATUS", data: [
490
+ "secure": secure,
491
+ "success": true
492
+ ])
493
+ }
494
+ }
495
+
496
+ /// Clear all WKWebView data: cache, cookies, local storage, IndexedDB.
497
+ /// Fires ON_WEB_DATA_CLEARED only after the async removal completes.
498
+ func clearWebData() {
499
+ commandLogger.debug("clearWebData called")
500
+
501
+ guard let webView else {
502
+ commandLogger.debug("clearWebData: webView is nil, skipping")
503
+ return
504
+ }
505
+ let dataTypes = WKWebsiteDataStore.allWebsiteDataTypes()
506
+ let store = webView.configuration.websiteDataStore
507
+
508
+ store.removeData(ofTypes: dataTypes, modifiedSince: .distantPast) { [weak self] in
509
+ guard let self else { return }
510
+ CacheManager.shared.clearCache()
511
+ commandLogger.debug("clearWebData complete")
512
+ DispatchQueue.main.async {
513
+ self.delegate?.sendJSONCallback(eventName: "ON_WEB_DATA_CLEARED", data: [
514
+ "success": true
515
+ ])
516
+ }
517
+ }
518
+ }
519
+
520
+ // MARK: - Helper Methods
521
+
522
+ // Helper method to parse camera options from string parameter
523
+ private func parseCameraOptions(from options: String?) -> [String: Any] {
524
+ var cameraOptions: [String: Any] = [:]
525
+
526
+ // Set defaults matching Android implementation
527
+ cameraOptions["quality"] = "medium"
528
+ cameraOptions["format"] = "jpeg"
529
+ cameraOptions["allowEditing"] = false
530
+
531
+ guard let optionsString = options, !optionsString.isEmpty else {
532
+ commandLogger.debug("No camera options provided, using defaults")
533
+ return cameraOptions
534
+ }
535
+
536
+ do {
537
+ // Try to parse as JSON
538
+ if let data = optionsString.data(using: .utf8),
539
+ let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
540
+
541
+ // Merge with defaults, allowing JSON to override
542
+ for (key, value) in json {
543
+ cameraOptions[key] = value
544
+ }
545
+ commandLogger.debug("Successfully parsed camera options from JSON")
546
+ } else {
547
+ // Fallback: treat as simple quality string
548
+ cameraOptions["quality"] = optionsString.lowercased()
549
+ commandLogger.debug("Treated camera options as quality string: \(optionsString)")
550
+ }
551
+ } catch {
552
+ commandLogger.warning("Failed to parse camera options JSON, treating as quality string: \(error.localizedDescription)")
553
+ cameraOptions["quality"] = optionsString.lowercased()
554
+ }
555
+
556
+ return cameraOptions
557
+ }
558
+
559
+ // Helper method to parse permission config from string parameter
560
+ private func parsePermissionConfig(from config: String?) -> [String: Any] {
561
+ var permissionConfig: [String: Any] = [:]
562
+
563
+ // Set defaults
564
+ permissionConfig["includeDetails"] = false
565
+
566
+ guard let configString = config, !configString.isEmpty else {
567
+ commandLogger.debug("No permission config provided, using defaults")
568
+ return permissionConfig
569
+ }
570
+
571
+ do {
572
+ // Try to parse as JSON
573
+ if let data = configString.data(using: .utf8),
574
+ let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
575
+
576
+ // Merge with defaults, allowing JSON to override
577
+ for (key, value) in json {
578
+ permissionConfig[key] = value
579
+ }
580
+ commandLogger.debug("Successfully parsed permission config from JSON")
581
+ } else {
582
+ // Fallback: treat as simple boolean string for includeDetails
583
+ let boolValue = configString.lowercased() == "true" || configString == "1"
584
+ permissionConfig["includeDetails"] = boolValue
585
+ commandLogger.debug("Treated permission config as includeDetails boolean: \(boolValue)")
586
+ }
587
+ } catch {
588
+ commandLogger.warning("Failed to parse permission config JSON, treating as boolean: \(error.localizedDescription)")
589
+ let boolValue = configString.lowercased() == "true" || configString == "1"
590
+ permissionConfig["includeDetails"] = boolValue
591
+ }
592
+
593
+ return permissionConfig
594
+ }
595
+
596
+ // Helper method to get camera authorization status as string (matching Android format)
597
+ private func getCameraAuthorizationStatusString() -> String {
598
+ switch AVCaptureDevice.authorizationStatus(for: .video) {
599
+ case .authorized:
600
+ return "GRANTED" // Match Android GRANTED
601
+ case .notDetermined:
602
+ return "NOT_DETERMINED" // Match Android NOT_DETERMINED
603
+ case .denied:
604
+ return "DENIED" // Match Android DENIED
605
+ case .restricted:
606
+ return "RESTRICTED" // Match Android RESTRICTED
607
+ @unknown default:
608
+ return "DENIED" // Default to DENIED for unknown states
609
+ }
610
+ }
611
+
612
+ // MARK: - Configuration
613
+
614
+ // Update view controller reference if needed
615
+ func updateViewController(_ newViewController: UIViewController) {
616
+ self.viewController = newViewController
617
+ commandLogger.debug("View controller reference updated in command handler")
618
+ }
619
+
620
+ // MARK: - Notification Methods
621
+
622
+ // TODO: replace json data parsing with file intent flow logic
623
+ func requestNotificationPermission() {
624
+ // Check if notifications are enabled in config
625
+ guard ConfigConstants.Notifications.enabled else {
626
+ commandLogger.warning("Notification permission requested but notifications are disabled in config")
627
+ delegate?.sendStringCallback(eventName: "NOTIFICATION_PERMISSION_STATUS", data: "DENIED")
628
+ return
629
+ }
630
+
631
+ commandLogger.debug("Notification permission requested")
632
+
633
+ Task { [weak self] in
634
+ guard let self else { return }
635
+ let granted = await self.notificationHandler.requestPermission()
636
+ let status = granted ? "GRANTED" : "DENIED"
637
+
638
+ await MainActor.run {
639
+ guard let delegate = self.delegate else {
640
+ commandLogger.debug("Delegate released before NOTIFICATION_PERMISSION_STATUS callback")
641
+ return
642
+ }
643
+ // Send plain string to match Android's BridgeUtils.notifyWeb format
644
+ delegate.sendStringCallback(eventName: "NOTIFICATION_PERMISSION_STATUS", data: status)
645
+ commandLogger.debug("Notification permission granted: \(granted)")
646
+ }
647
+ }
648
+ }
649
+
650
+ func checkNotificationPermissionStatus() {
651
+ // Check if notifications are enabled in config
652
+ guard ConfigConstants.Notifications.enabled else {
653
+ commandLogger.warning("Check notification permission status called but notifications are disabled in config")
654
+ delegate?.sendStringCallback(eventName: "NOTIFICATION_PERMISSION_STATUS", data: "DENIED")
655
+ return
656
+ }
657
+
658
+ commandLogger.debug("Checking notification permission status")
659
+
660
+ Task { [weak self] in
661
+ guard let self else { return }
662
+ let status = await self.notificationHandler.getPermissionStatusString()
663
+
664
+ await MainActor.run {
665
+ guard let delegate = self.delegate else {
666
+ commandLogger.debug("Delegate released before NOTIFICATION_PERMISSION_STATUS callback")
667
+ return
668
+ }
669
+ delegate.sendStringCallback(eventName: "NOTIFICATION_PERMISSION_STATUS", data: status)
670
+ commandLogger.debug("Notification permission status: \(status)")
671
+ }
672
+ }
673
+ }
674
+
675
+ func scheduleLocalNotification(_ configString: String?) {
676
+ // Check if notifications are enabled in config
677
+ guard ConfigConstants.Notifications.enabled else {
678
+ commandLogger.warning("Local notification requested but notifications are disabled in config")
679
+ delegate?.sendJSONCallback(eventName: "LOCAL_NOTIFICATION_SCHEDULED", data: [
680
+ "success": false,
681
+ "error": "Notifications disabled in configuration"
682
+ ])
683
+ return
684
+ }
685
+
686
+ // Log the raw input for debugging
687
+ if let configString = configString {
688
+ commandLogger.debug("Received notification config string: \(configString)")
689
+ } else {
690
+ commandLogger.error("Received nil config string")
691
+ }
692
+
693
+ guard let configString = configString,
694
+ let data = configString.data(using: .utf8),
695
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
696
+ let title = json["title"] as? String,
697
+ let body = json["body"] as? String else {
698
+ commandLogger.error("Invalid notification configuration - failed to parse JSON")
699
+ if let configString = configString {
700
+ commandLogger.error("Failed config string was: \(configString)")
701
+ }
702
+ delegate?.sendJSONCallback(eventName: "LOCAL_NOTIFICATION_SCHEDULED", data: [
703
+ "success": false,
704
+ "error": "Invalid configuration"
705
+ ])
706
+ return
707
+ }
708
+
709
+ // Parse notification config and map to NotificationConfig model
710
+ let channel = (json["channel"] as? String)
711
+ ?? ((json["sound"] as? String) == "urgent" ? "urgent" : "default")
712
+ let style = (json["style"] as? String) ?? "BASIC"
713
+ let largeImage = json["largeImage"] as? String
714
+ let priority = json["priority"] as? Int ?? 0
715
+ let vibrate = json["vibrate"] as? Bool ?? true
716
+ let autoCancel = json["autoCancel"] as? Bool ?? true
717
+ let dataDict = json["data"] as? [String: Any]
718
+
719
+ var actionsConfig: [NotificationAction]? = nil
720
+ if let actionsArray = json["actions"] as? [[String: Any]] {
721
+ actionsConfig = actionsArray.compactMap { item in
722
+ let title = item["title"] as? String ?? ""
723
+ let action = item["action"] as? String ?? ""
724
+ return (title.isEmpty || action.isEmpty) ? nil : NotificationAction(title: title, action: action)
725
+ }
726
+ }
727
+
728
+ let config = NotificationConfig(
729
+ title: title,
730
+ body: body,
731
+ channel: channel,
732
+ badge: json["badge"] as? Int,
733
+ largeImage: largeImage,
734
+ style: style,
735
+ priority: priority,
736
+ vibrate: vibrate,
737
+ autoCancel: autoCancel,
738
+ data: dataDict,
739
+ actions: actionsConfig
740
+ )
741
+
742
+ commandLogger.debug("Scheduling local notification")
743
+ let notificationId = notificationHandler.scheduleLocal(config)
744
+
745
+ commandLogger.debug("Local notification scheduled with ID: \(notificationId)")
746
+
747
+ // Send back the notification ID like Android does
748
+ delegate?.sendJSONCallback(eventName: "LOCAL_NOTIFICATION_SCHEDULED", data: [
749
+ "notificationId": notificationId,
750
+ "scheduled": true
751
+ ])
752
+ }
753
+
754
+ func cancelLocalNotification(_ notificationId: String?) {
755
+ // Check if notifications are enabled in config
756
+ guard ConfigConstants.Notifications.enabled else {
757
+ commandLogger.warning("Cancel notification requested but notifications are disabled in config")
758
+ delegate?.sendJSONCallback(eventName: "LOCAL_NOTIFICATION_CANCELLED", data: [
759
+ "notificationId": notificationId ?? "",
760
+ "success": false,
761
+ "error": "Notifications disabled in configuration"
762
+ ])
763
+ return
764
+ }
765
+
766
+ guard let notificationId = notificationId else {
767
+ commandLogger.error("Missing notification ID")
768
+ return
769
+ }
770
+
771
+ let success = notificationHandler.cancelLocal(notificationId)
772
+ commandLogger.debug("Cancelled notification \(notificationId): \(success)")
773
+
774
+ delegate?.sendJSONCallback(eventName: "LOCAL_NOTIFICATION_CANCELLED", data: [
775
+ "notificationId": notificationId,
776
+ "success": success
777
+ ])
778
+ }
779
+
780
+ func registerForPushNotifications() {
781
+ // Check if notifications are enabled in config
782
+ guard ConfigConstants.Notifications.enabled else {
783
+ commandLogger.warning("Push notification registration requested but notifications are disabled in config")
784
+ delegate?.sendJSONCallback(eventName: "PUSH_NOTIFICATION_TOKEN", data: [
785
+ "success": false,
786
+ "error": "Notifications disabled in configuration"
787
+ ])
788
+ return
789
+ }
790
+
791
+ commandLogger.debug("Registering for push notifications")
792
+
793
+ Task { [weak self] in
794
+ guard let self else { return }
795
+ let (token, error) = await self.notificationHandler.initializePush()
796
+
797
+ await MainActor.run {
798
+ guard let delegate = self.delegate else {
799
+ commandLogger.debug("Delegate released before PUSH_NOTIFICATION_TOKEN callback")
800
+ return
801
+ }
802
+ if let token = token {
803
+ delegate.sendJSONCallback(eventName: "PUSH_NOTIFICATION_TOKEN", data: [
804
+ "token": token,
805
+ "success": true
806
+ ])
807
+ } else {
808
+ let errorMessage = error ?? "Failed to get push token"
809
+ commandLogger.error("Push notification registration failed: \(errorMessage)")
810
+ delegate.sendJSONCallback(eventName: "PUSH_NOTIFICATION_TOKEN", data: [
811
+ "success": false,
812
+ "error": errorMessage
813
+ ])
814
+ }
815
+ }
816
+ }
817
+ }
818
+
819
+ func subscribeToTopic(_ configString: String?) {
820
+ // Check if notifications are enabled in config
821
+ guard ConfigConstants.Notifications.enabled else {
822
+ commandLogger.warning("Topic subscription requested but notifications are disabled in config")
823
+ delegate?.sendJSONCallback(eventName: "TOPIC_SUBSCRIPTION_RESULT", data: [
824
+ "success": false,
825
+ "error": "Notifications disabled in configuration",
826
+ "action": "subscribe"
827
+ ])
828
+ return
829
+ }
830
+
831
+ guard let configString = configString,
832
+ let data = configString.data(using: .utf8),
833
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
834
+ let topic = json["topic"] as? String else {
835
+ commandLogger.error("Invalid topic subscription configuration")
836
+ delegate?.sendJSONCallback(eventName: "TOPIC_SUBSCRIPTION_RESULT", data: [
837
+ "success": false,
838
+ "error": "Invalid topic configuration"
839
+ ])
840
+ return
841
+ }
842
+
843
+ commandLogger.debug("Subscribing to topic: \(topic)")
844
+
845
+ Task { [weak self, topic] in
846
+ guard let self else { return }
847
+ let success = await self.notificationHandler.subscribeToTopic(topic)
848
+
849
+ await MainActor.run {
850
+ guard let delegate = self.delegate else {
851
+ commandLogger.debug("Delegate released before TOPIC_SUBSCRIPTION_RESULT (subscribe) callback")
852
+ return
853
+ }
854
+ delegate.sendJSONCallback(eventName: "TOPIC_SUBSCRIPTION_RESULT", data: [
855
+ "topic": topic,
856
+ "success": success,
857
+ "action": "subscribe"
858
+ ])
859
+ }
860
+ }
861
+ }
862
+
863
+ func unsubscribeFromTopic(_ configString: String?) {
864
+ // Check if notifications are enabled in config
865
+ guard ConfigConstants.Notifications.enabled else {
866
+ commandLogger.warning("Topic unsubscription requested but notifications are disabled in config")
867
+ delegate?.sendJSONCallback(eventName: "TOPIC_SUBSCRIPTION_RESULT", data: [
868
+ "success": false,
869
+ "error": "Notifications disabled in configuration",
870
+ "action": "unsubscribe"
871
+ ])
872
+ return
873
+ }
874
+
875
+ guard let configString = configString,
876
+ let data = configString.data(using: .utf8),
877
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
878
+ let topic = json["topic"] as? String else {
879
+ commandLogger.error("Invalid topic unsubscription configuration")
880
+ delegate?.sendJSONCallback(eventName: "TOPIC_SUBSCRIPTION_RESULT", data: [
881
+ "success": false,
882
+ "error": "Invalid topic configuration"
883
+ ])
884
+ return
885
+ }
886
+
887
+ commandLogger.debug("Unsubscribing from topic: \(topic)")
888
+
889
+ Task { [weak self, topic] in
890
+ guard let self else { return }
891
+ let success = await self.notificationHandler.unsubscribeFromTopic(topic)
892
+
893
+ await MainActor.run {
894
+ guard let delegate = self.delegate else {
895
+ commandLogger.debug("Delegate released before TOPIC_SUBSCRIPTION_RESULT (unsubscribe) callback")
896
+ return
897
+ }
898
+ delegate.sendJSONCallback(eventName: "TOPIC_SUBSCRIPTION_RESULT", data: [
899
+ "topic": topic,
900
+ "success": success,
901
+ "action": "unsubscribe"
902
+ ])
903
+ }
904
+ }
905
+ }
906
+
907
+ func getSubscribedTopics() {
908
+ // Check if notifications are enabled in config
909
+ guard ConfigConstants.Notifications.enabled else {
910
+ commandLogger.warning("Get subscribed topics requested but notifications are disabled in config")
911
+ delegate?.sendJSONCallback(eventName: "SUBSCRIBED_TOPICS_RESULT", data: [
912
+ "topics": [],
913
+ "success": false,
914
+ "error": "Notifications disabled in configuration"
915
+ ])
916
+ return
917
+ }
918
+
919
+ commandLogger.debug("Getting subscribed topics")
920
+
921
+ Task { [weak self] in
922
+ guard let self else { return }
923
+ let topics = await self.notificationHandler.getSubscribedTopics()
924
+
925
+ await MainActor.run {
926
+ guard let delegate = self.delegate else {
927
+ commandLogger.debug("Delegate released before SUBSCRIBED_TOPICS_RESULT callback")
928
+ return
929
+ }
930
+ delegate.sendJSONCallback(eventName: "SUBSCRIBED_TOPICS_RESULT", data: [
931
+ "topics": topics,
932
+ "success": true
933
+ ])
934
+ }
935
+ }
936
+ }
937
+
938
+ // MARK: - Helpers
939
+
940
+ private func resolvePresentingViewController() -> UIViewController? {
941
+ if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
942
+ if let window = scene.windows.first(where: { $0.isKeyWindow }),
943
+ let rootVC = window.rootViewController {
944
+ return rootVC.presentedViewController ?? rootVC
945
+ }
946
+ }
947
+
948
+ return viewController
949
+ }
950
+
951
+ private func configureGoogleSignIn(clientId: String) {
952
+ guard lastConfiguredGoogleClientId != clientId else { return }
953
+ lastConfiguredGoogleClientId = clientId
954
+
955
+ let iosClientId = ConfigConstants.GoogleSignIn.iosClientId
956
+ let serverClientId = clientId // This is the Web Client ID
957
+ let configClientId = !iosClientId.isEmpty ? iosClientId : serverClientId
958
+
959
+ GIDSignIn.sharedInstance.configuration = GIDConfiguration(
960
+ clientID: configClientId,
961
+ serverClientID: serverClientId
962
+ )
963
+
964
+ if !hasAttemptedGoogleRestore {
965
+ hasAttemptedGoogleRestore = true
966
+ GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
967
+ if let error = error {
968
+ commandLogger.debug("Google Sign-In restore failed: \(error.localizedDescription)")
969
+ } else if user != nil {
970
+ commandLogger.debug("Google Sign-In restored previous session")
971
+ } else {
972
+ commandLogger.debug("Google Sign-In restore found no previous user")
973
+ }
974
+ }
975
+ }
976
+ }
977
+
978
+ private func isCancelledGoogleError(_ error: NSError) -> Bool {
979
+ let description = error.localizedDescription.lowercased()
980
+ if description.contains("cancel") {
981
+ return true
982
+ }
983
+
984
+ // GIDSignIn cancellation historically uses code -5; keep the check resilient
985
+ if error.code == -5 {
986
+ return true
987
+ }
988
+
989
+ return false
990
+ }
991
+ }