catalyst-core 0.1.0-canary.9 → 0.2.0-beta.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 (136) hide show
  1. package/README.md +1 -1
  2. package/bin/catalyst.js +8 -1
  3. package/changelog.md +6 -0
  4. package/dist/native/androidProject/app/build.gradle.kts +9 -0
  5. package/dist/native/androidProject/app/src/main/AndroidManifest.xml +2 -1
  6. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/BridgeMessageValidator.kt +1 -1
  7. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/CustomWebview.kt +31 -3
  8. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/MainActivity.kt +31 -3
  9. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/NativeBridge.kt +148 -0
  10. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/NativeCameraManager.kt +337 -0
  11. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/TransitionManager.kt +202 -0
  12. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/WebCacheManager.kt +22 -15
  13. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/BarcodeDetector.kt +123 -0
  14. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/CameraSessionManager.kt +244 -0
  15. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/HoldController.kt +70 -0
  16. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/TorchController.kt +57 -0
  17. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/VideoStreamState.kt +41 -0
  18. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/VideoStreamStateMachine.kt +40 -0
  19. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/ViewfinderMapper.kt +75 -0
  20. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/camera/ZoomController.kt +156 -0
  21. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/plugins/CatalystPlugin.kt +7 -0
  22. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/plugins/GeneratedPluginIndex.kt +6 -0
  23. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/plugins/PluginBridge.kt +253 -0
  24. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/FridaDetector.kt +16 -5
  25. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/BridgeUtils.kt +42 -5
  26. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/FrameworkServerUtils.kt +7 -3
  27. package/dist/native/androidProject/app/src/main/res/drawable/debug_viewfinder_border.xml +8 -0
  28. package/dist/native/androidProject/app/src/main/res/layout/activity_main.xml +37 -0
  29. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/plugins/PluginBridgeTest.kt +139 -0
  30. package/dist/native/androidSetup.js +1 -0
  31. package/dist/native/bridge/WebBridge.js +5 -5
  32. package/dist/native/bridge/constants/NativeInterfaces.js +9 -5
  33. package/dist/native/bridge/hooks/index.js +1 -0
  34. package/dist/native/bridge/hooks/useCamera.js +9 -0
  35. package/dist/native/bridge/hooks/useDataProtection.js +2 -0
  36. package/dist/native/bridge/hooks/useDeviceInfo.js +2 -0
  37. package/dist/native/bridge/hooks/useFilePicker.js +2 -0
  38. package/dist/native/bridge/hooks/useGoogleSignIn.js +1 -0
  39. package/dist/native/bridge/hooks/useHapticFeedback.js +1 -0
  40. package/dist/native/bridge/hooks/useIntent.js +1 -0
  41. package/dist/native/bridge/hooks/useNativeTransition.js +43 -0
  42. package/dist/native/bridge/hooks/useNetworkStatus.js +3 -0
  43. package/dist/native/bridge/hooks/useNotification.js +2 -0
  44. package/dist/native/bridge/hooks/useSafeArea.js +2 -0
  45. package/dist/native/bridge/hooks/useVideoStream.js +6 -0
  46. package/dist/native/bridge/hooks/utils.js +1 -0
  47. package/dist/native/bridge/hooks.js +1 -137
  48. package/dist/native/bridge/useBaseHook.js +12 -7
  49. package/dist/native/bridge/utils/NativeBridge.js +41 -6
  50. package/dist/native/buildAndroid/assets.js +52 -0
  51. package/dist/native/buildAndroid/build.js +19 -0
  52. package/dist/native/buildAndroid/config.js +1 -0
  53. package/dist/native/buildAndroid/index.js +1 -0
  54. package/dist/native/buildAppAndroid.js +2 -150
  55. package/dist/native/buildAppIos.js +2 -312
  56. package/dist/native/buildIos/assets.js +8 -0
  57. package/dist/native/buildIos/build.js +40 -0
  58. package/dist/native/buildIos/config.js +71 -0
  59. package/dist/native/buildIos/index.js +6 -0
  60. package/dist/native/buildIos/plugins.js +45 -0
  61. package/dist/native/internalPluginUtils.js +7 -0
  62. package/dist/native/iosnativeWebView/Package.resolved +36 -0
  63. package/dist/native/iosnativeWebView/Sources/Core/Camera/BarcodeDetector.swift +116 -0
  64. package/dist/native/iosnativeWebView/Sources/Core/Camera/CameraPreviewView.swift +58 -0
  65. package/dist/native/iosnativeWebView/Sources/Core/Camera/CameraSessionManager.swift +308 -0
  66. package/dist/native/iosnativeWebView/Sources/Core/Camera/HoldController.swift +63 -0
  67. package/dist/native/iosnativeWebView/Sources/Core/Camera/NativeCameraManager.swift +194 -0
  68. package/dist/native/iosnativeWebView/Sources/Core/Camera/TorchController.swift +60 -0
  69. package/dist/native/iosnativeWebView/Sources/Core/Camera/VideoStreamState.swift +44 -0
  70. package/dist/native/iosnativeWebView/Sources/Core/Camera/VideoStreamStateMachine.swift +60 -0
  71. package/dist/native/iosnativeWebView/Sources/Core/Camera/ZoomController.swift +130 -0
  72. package/dist/native/iosnativeWebView/Sources/Core/Constants/CatalystConstants.swift +11 -1
  73. package/dist/native/iosnativeWebView/Sources/Core/Constants/ConfigConstants.swift +2 -1
  74. package/dist/native/iosnativeWebView/Sources/Core/Plugins/CatalystPlugin.swift +5 -0
  75. package/dist/native/iosnativeWebView/Sources/Core/Plugins/GeneratedPluginIndex.swift +6 -0
  76. package/dist/native/iosnativeWebView/Sources/Core/Plugins/PluginBridge.swift +364 -0
  77. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeMessageValidator.swift +4 -1
  78. package/dist/native/iosnativeWebView/Sources/Core/WebView/NativeBridge.swift +227 -4
  79. package/dist/native/iosnativeWebView/Sources/Core/WebView/TransitionManager.swift +169 -0
  80. package/dist/native/iosnativeWebView/Sources/Core/WebView/WeakScriptMessageHandler.swift +14 -0
  81. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebView.swift +38 -7
  82. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebViewNavigationDelegate.swift +6 -2
  83. package/dist/native/iosnativeWebView/iosnativeWebView/ContentView.swift +30 -11
  84. package/dist/native/iosnativeWebView/iosnativeWebView/Info.plist +11 -17
  85. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/project.pbxproj +8 -2
  86. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BootTimingUtilityTests.swift +1 -1
  87. package/dist/native/iosnativeWebView/iosnativeWebViewTests/ConfigMappingTests.swift +4 -2
  88. package/dist/native/iosnativeWebView/iosnativeWebViewTests/PluginBridgeTests.swift +160 -0
  89. package/dist/native/plugin-bridge/PluginBridge.js +1 -0
  90. package/dist/native/pluginComposerAndroid.js +28 -0
  91. package/dist/native/pluginComposerIos.js +16 -0
  92. package/dist/native/renameAndroidProject.js +3 -3
  93. package/dist/native/setupEmulatorIos.js +6 -4
  94. package/dist/native/setupServer.js +2 -3
  95. package/dist/native/utils.js +4 -1
  96. package/dist/otel.js +70 -2
  97. package/dist/scripts/build.js +1 -1
  98. package/dist/scripts/cleanCache.js +1 -0
  99. package/dist/scripts/devBuild.js +1 -1
  100. package/dist/scripts/devServe.js +1 -1
  101. package/dist/scripts/loadEnvironmentVariables.js +1 -2
  102. package/dist/scripts/plugins.js +1 -0
  103. package/dist/scripts/registerAliases.js +6 -2
  104. package/dist/scripts/scriptUtils.js +2 -1
  105. package/dist/scripts/serve.js +2 -1
  106. package/dist/scripts/start.js +7 -2
  107. package/dist/server/expressServer.js +3 -8
  108. package/dist/server/renderer/document/Body.js +4 -4
  109. package/dist/server/renderer/document/Head.js +2 -2
  110. package/dist/server/renderer/extract.js +31 -27
  111. package/dist/server/renderer/handler.js +47 -24
  112. package/dist/server/renderer/index.js +1 -1
  113. package/dist/server/startServer.js +57 -7
  114. package/dist/server/utils/userAgentUtil.js +9 -3
  115. package/dist/server/utils/validator.js +1 -1
  116. package/dist/webpack/babel-plugins/remove-client.plugin.js +2 -2
  117. package/dist/webpack/babel-plugins/remove-ssr.plugin.js +2 -2
  118. package/dist/webpack/babel.config.client.js +1 -1
  119. package/dist/webpack/babel.config.ssr.js +1 -1
  120. package/dist/webpack/base.babel.js +7 -8
  121. package/dist/webpack/development.client.babel.js +7 -16
  122. package/dist/webpack/production.client.babel.js +1 -1
  123. package/dist/webpack/production.ssr.babel.js +5 -1
  124. package/mcp_v2/knowledge-base.json +193 -100
  125. package/mcp_v2/lib/helpers.js +42 -8
  126. package/mcp_v2/lib/seed.js +88 -0
  127. package/mcp_v2/mcp.js +150 -4
  128. package/mcp_v2/setup.js +30 -193
  129. package/mcp_v2/tools/build.js +1 -1
  130. package/mcp_v2/tools/config.js +16 -4
  131. package/mcp_v2/tools/conversion.js +11 -11
  132. package/mcp_v2/tools/github.js +1117 -0
  133. package/mcp_v2/tools/knowledge.js +16 -3
  134. package/mcp_v2/tools/sync.js +179 -10
  135. package/mcp_v2/tools/tasks.js +13 -4
  136. package/package.json +20 -8
