@elurjs/android 0.0.0-stage → 0.2.0

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 (145) hide show
  1. package/README.md +10 -2
  2. package/index.mjs +11 -0
  3. package/package.json +29 -4
  4. package/template/.gitkeep +0 -0
  5. package/template/app/build.gradle.kts +192 -0
  6. package/template/app/proguard-rules-elur.pro +12 -0
  7. package/template/app/proguard-rules.pro +3 -0
  8. package/template/app/src/main/AndroidManifest.xml +81 -0
  9. package/template/app/src/main/assets/oss-notices.txt +153 -0
  10. package/template/app/src/main/assets/tck_pixel.png +0 -0
  11. package/template/app/src/main/cpp/CMakeLists.txt +117 -0
  12. package/template/app/src/main/cpp/dlEncoder.h +117 -0
  13. package/template/app/src/main/cpp/dlEncoderJsi.cpp +315 -0
  14. package/template/app/src/main/cpp/dlEncoderQjs.cpp +394 -0
  15. package/template/app/src/main/cpp/dlOps.inc +145 -0
  16. package/template/app/src/main/cpp/elurBridge.cpp +1350 -0
  17. package/template/app/src/main/cpp/elurBridgeHermes.cpp +1294 -0
  18. package/template/app/src/main/cpp/elurSkia.cpp +287 -0
  19. package/template/app/src/main/cpp/elurSkiaTree.cpp +448 -0
  20. package/template/app/src/main/cpp/elurUiWorklet.cpp +1233 -0
  21. package/template/app/src/main/cpp/elurYoga.cpp +1060 -0
  22. package/template/app/src/main/cpp/elurYoga.h +82 -0
  23. package/template/app/src/main/cpp/hermes-libs/LICENSE +21 -0
  24. package/template/app/src/main/cpp/hermes-libs/arm64-v8a/libhermesvm.so +0 -0
  25. package/template/app/src/main/cpp/hermes-libs/include/hermes/AsyncDebuggerAPI.h +276 -0
  26. package/template/app/src/main/cpp/hermes-libs/include/hermes/CompileJS.h +97 -0
  27. package/template/app/src/main/cpp/hermes-libs/include/hermes/DebuggerAPI.h +502 -0
  28. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/CrashManager.h +107 -0
  29. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/CtorConfig.h +145 -0
  30. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/DebuggerTypes.h +193 -0
  31. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/GCConfig.h +211 -0
  32. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/GCTripwireContext.h +40 -0
  33. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/HermesExport.h +14 -0
  34. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/JSOutOfMemoryError.h +27 -0
  35. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/RuntimeConfig.h +141 -0
  36. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/SamplingProfiler.h +270 -0
  37. package/template/app/src/main/cpp/hermes-libs/include/hermes/RuntimeTaskRunner.h +64 -0
  38. package/template/app/src/main/cpp/hermes-libs/include/hermes/SynthTrace.h +1566 -0
  39. package/template/app/src/main/cpp/hermes-libs/include/hermes/SynthTraceParser.h +37 -0
  40. package/template/app/src/main/cpp/hermes-libs/include/hermes/ThreadSafetyAnalysis.h +75 -0
  41. package/template/app/src/main/cpp/hermes-libs/include/hermes/TimerStats.h +23 -0
  42. package/template/app/src/main/cpp/hermes-libs/include/hermes/TraceInterpreter.h +334 -0
  43. package/template/app/src/main/cpp/hermes-libs/include/hermes/TracingRuntime.h +328 -0
  44. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPAgent.h +131 -0
  45. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPDebugAPI.h +73 -0
  46. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CallbackOStream.h +89 -0
  47. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/ConsoleMessage.h +135 -0
  48. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainAgent.h +280 -0
  49. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainCoordinator.h +137 -0
  50. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainAgent.h +107 -0
  51. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainState.h +140 -0
  52. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/HeapProfilerDomainAgent.h +71 -0
  53. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/JSONValueInterfaces.h +40 -0
  54. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageConverters.h +82 -0
  55. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageInterfaces.h +72 -0
  56. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypes.h +1279 -0
  57. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypesInlines.h +313 -0
  58. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/ProfilerDomainAgent.h +38 -0
  59. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectConverters.h +77 -0
  60. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectsTable.h +127 -0
  61. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RuntimeDomainAgent.h +138 -0
  62. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Dummy.h +24 -0
  63. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Extensions.h +20 -0
  64. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/ExtensionsBytecode.h +23 -0
  65. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Intrinsics.h +44 -0
  66. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/JSIUtils.h +123 -0
  67. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/TextEncoder.h +29 -0
  68. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribDummy.h +24 -0
  69. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribExtensions.h +23 -0
  70. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoder.h +30 -0
  71. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoderUtils.h +113 -0
  72. package/template/app/src/main/cpp/hermes-libs/include/hermes/hermes.h +242 -0
  73. package/template/app/src/main/cpp/hermes-libs/include/hermes/hermes_tracing.h +52 -0
  74. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIHelpers.h +295 -0
  75. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIRuntimeWrapper.h +25 -0
  76. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_abi.h +642 -0
  77. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_vtable.h +29 -0
  78. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/HermesSandboxRuntime.h +41 -0
  79. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_compiled.h +12 -0
  80. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled-impl.h +8516 -0
  81. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled.h +137 -0
  82. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled-impl.h +3945 -0
  83. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled.h +119 -0
  84. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-fb.h +124 -0
  85. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-impl.h +66 -0
  86. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt.h +456 -0
  87. package/template/app/src/main/cpp/hermes-libs/include/jsi/JSIDynamic.h +26 -0
  88. package/template/app/src/main/cpp/hermes-libs/include/jsi/decorator.h +1157 -0
  89. package/template/app/src/main/cpp/hermes-libs/include/jsi/hermes-interfaces.h +242 -0
  90. package/template/app/src/main/cpp/hermes-libs/include/jsi/instrumentation.h +132 -0
  91. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsi-inl.h +434 -0
  92. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsi.h +2266 -0
  93. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsilib.h +59 -0
  94. package/template/app/src/main/cpp/hermes-libs/include/jsi/threadsafe.h +79 -0
  95. package/template/app/src/main/cpp/hermes-libs/jsi-impl/jsi.cpp +1111 -0
  96. package/template/app/src/main/cpp/hermes-libs/x86_64/libhermesvm.so +0 -0
  97. package/template/app/src/main/java/com/elur/universal/BinaryCodec.kt +121 -0
  98. package/template/app/src/main/java/com/elur/universal/DlDecoder.kt +260 -0
  99. package/template/app/src/main/java/com/elur/universal/DlOpsDecode.kt +158 -0
  100. package/template/app/src/main/java/com/elur/universal/ElurBoxDrawable.kt +161 -0
  101. package/template/app/src/main/java/com/elur/universal/ElurBridge.kt +238 -0
  102. package/template/app/src/main/java/com/elur/universal/ElurBridgeHermes.kt +223 -0
  103. package/template/app/src/main/java/com/elur/universal/ElurCanvasView.kt +202 -0
  104. package/template/app/src/main/java/com/elur/universal/ElurCryptoModule.kt +206 -0
  105. package/template/app/src/main/java/com/elur/universal/ElurCustomLayout.kt +185 -0
  106. package/template/app/src/main/java/com/elur/universal/ElurEditText.kt +17 -0
  107. package/template/app/src/main/java/com/elur/universal/ElurFontRegistry.kt +190 -0
  108. package/template/app/src/main/java/com/elur/universal/ElurHttpModule.kt +306 -0
  109. package/template/app/src/main/java/com/elur/universal/ElurImageService.kt +348 -0
  110. package/template/app/src/main/java/com/elur/universal/ElurLicensesActivity.kt +84 -0
  111. package/template/app/src/main/java/com/elur/universal/ElurListView.kt +954 -0
  112. package/template/app/src/main/java/com/elur/universal/ElurManifest.kt +117 -0
  113. package/template/app/src/main/java/com/elur/universal/ElurMetrics.kt +325 -0
  114. package/template/app/src/main/java/com/elur/universal/ElurModuleRegistrar.kt +14 -0
  115. package/template/app/src/main/java/com/elur/universal/ElurPermissionGate.kt +36 -0
  116. package/template/app/src/main/java/com/elur/universal/ElurRenderer.kt +6164 -0
  117. package/template/app/src/main/java/com/elur/universal/ElurRowYoga.kt +130 -0
  118. package/template/app/src/main/java/com/elur/universal/ElurScrollView.kt +240 -0
  119. package/template/app/src/main/java/com/elur/universal/ElurShellView.kt +117 -0
  120. package/template/app/src/main/java/com/elur/universal/ElurSkiaCanvasView.kt +162 -0
  121. package/template/app/src/main/java/com/elur/universal/ElurSkiaTreeRenderer.kt +968 -0
  122. package/template/app/src/main/java/com/elur/universal/ElurStateModule.kt +69 -0
  123. package/template/app/src/main/java/com/elur/universal/ElurSwipeDriver.kt +34 -0
  124. package/template/app/src/main/java/com/elur/universal/ElurTckModule.kt +99 -0
  125. package/template/app/src/main/java/com/elur/universal/ElurTextMeasure.kt +16 -0
  126. package/template/app/src/main/java/com/elur/universal/ElurTrace.kt +24 -0
  127. package/template/app/src/main/java/com/elur/universal/ElurUiModule.kt +48 -0
  128. package/template/app/src/main/java/com/elur/universal/ElurUiWorklet.kt +305 -0
  129. package/template/app/src/main/java/com/elur/universal/JsBridge.kt +67 -0
  130. package/template/app/src/main/java/com/elur/universal/JsThread.kt +189 -0
  131. package/template/app/src/main/java/com/elur/universal/MainActivity.kt +844 -0
  132. package/template/app/src/main/java/com/elur/universal/ModuleRegistry.kt +701 -0
  133. package/template/app/src/main/java/com/elur/universal/YogaRowScope.kt +97 -0
  134. package/template/app/src/main/res/values/ids.xml +10 -0
  135. package/template/app/src/main/res/values/strings.xml +8 -0
  136. package/template/app/src/main/res/values-es/strings.xml +5 -0
  137. package/template/app/src/main/res/xml/network_security_config.xml +10 -0
  138. package/template/build.gradle.kts +5 -0
  139. package/template/gradle/libs.versions.toml +12 -0
  140. package/template/gradle/wrapper/gradle-wrapper.jar +0 -0
  141. package/template/gradle/wrapper/gradle-wrapper.properties +8 -0
  142. package/template/gradle.properties +23 -0
  143. package/template/gradlew +251 -0
  144. package/template/gradlew.bat +94 -0
  145. package/template/settings.gradle.kts +32 -0