@@ -0,0 +1,156 @@
1
+ package io.yourname.androidproject.camera
2
+
3
+ import android.animation.ValueAnimator
4
+ import android.util.Log
5
+ import android.view.MotionEvent
6
+ import android.view.ScaleGestureDetector
7
+ import android.view.animation.DecelerateInterpolator
8
+ import androidx.camera.core.Camera
9
+ import android.content.Context
10
+
11
+ /**
12
+ * Handles all zoom operations:
13
+ * - setZoom(multiplier: Float) via bridge — 1.0 = 1x, 2.0 = 2x
14
+ * - pinch-to-zoom via ScaleGestureDetector
15
+ * - auto-zoom suggestion callback (wired from BarcodeDetector)
16
+ *
17
+ * Fires ON_ZOOM_CHANGED via [onZoomChanged] callback after each zoom change.
18
+ * Payload: zoomLevel (Float multiplier, e.g. 1.5), minZoom, maxZoom.
19
+ */
20
+ class ZoomController(
21
+ context: Context,
22
+ private val stateMachine: VideoStreamStateMachine,
23
+ private val onZoomChanged: (zoomLevel: Float, minZoom: Float, maxZoom: Float) -> Unit
24
+ ) {
25
+
26
+ private val TAG = "ZoomController"
27
+
28
+ private var camera: Camera? = null
29
+
30
+ // Smooth auto-zoom state
31
+ private var zoomAnimator: ValueAnimator? = null
32
+ private var lastSuggestedRatio: Float = -1f
33
+ private var consecutiveSuggestionCount: Int = 0
34
+ private val SUGGESTION_CONFIRM_FRAMES = 2 // frames before committing to a zoom target
35
+ private val SUGGESTION_TOLERANCE = 0.1f // ratio delta considered "same target"
36
+ private val ZOOM_ANIMATION_DURATION_MS = 300L
37
+
38
+ private val scaleGestureDetector = ScaleGestureDetector(
39
+ context,
40
+ object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
41
+ override fun onScale(detector: ScaleGestureDetector): Boolean {
42
+ if (!stateMachine.isActive) return true
43
+ val cam = camera ?: return true
44
+ val zoomState = cam.cameraInfo.zoomState.value ?: return true
45
+ val newRatio = (zoomState.zoomRatio * detector.scaleFactor)
46
+ .coerceIn(zoomState.minZoomRatio, zoomState.maxZoomRatio)
47
+ cam.cameraControl.setZoomRatio(newRatio)
48
+ onZoomChanged(newRatio, zoomState.minZoomRatio, zoomState.maxZoomRatio)
49
+ return true
50
+ }
51
+ }
52
+ )
53
+
54
+ fun attachCamera(cam: Camera) {
55
+ camera = cam
56
+ }
57
+
58
+ fun detachCamera() {
59
+ cancelZoomAnimation()
60
+ camera = null
61
+ }
62
+
63
+ fun onTouchEvent(event: MotionEvent): Boolean {
64
+ return if (stateMachine.isActive) scaleGestureDetector.onTouchEvent(event) else false
65
+ }
66
+
67
+ /** Called from bridge: multiplier e.g. 1.0=1x, 2.0=2x */
68
+ fun setZoom(multiplier: Float) {
69
+ Log.d(TAG, "setZoom(${multiplier}x) called")
70
+ applyZoomMultiplier(multiplier)
71
+ }
72
+
73
+ fun applyZoomMultiplier(multiplier: Float) {
74
+ val cam = camera ?: run {
75
+ Log.w(TAG, "applyZoomMultiplier(${multiplier}x) — camera is null, skipping")
76
+ return
77
+ }
78
+ val zoomState = cam.cameraInfo.zoomState.value ?: run {
79
+ Log.w(TAG, "applyZoomMultiplier(${multiplier}x) — zoomState is null, skipping")
80
+ return
81
+ }
82
+ val min = zoomState.minZoomRatio
83
+ val max = zoomState.maxZoomRatio
84
+ val ratio = multiplier.coerceIn(min, max)
85
+ Log.d(TAG, "applyZoomMultiplier(${multiplier}x) → ratio=$ratio (min=$min max=$max)")
86
+ cam.cameraControl.setZoomRatio(ratio)
87
+ onZoomChanged(ratio, min, max)
88
+ }
89
+
90
+ /**
91
+ * Auto-zoom suggestion from ML Kit ZoomSuggestionOptions.
92
+ * Zoom-only-up guard: never apply a suggestion that would zoom out.
93
+ * Debounce: only commit after SUGGESTION_CONFIRM_FRAMES consecutive frames
94
+ * with the same target (within SUGGESTION_TOLERANCE).
95
+ * Animation: smoothly interpolates from current ratio to target over ZOOM_ANIMATION_DURATION_MS.
96
+ */
97
+ fun onAutoZoomSuggestion(suggestedRatio: Float): Boolean {
98
+ val cam = camera ?: return false
99
+ val zoomState = cam.cameraInfo.zoomState.value ?: return false
100
+ val clamped = suggestedRatio.coerceIn(zoomState.minZoomRatio, zoomState.maxZoomRatio)
101
+
102
+ // Zoom-only-up guard
103
+ if (clamped <= zoomState.zoomRatio) {
104
+ Log.d(TAG, "auto-zoom suggestion=$suggestedRatio ignored — would zoom out")
105
+ consecutiveSuggestionCount = 0
106
+ lastSuggestedRatio = -1f
107
+ return false
108
+ }
109
+
110
+ // Debounce: count consecutive frames pointing at the same target
111
+ if (Math.abs(clamped - lastSuggestedRatio) <= SUGGESTION_TOLERANCE) {
112
+ consecutiveSuggestionCount++
113
+ } else {
114
+ consecutiveSuggestionCount = 1
115
+ lastSuggestedRatio = clamped
116
+ }
117
+
118
+ if (consecutiveSuggestionCount < SUGGESTION_CONFIRM_FRAMES) {
119
+ Log.d(TAG, "auto-zoom debounce: $consecutiveSuggestionCount/$SUGGESTION_CONFIRM_FRAMES for target=$clamped")
120
+ return false
121
+ }
122
+
123
+ // Confirmed — reset counters and animate
124
+ consecutiveSuggestionCount = 0
125
+ lastSuggestedRatio = -1f
126
+
127
+ val fromRatio = zoomState.zoomRatio
128
+ val minZoom = zoomState.minZoomRatio
129
+ val maxZoom = zoomState.maxZoomRatio
130
+ Log.d(TAG, "auto-zoom: animating $fromRatio → $clamped")
131
+
132
+ zoomAnimator?.cancel()
133
+ zoomAnimator = ValueAnimator.ofFloat(fromRatio, clamped).apply {
134
+ duration = ZOOM_ANIMATION_DURATION_MS
135
+ interpolator = DecelerateInterpolator()
136
+ addUpdateListener { animator ->
137
+ val ratio = animator.animatedValue as Float
138
+ cam.cameraControl.setZoomRatio(ratio)
139
+ onZoomChanged(ratio, minZoom, maxZoom)
140
+ }
141
+ start()
142
+ }
143
+ return true
144
+ }
145
+
146
+ fun cancelZoomAnimation() {
147
+ zoomAnimator?.cancel()
148
+ zoomAnimator = null
149
+ consecutiveSuggestionCount = 0
150
+ lastSuggestedRatio = -1f
151
+ }
152
+
153
+ fun currentMaxZoomRatio(): Float {
154
+ return camera?.cameraInfo?.zoomState?.value?.maxZoomRatio ?: 8.0f
155
+ }
156
+ }
@@ -0,0 +1,7 @@
1
+ package io.yourname.androidproject.plugins
2
+
3
+ import org.json.JSONObject
4
+
5
+ interface CatalystPlugin {
6
+ fun handle(command: String, data: JSONObject?, bridge: PluginBridgeContext)
7
+ }
@@ -0,0 +1,6 @@
1
+ package io.yourname.androidproject.plugins
2
+
3
+ object GeneratedPluginIndex {
4
+ val pluginIdToClassName: Map<String, String> = emptyMap()
5
+ val pluginToCommands: Map<String, Set<String>> = emptyMap()
6
+ }
@@ -0,0 +1,253 @@
1
+ package io.yourname.androidproject.plugins
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.util.Log
6
+ import android.webkit.JavascriptInterface
7
+ import android.webkit.WebView
8
+ import io.yourname.androidproject.CatalystConstants
9
+ import org.json.JSONArray
10
+ import org.json.JSONException
11
+ import org.json.JSONObject
12
+ import java.util.Properties
13
+
14
+ internal data class PluginRequest(
15
+ val pluginId: String,
16
+ val command: String,
17
+ val data: JSONObject?,
18
+ val requestId: String?
19
+ )
20
+
21
+ private class PluginBridgeRuntimeError(
22
+ val publicMessage: String,
23
+ val code: String,
24
+ cause: Throwable? = null
25
+ ) : Exception(publicMessage, cause)
26
+
27
+ class PluginBridge(
28
+ private val activity: Activity,
29
+ private val webView: WebView,
30
+ private val properties: Properties
31
+ ) {
32
+ companion object {
33
+ private const val TAG = "PluginBridge"
34
+ private const val ERROR_EVENT = "PLUGIN_BRIDGE_ERROR"
35
+ private const val SYSTEM_PLUGIN_ID = "__bridge__"
36
+ private const val ERROR_CODE_INVALID_PAYLOAD = "INVALID_PAYLOAD"
37
+ private const val ERROR_CODE_PLUGIN_NOT_FOUND = "PLUGIN_NOT_FOUND"
38
+ private const val ERROR_CODE_COMMAND_NOT_SUPPORTED = "COMMAND_NOT_SUPPORTED"
39
+ private const val ERROR_CODE_PLUGIN_NOT_REGISTERED = "PLUGIN_NOT_REGISTERED"
40
+ private const val ERROR_CODE_PLUGIN_INSTANTIATION_FAILED = "PLUGIN_INSTANTIATION_FAILED"
41
+ private const val ERROR_CODE_PLUGIN_EXECUTION_FAILED = "PLUGIN_EXECUTION_FAILED"
42
+
43
+ private fun readRequiredString(body: JSONObject, key: String): String {
44
+ if (!body.has(key) || body.isNull(key)) {
45
+ return ""
46
+ }
47
+
48
+ val rawValue = body.get(key)
49
+ if (rawValue !is String) {
50
+ throw IllegalArgumentException("$key must be a string")
51
+ }
52
+
53
+ return rawValue.trim()
54
+ }
55
+
56
+ private fun readOptionalString(body: JSONObject, key: String): String? {
57
+ if (!body.has(key) || body.isNull(key)) {
58
+ return null
59
+ }
60
+
61
+ val rawValue = body.get(key)
62
+ if (rawValue !is String) {
63
+ throw IllegalArgumentException("$key must be a string when provided")
64
+ }
65
+
66
+ return rawValue.trim().ifEmpty { null }
67
+ }
68
+
69
+ private fun readOptionalObject(body: JSONObject, key: String): JSONObject? {
70
+ if (!body.has(key) || body.isNull(key)) {
71
+ return null
72
+ }
73
+
74
+ val rawValue = body.get(key)
75
+ if (rawValue !is JSONObject) {
76
+ throw IllegalArgumentException("$key must be an object when provided")
77
+ }
78
+
79
+ return rawValue
80
+ }
81
+
82
+ internal fun parseRequest(payload: String?): PluginRequest {
83
+ if (payload.isNullOrBlank()) {
84
+ throw IllegalArgumentException("Payload is required")
85
+ }
86
+ val messageSize = payload.toByteArray(Charsets.UTF_8).size
87
+ if (messageSize > CatalystConstants.Bridge.MAX_MESSAGE_SIZE) {
88
+ throw IllegalArgumentException("Payload exceeds maximum size")
89
+ }
90
+
91
+ val body = JSONObject(payload)
92
+ return PluginRequest(
93
+ pluginId = readRequiredString(body, "pluginId"),
94
+ command = readRequiredString(body, "command"),
95
+ data = readOptionalObject(body, "data"),
96
+ requestId = readOptionalString(body, "requestId")
97
+ )
98
+ }
99
+ }
100
+
101
+ private val pluginIdToClassName = GeneratedPluginIndex.pluginIdToClassName
102
+ private val pluginToCommands = GeneratedPluginIndex.pluginToCommands
103
+
104
+ @JavascriptInterface
105
+ fun emit(payload: String?) {
106
+ var request: PluginRequest? = null
107
+
108
+ try {
109
+ request = parseRequest(payload)
110
+
111
+ if (request.pluginId.isEmpty()) {
112
+ sendBridgeError("pluginId is required", ERROR_CODE_INVALID_PAYLOAD, request)
113
+ return
114
+ }
115
+ if (request.command.isEmpty()) {
116
+ sendBridgeError("command is required", ERROR_CODE_INVALID_PAYLOAD, request)
117
+ return
118
+ }
119
+
120
+ if (!hasPlugin(request.pluginId)) {
121
+ sendBridgeError("Unsupported plugin: ${request.pluginId}", ERROR_CODE_PLUGIN_NOT_FOUND, request)
122
+ return
123
+ }
124
+
125
+ if (!hasCommand(request.pluginId, request.command)) {
126
+ sendBridgeError(
127
+ "Unsupported command '${request.command}' for plugin '${request.pluginId}'",
128
+ ERROR_CODE_COMMAND_NOT_SUPPORTED,
129
+ request
130
+ )
131
+ return
132
+ }
133
+
134
+ val plugin = try {
135
+ getPluginForId(request.pluginId)
136
+ } catch (error: PluginBridgeRuntimeError) {
137
+ sendBridgeError(error.publicMessage, error.code, request)
138
+ return
139
+ }
140
+
141
+ val callbackContext = PluginBridgeContext(
142
+ activity = activity,
143
+ webView = webView,
144
+ properties = properties,
145
+ pluginId = request.pluginId,
146
+ command = request.command,
147
+ requestId = request.requestId
148
+ )
149
+
150
+ plugin.handle(request.command, request.data, callbackContext)
151
+ } catch (error: IllegalArgumentException) {
152
+ sendBridgeError(error.message ?: "Invalid payload", ERROR_CODE_INVALID_PAYLOAD, request)
153
+ } catch (error: JSONException) {
154
+ sendBridgeError("Invalid JSON payload", ERROR_CODE_INVALID_PAYLOAD, request)
155
+ } catch (error: Exception) {
156
+ Log.e(TAG, "Plugin command failed for ${request?.pluginId ?: "<unknown>"}.${request?.command ?: "<unknown>"}", error)
157
+ sendBridgeError("Plugin execution failed", ERROR_CODE_PLUGIN_EXECUTION_FAILED, request)
158
+ }
159
+ }
160
+
161
+ private fun sendBridgeError(message: String, code: String, request: PluginRequest?) {
162
+ PluginBridgeContext(
163
+ activity = activity,
164
+ webView = webView,
165
+ properties = properties,
166
+ pluginId = SYSTEM_PLUGIN_ID,
167
+ command = request?.command,
168
+ requestId = request?.requestId
169
+ ).callback(
170
+ ERROR_EVENT,
171
+ JSONObject().apply {
172
+ put("message", message)
173
+ put("code", code)
174
+ put("pluginId", request?.pluginId ?: SYSTEM_PLUGIN_ID)
175
+ request?.command?.takeIf { it.isNotEmpty() }?.let { put("command", it) }
176
+ }
177
+ )
178
+ }
179
+
180
+ private fun hasPlugin(pluginId: String): Boolean {
181
+ return pluginIdToClassName.containsKey(pluginId)
182
+ }
183
+
184
+ private fun hasCommand(pluginId: String, command: String): Boolean {
185
+ return pluginToCommands[pluginId]?.contains(command) ?: false
186
+ }
187
+
188
+ private fun getPluginForId(pluginId: String): CatalystPlugin {
189
+ val className = pluginIdToClassName[pluginId]
190
+ ?: throw PluginBridgeRuntimeError(
191
+ "Plugin is not registered",
192
+ ERROR_CODE_PLUGIN_NOT_REGISTERED
193
+ )
194
+
195
+ return try {
196
+ val clazz = Class.forName(className)
197
+ val instance = clazz.getDeclaredConstructor().newInstance()
198
+ instance as? CatalystPlugin
199
+ ?: throw IllegalStateException("Plugin class '$className' must implement CatalystPlugin")
200
+ } catch (error: Exception) {
201
+ Log.e(TAG, "Failed to instantiate plugin class $className for plugin $pluginId", error)
202
+ throw PluginBridgeRuntimeError(
203
+ "Plugin could not be initialized",
204
+ ERROR_CODE_PLUGIN_INSTANTIATION_FAILED,
205
+ error
206
+ )
207
+ }
208
+ }
209
+ }
210
+
211
+ class PluginBridgeContext(
212
+ val activity: Activity,
213
+ val webView: WebView,
214
+ val properties: Properties,
215
+ val pluginId: String,
216
+ val command: String?,
217
+ val requestId: String?
218
+ ) {
219
+ val context: Context
220
+ get() = activity
221
+
222
+ fun callback(
223
+ eventName: String,
224
+ data: Any?,
225
+ command: String? = this.command
226
+ ) {
227
+ require(eventName.isNotBlank()) { "Callback eventName is required" }
228
+
229
+ val pluginLiteral = JSONObject.quote(pluginId)
230
+ val eventLiteral = JSONObject.quote(eventName)
231
+ val dataLiteral = toJavaScriptLiteral(data)
232
+ val requestLiteral = requestId?.let(JSONObject::quote) ?: "null"
233
+ val commandLiteral = command?.takeIf { it.isNotBlank() }?.let(JSONObject::quote) ?: "null"
234
+
235
+ webView.post {
236
+ webView.evaluateJavascript(
237
+ "window.PluginBridgeWeb && window.PluginBridgeWeb.callback($pluginLiteral, $eventLiteral, $dataLiteral, $requestLiteral, $commandLiteral);",
238
+ null
239
+ )
240
+ }
241
+ }
242
+
243
+ private fun toJavaScriptLiteral(value: Any?): String {
244
+ return when (value) {
245
+ null -> "null"
246
+ is JSONObject -> value.toString()
247
+ is JSONArray -> value.toString()
248
+ is Number, is Boolean -> value.toString()
249
+ is String -> JSONObject.quote(value)
250
+ else -> JSONObject.wrap(value)?.toString() ?: "null"
251
+ }
252
+ }
253
+ }
@@ -5,7 +5,8 @@ import io.yourname.androidproject.utils.BridgeUtils
5
5
  import java.io.BufferedReader
6
6
  import java.io.File
7
7
  import java.io.InputStreamReader
8
- import java.net.Socket
8
+ import java.net.InetSocketAddress
9
+ import java.nio.channels.SocketChannel
9
10
 
10
11
  /**
11
12
  * Local Frida and hooking framework detection.
@@ -68,10 +69,20 @@ object FridaDetector {
68
69
  private fun checkFridaPorts(): Boolean {
69
70
  return FRIDA_PORTS.any { port ->
70
71
  try {
71
- Socket().use { socket ->
72
- val address = java.net.InetSocketAddress("127.0.0.1", port)
73
- socket.connect(address, 2000) // 2 second timeout
74
- socket.isConnected
72
+ SocketChannel.open().use { channel ->
73
+ val address = InetSocketAddress("127.0.0.1", port)
74
+ val deadline = System.currentTimeMillis() + 2000
75
+ channel.configureBlocking(false)
76
+ channel.connect(address)
77
+
78
+ while (!channel.finishConnect()) {
79
+ if (System.currentTimeMillis() >= deadline) {
80
+ return@use false
81
+ }
82
+ Thread.sleep(25)
83
+ }
84
+
85
+ true
75
86
  }
76
87
  } catch (e: Exception) {
77
88
  // Connection failed or timed out - no Frida on this port
@@ -76,12 +76,25 @@ object BridgeUtils {
76
76
  // Safe area events
77
77
  ON_SAFE_AREA_INSETS_UPDATED("ON_SAFE_AREA_INSETS_UPDATED"),
78
78
 
79
+ // Video stream events
80
+ ON_VIDEO_STREAM_READY("ON_VIDEO_STREAM_READY"),
81
+ ON_VIDEO_STREAM_STOPPED("ON_VIDEO_STREAM_STOPPED"),
82
+ ON_QR_DETECTED("ON_QR_DETECTED"),
83
+ ON_TORCH_CHANGED("ON_TORCH_CHANGED"),
84
+ ON_ZOOM_CHANGED("ON_ZOOM_CHANGED"),
85
+
79
86
  // Security events
80
87
  ON_SCREEN_SECURE_SET("ON_SCREEN_SECURE_SET"),
81
88
  ON_SCREEN_SECURE_STATUS("ON_SCREEN_SECURE_STATUS"),
82
89
  ON_SCREEN_SECURE_ERROR("ON_SCREEN_SECURE_ERROR"),
83
90
  ON_WEB_DATA_CLEARED("ON_WEB_DATA_CLEARED"),
84
91
  ON_WEB_DATA_CLEAR_ERROR("ON_WEB_DATA_CLEAR_ERROR"),
92
+
93
+ // Transition events
94
+ ON_TRANSITION_COMMITTED("ON_TRANSITION_COMMITTED"),
95
+ ON_TRANSITION_CANCELLED("ON_TRANSITION_CANCELLED"),
96
+ ON_TRANSITION_TIMEOUT("ON_TRANSITION_TIMEOUT"),
97
+
85
98
  }
86
99
 
87
100
  /**
@@ -99,13 +112,25 @@ object BridgeUtils {
99
112
  }
100
113
 
101
114
  try {
102
- val safeData = data?.replace("'", "\\'") ?: ""
103
115
  val jsCode = if (data != null) {
104
- "window.WebBridge.callback('${event.eventName}', '$safeData')"
116
+ // If data looks like a JSON object or array, inject it raw (with U+2028/U+2029
117
+ // escaping) so the JS side receives a live value rather than a double-encoded string.
118
+ // Otherwise wrap with JSONObject.quote() to produce a safe JS string literal.
119
+ val trimmed = data.trimStart()
120
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
121
+ (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
122
+ val safeData = data
123
+ .replace("
", "\\u2028")
124
+ .replace("
", "\\u2029")
125
+ "window.WebBridge.callback('${event.eventName}', $safeData)"
126
+ } else {
127
+ val quotedData = org.json.JSONObject.quote(data)
128
+ "window.WebBridge.callback('${event.eventName}', $quotedData)"
129
+ }
105
130
  } else {
106
131
  "window.WebBridge.callback('${event.eventName}', null)"
107
132
  }
108
-
133
+
109
134
  webView.evaluateJavascript(jsCode, null)
110
135
  Log.d(TAG, "✅ Web notification sent: ${event.eventName}")
111
136
  } catch (e: Exception) {
@@ -146,9 +171,21 @@ object BridgeUtils {
146
171
  * @param jsonData The JSON object to send
147
172
  */