@@ -0,0 +1,117 @@
1
+ package com.elur.universal
2
+
3
+ import java.security.MessageDigest
4
+ import org.json.JSONObject
5
+
6
+ /**
7
+ * U13 — verificación del manifiesto de assets antes de `ready`.
8
+ *
9
+ * `elur build --target android` emite `elur-manifest.json` con las versiones del contrato vigente
10
+ * (ir/dlAbi/nav/hbc), un `build` fingerprint (sha256 del conjunto) y sha256+bytes de cada asset
11
+ * `elur*.{js,hbc}`. En release el host no inicia sin manifiesto verificado: un asset corrupto/stale
12
+ * no llega a evaluarse.
13
+ *
14
+ * Objeto puro — `readFile` abstrae el origen (assets en prod, mapa en tests JVM).
15
+ */
16
+ object ElurManifest {
17
+
18
+ class ManifestException(msg: String) : Exception(msg)
19
+
20
+ /**
21
+ * ADR-0083 — engine declarado en el manifiesto o null (debug sin `--engine`). Es el motor que
22
+ * release ejecuta; los extras del intent no existen fuera de debug.
23
+ */
24
+ fun engineOf(manifestJson: String): String? {
25
+ val e =
26
+ try {
27
+ JSONObject(manifestJson).optString("engine", "")
28
+ } catch (x: Exception) {
29
+ ""
30
+ }
31
+ return e.takeIf { it == "quickjs" || it == "hermes" }
32
+ }
33
+
34
+ /**
35
+ * ADR-0194 — superficie declarada en el manifiesto: "native" (default) = Platform Views;
36
+ * "custom" = renderer Skia del árbol (opt-in, cae a views si la cap no está); "auto" = el
37
+ * framework decide (hoy ≡ native). Mismo nivel declarativo que `engine` — en release fija el
38
+ * carril, los extras no existen.
39
+ */
40
+ fun surfaceOf(manifestJson: String): String? {
41
+ val s =
42
+ try {
43
+ JSONObject(manifestJson).optString("surface", "")
44
+ } catch (x: Exception) {
45
+ ""
46
+ }
47
+ return s.takeIf { it == "native" || it == "custom" || it == "auto" }
48
+ }
49
+
50
+ /**
51
+ * Devuelve el fingerprint `build` (8 chars) si todo verifica. `requireEngine` (release): el
52
+ * manifiesto debe declarar `engine` — "quickjs"/"hermes" — y con hermes los .hbc del par deben
53
+ * estar declarados (bytecode declarado, no presente = build incompleto).
54
+ */
55
+ fun verify(
56
+ manifestJson: String,
57
+ expectedDlAbi: Int,
58
+ assetNames: List<String>,
59
+ requireEngine: Boolean = false,
60
+ readFile: (String) -> ByteArray?
61
+ ): String {
62
+ val m =
63
+ try {
64
+ JSONObject(manifestJson)
65
+ } catch (e: Exception) {
66
+ throw ManifestException("manifiesto ilegible: ${e.message}")
67
+ }
68
+ val dlAbi = m.optInt("dlAbi", -1)
69
+ if (dlAbi != expectedDlAbi) {
70
+ throw ManifestException(
71
+ "dlAbi del manifiesto ($dlAbi) != decoder del host ($expectedDlAbi)"
72
+ )
73
+ }
74
+ if (requireEngine) {
75
+ val eng =
76
+ engineOf(manifestJson)
77
+ ?: throw ManifestException("manifiesto sin engine declarado")
78
+ if (eng == "hermes") {
79
+ val fs = m.optJSONObject("files")
80
+ for (b in listOf("elurSignals.hbc", "elurApp.hbc")) {
81
+ if (fs?.optJSONObject(b) == null) {
82
+ throw ManifestException("engine=hermes pero '$b' no declarado")
83
+ }
84
+ }
85
+ }
86
+ }
87
+ val files = m.optJSONObject("files") ?: throw ManifestException("manifiesto sin 'files'")
88
+ for (name in assetNames) {
89
+ val entry =
90
+ files.optJSONObject(name)
91
+ ?: throw ManifestException(
92
+ "asset '$name' no declarado en el manifiesto"
93
+ )
94
+ val bytes =
95
+ readFile(name)
96
+ ?: throw ManifestException("asset '$name' declarado pero no legible")
97
+ val sha = sha256Hex(bytes)
98
+ val declared = entry.optString("sha256")
99
+ if (sha != declared) {
100
+ throw ManifestException(
101
+ "sha256 de '$name' no coincide (declarado ${declared.take(12)}…, real ${sha.take(12)}…)"
102
+ )
103
+ }
104
+ if (entry.optLong("bytes", -1) != bytes.size.toLong()) {
105
+ throw ManifestException("bytes de '$name' no coinciden con el manifiesto")
106
+ }
107
+ }
108
+ val build = m.optString("build")
109
+ if (build.isEmpty()) throw ManifestException("manifiesto sin fingerprint 'build'")
110
+ return build.take(8)
111
+ }
112
+
113
+ fun sha256Hex(bytes: ByteArray): String {
114
+ val d = MessageDigest.getInstance("SHA-256").digest(bytes)
115
+ return d.joinToString("") { "%02x".format(it) }
116
+ }
117
+ }
@@ -0,0 +1,325 @@
1
+ package com.elur.universal
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+
6
+ /**
7
+ * ADR-0084 / R4.1 — métricas acotadas del lado host.
8
+ *
9
+ * Tres piezas:
10
+ * - ring de los últimos [COMMIT_RING] commits aplicados en main
11
+ * ```
12
+ * (commitId=frame, ops, bytes, ms decode+apply, ms de espera en la
13
+ * cola JS→main, hojas re-medidas);
14
+ * ```
15
+ * - contadores de sesión (Yoga: llamadas de medida, hits de cache,
16
+ * ```
17
+ * timeouts, remeasures; stale commits por surfaceEpoch; profundidad
18
+ * de la cola UI→JS leída de [JsThread]);
19
+ * ```
20
+ * - `dump()` → JSON con provenance (generación de sesión, engine
21
+ * ```
22
+ * declarado, fingerprint del manifiesto) + heaps (PSS por bucket:
23
+ * java/native/graphics + total).
24
+ * ```
25
+ * Nada se loggea por frame: el push cadenciado sale cada [REPORT_EVERY] commits por `onReport`
26
+ * (MainActivity lo cablea a logcat; null = mudo) y el dump completo en frontera de lifecycle
27
+ * (onPause). La contraparte JS es `metrics()` del EmbeddedHost, que empuja `[metrics-js]` por
28
+ * console.log al mismo logcat — juntas separan JS activo / espera en colas / decode+apply / ack.
29
+ *
30
+ * `beginSession` la invoca JsThread.beginSession: los contadores son POR SESIÓN — un restart de
31
+ * engine reinicia la muestra y el dump lleva la generación para correlacionar con `[metrics-js]`.
32
+ */
33
+ object ElurMetrics {
34
+
35
+ const val COMMIT_RING = 128
36
+ const val REPORT_EVERY = 600
37
+ private const val LOGCAT_MAX = 3600
38
+ private const val ERROR_RING = 32
39
+
40
+ /**
41
+ * ADR-0191 — evento de error de producción, acotado y sin PII: `kind` del vocabulario cerrado
42
+ * (session-overflow, session-close, unhandled-rejection, js-stall, prev-exit, engine-init),
43
+ * `detail` JSON con contadores/ids solamente (nunca payloads de app).
44
+ */
45
+ class ErrorRec(val t: Long, val kind: String, val detail: String) {
46
+ fun toJson(): JSONObject = JSONObject().put("t", t).put("kind", kind).put("detail", detail)
47
+ }
48
+
49
+ private val errors = ArrayDeque<ErrorRec>()
50
+
51
+ /**
52
+ * Un commit aplicado en el hilo main. `applyEndMs` es uptime (mismo reloj que
53
+ * FrameTimeline/framestats) — el ancla que permite correlacionar commit→present con una traza
54
+ * Perfetto sin marker por frame (R7.7).
55
+ */
56
+ class CommitRec(
57
+ val frame: Long,
58
+ val ops: Int,
59
+ val bytes: Int,
60
+ val decodeApplyMs: Double,
61
+ val queueWaitMs: Double,
62
+ val remeasured: Int,
63
+ val applyEndMs: Long,
64
+ ) {
65
+ fun toJson(): JSONObject =
66
+ JSONObject()
67
+ .put("f", frame)
68
+ .put("ops", ops)
69
+ .put("b", bytes)
70
+ .put("apply", decodeApplyMs)
71
+ .put("qw", queueWaitMs)
72
+ .put("rm", remeasured)
73
+ .put("at", applyEndMs)
74
+ }
75
+
76
+ private val commits = ArrayDeque<CommitRec>()
77
+
78
+ var sessionGen = 0
79
+ private set
80
+ var commitsApplied = 0L
81
+ private set
82
+ var opsApplied = 0L
83
+ private set
84
+ var bytesApplied = 0L
85
+ private set
86
+ var decodeApplyMsTotal = 0.0
87
+ private set
88
+ var queueWaitMsTotal = 0.0
89
+ private set
90
+ var yogaMeasureCalls = 0L
91
+ private set
92
+ var yogaMeasureCacheHits = 0L
93
+ private set
94
+ var yogaMeasureTimeouts = 0L
95
+
96
+ /** Medidas de texto resueltas en el hilo JS (PrecomputedText) sin latch a main. */
97
+ var yogaMeasureOffUi = 0L
98
+ private set
99
+ /** Tandas de requestLeafRemeasure (dirty leaves post-apply + config change). */
100
+ var remeasureRequests = 0L
101
+ private set
102
+ /** Hojas efectivamente re-medidas post-apply. */
103
+ var remeasuredLeaves = 0L
104
+ private set
105
+ /** Commits descartados por surfaceEpoch (posteados antes de destroy). */
106
+ var staleCommits = 0L
107
+ private set
108
+
109
+ /** Errores reportados en la sesión (ring en `errors`; total aquí). */
110
+ var errorsTotal = 0L
111
+ private set
112
+
113
+ /** Provenance del build/medición — lo fija MainActivity al boot. */
114
+ @JvmField var engine: String = ""
115
+ @JvmField var buildFp: String = ""
116
+
117
+ // ADR-0112: nodos vivos del árbol Yoga nativo (g_nodes). La lectura
118
+ // es JsThread-confined — el renderer cablea `yogaCountSampler` que
119
+ // postea la lectura y aterriza aquí por callback en main; el valor
120
+ // del dump puede ir un reporte por detrás (nunca una lectura con
121
+ // data race). -1 = engine sin soporte / aún sin muestra.
122
+ @Volatile var yogaNodeCount = -1
123
+ @JvmField var yogaCountSampler: (() -> Unit)? = null
124
+
125
+ // ADR-0112: bytes del heap JS (JS_ComputeMemoryUsage / instrumentation
126
+ // .getHeapInfo) — misma disciplina JsThread-confined que yogaNodeCount.
127
+ // -1 = engine sin soporte / aún sin muestra.
128
+ @Volatile var jsHeapBytes = -1L
129
+ @JvmField var jsHeapSampler: (() -> Unit)? = null
130
+
131
+ /** Sink del resumen cadenciado — MainActivity lo cablea a Log.i. */
132
+ @JvmField var onReport: ((String) -> Unit)? = null
133
+
134
+ /** Frontera de sesión: todo contador/ring reinicia con la generación. */
135
+ @Synchronized
136
+ fun beginSession(gen: Int) {
137
+ sessionGen = gen
138
+ commits.clear()
139
+ commitsApplied = 0
140
+ opsApplied = 0
141
+ bytesApplied = 0
142
+ decodeApplyMsTotal = 0.0
143
+ queueWaitMsTotal = 0.0
144
+ yogaMeasureCalls = 0
145
+ yogaMeasureCacheHits = 0
146
+ yogaMeasureTimeouts = 0
147
+ remeasureRequests = 0
148
+ remeasuredLeaves = 0
149
+ staleCommits = 0
150
+ errors.clear()
151
+ errorsTotal = 0
152
+ }
153
+
154
+ /**
155
+ * Un commit aplicado (path binario o drain JSON). `queueWaitMs` es post→inicio-de-apply en main
156
+ * (cola JS→UI); `decodeApplyMs` es el trabajo de main (decode + ops sobre Views). Ambos se
157
+ * acumulan Y entran al ring — el agregado es de sesión, el ring conserva el tramo reciente.
158
+ */
159
+ @Synchronized
160
+ fun recordCommit(
161
+ frame: Long,
162
+ ops: Int,
163
+ bytes: Int,
164
+ decodeApplyMs: Double,
165
+ queueWaitMs: Double,
166
+ remeasured: Int,
167
+ applyEndMs: Long = android.os.SystemClock.uptimeMillis()
168
+ ) {
169
+ commits.addLast(
170
+ CommitRec(frame, ops, bytes, decodeApplyMs, queueWaitMs, remeasured, applyEndMs)
171
+ )
172
+ while (commits.size > COMMIT_RING) commits.removeFirst()
173
+ commitsApplied++
174
+ opsApplied += ops
175
+ bytesApplied += bytes
176
+ decodeApplyMsTotal += decodeApplyMs
177
+ queueWaitMsTotal += queueWaitMs
178
+ if (commitsApplied == 1L || commitsApplied % REPORT_EVERY == 0L) {
179
+ yogaCountSampler?.invoke() // muestrea async — aterriza en el próximo reporte
180
+ jsHeapSampler?.invoke()
181
+ onReport?.invoke(summaryLine())
182
+ }
183
+ }
184
+
185
+ @Synchronized
186
+ fun recordMeasureCall() {
187
+ yogaMeasureCalls++
188
+ }
189
+
190
+ @Synchronized
191
+ fun recordMeasureHit() {
192
+ yogaMeasureCacheHits++
193
+ }
194
+
195
+ @Synchronized
196
+ fun recordMeasureTimeout() {
197
+ yogaMeasureTimeouts++
198
+ }
199
+
200
+ @Synchronized
201
+ fun recordMeasureOffUi() {
202
+ yogaMeasureOffUi++
203
+ }
204
+
205
+ @Synchronized
206
+ fun recordRemeasure(leaves: Int) {
207
+ remeasureRequests++
208
+ remeasuredLeaves += leaves
209
+ }
210
+
211
+ @Synchronized
212
+ fun recordStale() {
213
+ staleCommits++
214
+ }
215
+
216
+ /**
217
+ * ADR-0191 — error de producción estructurado. Llamadores: bridge JNI
218
+ * (ElurRenderer.reportError), watchdog de JsThread (js-stall), ApplicationExitInfo del proceso
219
+ * previo (prev-exit), fallo de init del engine (engine-init). Ring acotado — un burst de
220
+ * rechazos no desplaza el resto del estado.
221
+ */
222
+ @Synchronized
223
+ fun recordError(kind: String, detail: String) {
224
+ errors.addLast(ErrorRec(System.currentTimeMillis(), kind, detail))
225
+ while (errors.size > ERROR_RING) errors.removeFirst()
226
+ errorsTotal++
227
+ onReport?.invoke("[metrics-host] error kind=$kind $detail")
228
+ }
229
+
230
+ /** Resumen de una línea para el push cadenciado (sin heaps — eso va en dump). */
231
+ @Synchronized
232
+ fun summaryLine(): String =
233
+ "[metrics-host] gen=$sessionGen commits=$commitsApplied ops=$opsApplied " +
234
+ "apply=${r1(decodeApplyMsTotal)}ms qw=${r1(queueWaitMsTotal)}ms " +
235
+ "yoga=$yogaMeasureCalls/hit=$yogaMeasureCacheHits/to=$yogaMeasureTimeouts" +
236
+ "/offui=$yogaMeasureOffUi " +
237
+ "/nodes=$yogaNodeCount " +
238
+ "stale=$staleCommits jsq=${JsThread.queueDepth}/${JsThread.queueDepthMax}"
239
+
240
+ /**
241
+ * Snapshot completo exportable — JSON en una línea. Con ~128 recs supera el límite del logger
242
+ * (~4KB/entrada); para logcat usar [dumpLogLines], que lo parte en chunks etiquetados.
243
+ */
244
+ @Synchronized
245
+ fun dump(): String {
246
+ val recent = JSONArray()
247
+ for (c in commits) recent.put(c.toJson())
248
+ val errs = JSONArray()
249
+ for (e in errors) errs.put(e.toJson())
250
+ return JSONObject()
251
+ .put("gen", sessionGen)
252
+ .put("engine", engine)
253
+ .put("fp", buildFp)
254
+ .put(
255
+ "commits",
256
+ JSONObject()
257
+ .put("n", commitsApplied)
258
+ .put("ops", opsApplied)
259
+ .put("bytes", bytesApplied)
260
+ .put("applyMs", r2(decodeApplyMsTotal))
261
+ .put("queueWaitMs", r2(queueWaitMsTotal))
262
+ )
263
+ .put(
264
+ "yoga",
265
+ JSONObject()
266
+ .put("calls", yogaMeasureCalls)
267
+ .put("cacheHits", yogaMeasureCacheHits)
268
+ .put("timeouts", yogaMeasureTimeouts)
269
+ .put("offUi", yogaMeasureOffUi)
270
+ .put("remeasureReqs", remeasureRequests)
271
+ .put("remeasuredLeaves", remeasuredLeaves)
272
+ .put("nodes", yogaNodeCount)
273
+ )
274
+ .put("staleCommits", staleCommits)
275
+ .put(
276
+ "jsQueue",
277
+ JSONObject()
278
+ .put("depth", JsThread.queueDepth)
279
+ .put("maxDepth", JsThread.queueDepthMax)
280
+ )
281
+ .put("mem", memJson())
282
+ .put("errors", JSONObject().put("n", errorsTotal).put("recent", errs))
283
+ .put("recentCommits", recent)
284
+ .toString()
285
+ }
286
+
287
+ /**
288
+ * `dump()` partido para el logger: cada línea es `"[metrics-host] k/n <chunk>"` (k desde 1).
289
+ * Reensamblar concatenando los chunks en orden. LOGCAT_MAX guarda margen bajo el límite de
290
+ * ~4076B por entrada del kernel logger.
291
+ */
292
+ fun dumpLogLines(): List<String> {
293
+ val body = dump()
294
+ val n = (body.length + LOGCAT_MAX - 1) / LOGCAT_MAX
295
+ return (0 until n).map { i ->
296
+ "[metrics-host] ${i + 1}/$n " +
297
+ body.substring(i * LOGCAT_MAX, minOf((i + 1) * LOGCAT_MAX, body.length))
298
+ }
299
+ }
300
+
301
+ private fun memJson(): JSONObject {
302
+ val mi = android.os.Debug.MemoryInfo()
303
+ android.os.Debug.getMemoryInfo(mi)
304
+ fun stat(name: String) = mi.getMemoryStat(name)?.toIntOrNull() ?: 0
305
+ // Algunos vendors (MIUI) no rellenan los buckets summary.* —
306
+ // fallback a las APIs directas para no exportar ceros falsos.
307
+ val javaKb =
308
+ stat("summary.javaHeap").takeIf { it > 0 }
309
+ ?: ((Runtime.getRuntime().totalMemory() -
310
+ Runtime.getRuntime().freeMemory()) / 1024)
311
+ .toInt()
312
+ val nativeKb =
313
+ stat("summary.nativeHeap").takeIf { it > 0 }
314
+ ?: (android.os.Debug.getNativeHeapAllocatedSize() / 1024).toInt()
315
+ return JSONObject()
316
+ .put("javaKb", javaKb)
317
+ .put("nativeKb", nativeKb)
318
+ .put("graphicsKb", stat("summary.graphics"))
319
+ .put("jsBytes", jsHeapBytes)
320
+ .put("pssKb", mi.totalPss)
321
+ }
322
+
323
+ private fun r1(v: Double) = Math.round(v * 10.0) / 10.0
324
+ private fun r2(v: Double) = Math.round(v * 100.0) / 100.0
325
+ }
@@ -0,0 +1,14 @@
1
+ // Generated by cli/gen-host-integration.mjs — do not edit.
2
+ package com.elur.universal
3
+
4
+ import android.app.Activity
5
+
6
+ /** Registrant de módulos de paquetes (ADR-0103): una entrada por
7
+ * bindings.android.class de los elur.plugin.json del grafo. */
8
+ object ElurModuleRegistrar {
9
+ fun registerAll(renderer: ElurHostRenderer, activity: Activity) {
10
+ renderer.registerModule(com.elurjs.i18n.ElurI18nModule(activity))
11
+ renderer.registerModule(com.elurjs.kv.ElurKvModule(activity))
12
+ renderer.registerModule(com.elurjs.location.ElurLocationModule(activity))
13
+ }
14
+ }
@@ -0,0 +1,36 @@
1
+ package com.elur.universal
2
+
3
+ import android.app.Activity
4
+ import android.content.pm.PackageManager
5
+
6
+ /**
7
+ * Gate de permisos runtime (ADR-0076 §8, error `permission_denied`):
8
+ * un módulo con PermissionDecl `required` pide vía ensure() — la
9
+ * Activity del host enruta onRequestPermissionsResult a dispatch()
10
+ * y la continuación del comando corre donde el diálogo lo dejó.
11
+ * Sin androidx: APIs de framework (API 23+).
12
+ * Un pending por requestCode; códigos del bloque 7000+ no colisionan
13
+ * con usos propios del host.
14
+ */
15
+ object ElurPermissionGate {
16
+ private val pending = HashMap<Int, (Boolean) -> Unit>()
17
+ private var seq = 0
18
+
19
+ /** Ejecuta `cont` ahora si ya está concedido; si no, pide y continúa al resultado. */
20
+ fun ensure(activity: Activity, permission: String, cont: (Boolean) -> Unit) {
21
+ if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
22
+ cont(true)
23
+ return
24
+ }
25
+ val code = 7000 + (++seq)
26
+ pending[code] = cont
27
+ activity.requestPermissions(arrayOf(permission), code)
28
+ }
29
+
30
+ /** La Activity lo invoca desde onRequestPermissionsResult; true = era nuestro. */
31
+ fun dispatch(requestCode: Int, grantResults: IntArray): Boolean {
32
+ val cont = pending.remove(requestCode) ?: return false
33
+ cont(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
34
+ return true
35
+ }
36
+ }