148
173
  fun notifyWebJson(webView: WebView, event: WebEvents, jsonData: JSONObject) {
174
+ // Ensure WebView interactions happen on the main thread
175
+ if (Looper.myLooper() != Looper.getMainLooper()) {
176
+ webView.post { notifyWebJson(webView, event, jsonData) }
177
+ return
178
+ }
179
+
149
180
  try {
150
- val jsonString = jsonData.toString().replace("'", "\\'")
151
- notifyWeb(webView, event, jsonString)
181
+ // Inject JSON directly into the JS call. U+2028/U+2029 are valid JSON whitespace but
182
+ // are treated as line terminators by V8, causing a SyntaxError — escape them first.
183
+ val safeJson = jsonData.toString()
184
+ .replace("
", "\\u2028")
185
+ .replace("
", "\\u2029")
186
+ val jsCode = "window.WebBridge.callback('${event.eventName}', $safeJson)"
187
+ webView.evaluateJavascript(jsCode, null)
188
+ Log.d(TAG, "✅ Web JSON notification sent: ${event.eventName}")
152
189
  } catch (e: Exception) {
153
190
  Log.e(TAG, "❌ Failed to send JSON to web: ${e.message}")
154
191
  notifyWebError(webView, event, "Error processing data: ${e.message}")
@@ -12,7 +12,8 @@ import io.ktor.server.routing.*
12
12
  import kotlinx.coroutines.*
13
13
  import java.io.File
14
14
  import java.io.IOException
15
- import java.net.ServerSocket
15
+ import java.net.InetSocketAddress
16
+ import java.nio.channels.ServerSocketChannel
16
17
  import java.security.SecureRandom
17
18
  import java.util.*
18
19
  import java.util.concurrent.ConcurrentHashMap
@@ -279,7 +280,10 @@ object FrameworkServerUtils {
279
280
 
280
281
  private fun isPortAvailable(port: Int): Boolean {
281
282
  return try {
282
- ServerSocket(port).use { true }
283
+ ServerSocketChannel.open().use { channel ->
284
+ channel.bind(InetSocketAddress("127.0.0.1", port))
285
+ true
286
+ }
283
287
  } catch (e: IOException) {
284
288
  false
285
289
  }
@@ -408,4 +412,4 @@ object FrameworkServerUtils {
408
412
  }
409
413
  }
410
414
  }
411
- }
415
+ }
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <shape xmlns:android="http://schemas.android.com/apk/res/android"
3
+ android:shape="rectangle">
4
+ <stroke
5
+ android:width="3dp"
6
+ android:color="#FF0000" />
7
+ <solid android:color="#33FF0000" />
8
+ </shape>
@@ -13,6 +13,12 @@
13
13
  app:layout_constraintStart_toStartOf="parent"
14
14
  app:layout_constraintEnd_toEndOf="parent">
15
15
 
16
+ <androidx.camera.view.PreviewView
17
+ android:id="@+id/camera_preview"
18
+ android:layout_width="match_parent"
19
+ android:layout_height="match_parent"
20
+ android:visibility="invisible" />
21
+
16
22
  <WebView
17
23
  android:id="@+id/webview"
18
24
  android:layout_width="match_parent"
@@ -24,6 +30,37 @@
24
30
  android:layout_width="wrap_content"
25
31
  android:layout_height="wrap_content"
26
32
  android:visibility="gone" />
33
+
34
+ <RelativeLayout
35
+ android:id="@+id/debug_viewfinder_overlay"
36
+ android:layout_width="0dp"
37
+ android:layout_height="0dp"
38
+ android:background="@null"
39
+ android:visibility="gone">
40
+
41
+ <TextView
42
+ android:id="@+id/debug_qr_status"
43
+ android:layout_width="wrap_content"
44
+ android:layout_height="wrap_content"
45
+ android:layout_alignParentBottom="true"
46
+ android:layout_centerHorizontal="true"
47
+ android:layout_marginBottom="8dp"
48
+ android:paddingHorizontal="10dp"
49
+ android:paddingVertical="4dp"
50
+ android:background="#CC000000"
51
+ android:textColor="#FFFFFF"
52
+ android:textSize="12sp"
53
+ android:text="⬤ –" />
54
+
55
+ </RelativeLayout>
56
+
57
+ <!-- Debug: shows where native thinks the barcode box is in screen space -->
58
+ <View
59
+ android:id="@+id/debug_barcode_overlay"
60
+ android:layout_width="0dp"
61
+ android:layout_height="0dp"
62
+ android:background="#5500FF00"
63
+ android:visibility="gone" />
27
64
  </RelativeLayout>
28
65
 
29
66
  </androidx.constraintlayout.widget.ConstraintLayout>