@elurjs/universal 0.0.0-stage → 0.1.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 (758) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +24 -0
  3. package/README.md +102 -2
  4. package/THIRD_PARTY_NOTICES.md +153 -0
  5. package/cli/.gitkeep +0 -0
  6. package/cli/build-spec.mjs +46 -0
  7. package/cli/build-ssg.mjs +145 -0
  8. package/cli/build-ssr.mjs +276 -0
  9. package/cli/check-divergences.mjs +135 -0
  10. package/cli/check-doc-sync.mjs +282 -0
  11. package/cli/commands.d.mts +8 -0
  12. package/cli/commands.mjs +124 -0
  13. package/cli/commit-present.py +157 -0
  14. package/cli/create-app.mjs +768 -0
  15. package/cli/debug.mjs +45 -0
  16. package/cli/dev.mjs +488 -0
  17. package/cli/doctor.mjs +197 -0
  18. package/cli/elur.mjs +394 -0
  19. package/cli/font-license.mjs +24 -0
  20. package/cli/gen-bundle.mjs +195 -0
  21. package/cli/gen-doc-data.mjs +274 -0
  22. package/cli/gen-es5.mjs +60 -0
  23. package/cli/gen-hbc.mjs +87 -0
  24. package/cli/gen-host-integration.mjs +386 -0
  25. package/cli/gen-i18n-corpus.mjs +47 -0
  26. package/cli/gen-manifest.mjs +95 -0
  27. package/cli/gen-qjsc.mjs +77 -0
  28. package/cli/gen-route-types.mjs +65 -0
  29. package/cli/gen-routes.mjs +129 -0
  30. package/cli/gen-signals.mjs +151 -0
  31. package/cli/gen-ssr-client.mjs +119 -0
  32. package/cli/gen-wire-codec.mjs +214 -0
  33. package/cli/gen-wire-corpus.mjs +318 -0
  34. package/cli/gen-worklet-src.mjs +200 -0
  35. package/cli/gen-zones.mjs +197 -0
  36. package/cli/hermes-pair.mjs +61 -0
  37. package/cli/inspect.mjs +55 -0
  38. package/cli/layout-oracle-web.mjs +213 -0
  39. package/cli/layout-oracle.mjs +80 -0
  40. package/cli/lib-vlq.mjs +84 -0
  41. package/cli/measure-engines.mjs +206 -0
  42. package/cli/measure-shared.mjs +143 -0
  43. package/cli/package-linux.mjs +440 -0
  44. package/cli/parity-align.mjs +66 -0
  45. package/cli/platform-plugin.ts +97 -0
  46. package/cli/plugin-manifest.mjs +573 -0
  47. package/cli/run-bench.mjs +291 -0
  48. package/cli/run-commit-present.sh +91 -0
  49. package/cli/run-device-ab-surface.sh +94 -0
  50. package/cli/run-device-ab.sh +107 -0
  51. package/cli/run-energy.sh +44 -0
  52. package/cli/run-parity.mjs +164 -0
  53. package/cli/run-semantics.mjs +111 -0
  54. package/cli/run-tck.mjs +243 -0
  55. package/cli/sdui.mjs +1211 -0
  56. package/cli/symbolicate.mjs +90 -0
  57. package/cli/tck-android.sh +21 -0
  58. package/cli/tck-events-android.mjs +101 -0
  59. package/cli/tck-linux-atspi.py +389 -0
  60. package/cli/tck-platform-linux.mjs +638 -0
  61. package/cli/tck-platform.mjs +510 -0
  62. package/cli/visual-parity.mjs +691 -0
  63. package/docs/AUDITORIA-STATE-OF-THE-ART-2026-11.md +981 -0
  64. package/docs/ESTADO.md +679 -0
  65. package/docs/IMPLEMENTACION-NATIVA-v5.md +507 -0
  66. package/docs/PENDIENTES.md +1306 -0
  67. package/docs/adr/0013-transiciones-navegacion.md +169 -0
  68. package/docs/adr/0014-list-renderitem-factory.md +41 -0
  69. package/docs/adr/0015-dl-header-versionado.md +57 -0
  70. package/docs/adr/0016-hermes-v1-runtime.md +78 -0
  71. package/docs/adr/0017-encoder-nativo-dl.md +62 -0
  72. package/docs/adr/0018-yoga-tree-nativo.md +78 -0
  73. package/docs/adr/0019-ssr-universal-hidratacion.md +245 -0
  74. package/docs/adr/0020-canvas-draw-list.md +65 -0
  75. package/docs/adr/0021-text-input-props.md +55 -0
  76. package/docs/adr/0022-deep-links.md +49 -0
  77. package/docs/adr/0023-animacion-declarativa.md +130 -0
  78. package/docs/adr/0024-estilos-reactivos-vocabulario.md +100 -0
  79. package/docs/adr/0025-worklets-contrato-runner.md +181 -0
  80. package/docs/adr/0026-threading-js-dedicado.md +94 -0
  81. package/docs/adr/0027-ui-array-children-y-scope-por-fila.md +58 -0
  82. package/docs/adr/0028-commit-por-frame-en-host-embebido.md +93 -0
  83. package/docs/adr/0029-render-commit-latest-wins-screenhost.md +62 -0
  84. package/docs/adr/0030-destruccion-recursiva-ids-monotonicos.md +79 -0
  85. package/docs/adr/0031-scopes-formales-pool-filas.md +76 -0
  86. package/docs/adr/0032-nav-commit-autoritativo.md +64 -0
  87. package/docs/adr/0033-lista-virtual-ventana.md +80 -0
  88. package/docs/adr/0034-attach-event-class-strict-styles.md +89 -0
  89. package/docs/adr/0035-pipeline-imagenes-acotado.md +133 -0
  90. package/docs/adr/0036-data-por-entry-spa.md +91 -0
  91. package/docs/adr/0037-ir-serializable-factories-por-id.md +73 -0
  92. package/docs/adr/0038-transform-keys-compositor.md +79 -0
  93. package/docs/adr/0039-destroy-postorder-scope-ownership.md +86 -0
  94. package/docs/adr/0040-outbound-barriers-overflow-ack.md +60 -0
  95. package/docs/adr/0041-diff-treap-ir-version-strict.md +65 -0
  96. package/docs/adr/0042-data-endpoint-seguridad-hasloader.md +67 -0
  97. package/docs/adr/0043-aplicador-dom-unico.md +70 -0
  98. package/docs/adr/0044-descriptor-runtime-explicito.md +80 -0
  99. package/docs/adr/0045-navstate-versionado-scroll-settle.md +72 -0
  100. package/docs/adr/0046-harness-build-fail-closed.md +99 -0
  101. package/docs/adr/0047-envelope-evento-normalizado.md +110 -0
  102. package/docs/adr/0048-sesion-embebida-estados.md +91 -0
  103. package/docs/adr/0049-strict-styles-valores-portables.md +78 -0
  104. package/docs/adr/0050-update-style-tipado-abi-v5.md +66 -0
  105. package/docs/adr/0051-plugin-sdk-comandos.md +65 -0
  106. package/docs/adr/0052-benchmarks-reproducibles.md +50 -0
  107. package/docs/adr/0053-fling-target-pool-estructural.md +105 -0
  108. package/docs/adr/0054-lista-nativa-render-policy.md +130 -0
  109. package/docs/adr/0055-cesm-core.md +143 -0
  110. package/docs/adr/0056-dos-ejes-superficie-vs-propietario-de-ventana.md +112 -0
  111. package/docs/adr/0057-reset-node-y-firma-de-reciclaje.md +95 -0
  112. package/docs/adr/0058-rollback-de-montaje.md +83 -0
  113. package/docs/adr/0059-traza-on-device-u01-y-scroll-unico-productor.md +89 -0
  114. package/docs/adr/0060-list-update-patch-por-campo.md +73 -0
  115. package/docs/adr/0061-elegibilidad-de-plantilla-nativa.md +70 -0
  116. package/docs/adr/0062-invalidacion-adapter-lista-nativa.md +77 -0
  117. package/docs/adr/0063-autoridad-eventos-y-scroll.md +66 -0
  118. package/docs/adr/0064-admision-unica-de-commits.md +66 -0
  119. package/docs/adr/0065-runtime-de-sesion-u11.md +97 -0
  120. package/docs/adr/0066-perfil-layout-y-safe-area.md +78 -0
  121. package/docs/adr/0067-sesion-robusta-y-procedencia-de-build.md +121 -0
  122. package/docs/adr/0068-metodologia-de-benchmark-y-carril-verificable.md +94 -0
  123. package/docs/adr/0069-schema-de-wire-y-corpus-comun-de-codecs.md +126 -0
  124. package/docs/adr/0070-modelo-publico-de-aplicacion-y-mount.md +91 -0
  125. package/docs/adr/0071-image-service-y-tck-de-plataforma.md +133 -0
  126. package/docs/adr/0072-par-compilador-runtime-hermes.md +62 -0
  127. package/docs/adr/0073-corpus-de-semantica-y-lowering-por-motor.md +67 -0
  128. package/docs/adr/0074-perfil-i18n-formateo-dom-free.md +85 -0
  129. package/docs/adr/0075-back-predictivo-restore-y-layout-adaptativo.md +126 -0
  130. package/docs/adr/0076-contrato-de-modulos-capa-1.md +159 -0
  131. package/docs/adr/0077-manifest-de-plugin-y-plugin-sync.md +109 -0
  132. package/docs/adr/0078-extraccion-de-i18n-a-paquete-propio.md +114 -0
  133. package/docs/adr/0079-handles-de-host-objects-por-epoch.md +96 -0
  134. package/docs/adr/0080-platform-views-por-contrato.md +93 -0
  135. package/docs/adr/0081-codegen-del-dsl-de-modulos.md +118 -0
  136. package/docs/adr/0082-variante-web-de-modulos-nativos.md +126 -0
  137. package/docs/adr/0083-perfiles-dev-release.md +92 -0
  138. package/docs/adr/0084-instrumentacion-acotada-exportable.md +126 -0
  139. package/docs/adr/0085-medicion-agrupada-en-main.md +125 -0
  140. package/docs/adr/0086-matriz-capacidades-props-eventos.md +75 -0
  141. package/docs/adr/0087-uithread-runner-android.md +271 -0
  142. package/docs/adr/0088-worklet-src-estatico.md +82 -0
  143. package/docs/adr/0089-composicion-animaciones-settle-drag.md +122 -0
  144. package/docs/adr/0090-linter-capturas-build.md +94 -0
  145. package/docs/adr/0091-router-core-vs-universal.md +74 -0
  146. package/docs/adr/0092-sharedregion-type-strings.md +59 -0
  147. package/docs/adr/0093-permission-request-estandar.md +52 -0
  148. package/docs/adr/0094-dispatch-worker-timeoutms.md +51 -0
  149. package/docs/adr/0095-tck-modulos.md +65 -0
  150. package/docs/adr/0096-cesm-ring-deferral.md +47 -0
  151. package/docs/adr/0097-tooling-diferido.md +51 -0
  152. package/docs/adr/0098-handshake-moduleabi.md +46 -0
  153. package/docs/adr/0099-modulos-ambient.md +58 -0
  154. package/docs/adr/0100-auto-declaracion-modulos.md +43 -0
  155. package/docs/adr/0101-plataforma-build.md +49 -0
  156. package/docs/adr/0102-permisos-manifest-build.md +38 -0
  157. package/docs/adr/0103-registrant-ownership.md +45 -0
  158. package/docs/adr/0104-toolchain-release.md +125 -0
  159. package/docs/adr/0105-cesm-ring-mode.md +71 -0
  160. package/docs/adr/0106-module-observabilidad.md +100 -0
  161. package/docs/adr/0107-layout-l1-oraculo.md +67 -0
  162. package/docs/adr/0108-semantica-como-ops.md +69 -0
  163. package/docs/adr/0109-text-input-composition.md +64 -0
  164. package/docs/adr/0110-yoga-3-2.md +63 -0
  165. package/docs/adr/0111-hot-reload-con-estado.md +92 -0
  166. package/docs/adr/0112-metricas-nativas-reales.md +65 -0
  167. package/docs/adr/0113-cesm-proyeccion-ampliada.md +80 -0
  168. package/docs/adr/0114-androidx-deps.md +72 -0
  169. package/docs/adr/0115-coil-imagenes.md +57 -0
  170. package/docs/adr/0116-precomputed-text-off-ui.md +49 -0
  171. package/docs/adr/0117-a11y-state-hint-foco.md +54 -0
  172. package/docs/adr/0118-yoga-3-2-vocabulario.md +98 -0
  173. package/docs/adr/0119-codecs-wire-desde-esquema.md +86 -0
  174. package/docs/adr/0120-unidades-logicas-pointscalefactor.md +73 -0
  175. package/docs/adr/0121-yoga-filas-lista.md +100 -0
  176. package/docs/adr/0122-delegado-layout-subarbol.md +140 -0
  177. package/docs/adr/0123-canvas-sobre-skia-raster.md +101 -0
  178. package/docs/adr/0124-evaluacion-taffy-css-grid.md +52 -0
  179. package/docs/adr/0125-paridad-visual-android.md +89 -0
  180. package/docs/adr/0126-documento-web-metadata-enlaces.md +52 -0
  181. package/docs/adr/0127-perfil-l1-shorthand-flex-herencia-texto.md +70 -0
  182. package/docs/adr/0128-pantalla-llena-fragmentos-transparentes.md +56 -0
  183. package/docs/adr/0129-content-visibility-canvas-unidades-logicas.md +37 -0
  184. package/docs/adr/0130-expresiones-reactivas-ui.md +55 -0
  185. package/docs/adr/0131-state-style.md +59 -0
  186. package/docs/adr/0132-create-theme-system-color-scheme.md +58 -0
  187. package/docs/adr/0133-navegacion-rutas-href-chrome.md +59 -0
  188. package/docs/adr/0134-servicios-ambient-modulos-timers.md +63 -0
  189. package/docs/adr/0135-registro-fuentes.md +67 -0
  190. package/docs/adr/0136-i18n-zonas-dst-locale-reactivo.md +70 -0
  191. package/docs/adr/0137-ssg-universal.md +78 -0
  192. package/docs/adr/0138-plantillas-fila-ui-rowref.md +54 -0
  193. package/docs/adr/0139-paridad-geometrica-e-inspector.md +63 -0
  194. package/docs/adr/0140-medida-line-height-css.md +78 -0
  195. package/docs/adr/0141-build-ssr-autocontenido.md +37 -0
  196. package/docs/adr/0142-tema-ssr-cookie-client-hint.md +42 -0
  197. package/docs/adr/0143-paridad-visual-ci.md +51 -0
  198. package/docs/adr/0144-oraculo-layout-chromium.md +45 -0
  199. package/docs/adr/0145-admision-opcodes-wire.md +89 -0
  200. package/docs/adr/0146-presupuesto-divergencias.md +82 -0
  201. package/docs/adr/0147-spans-texto-enriquecido.md +113 -0
  202. package/docs/adr/0148-scroll-restore.md +92 -0
  203. package/docs/adr/0149-gestion-foco.md +94 -0
  204. package/docs/adr/0150-sticky.md +89 -0
  205. package/docs/adr/0151-politica-migracion-snapshots.md +83 -0
  206. package/docs/adr/0152-vocabulario-semantico-v3.md +112 -0
  207. package/docs/adr/0153-puerta-doc-codigo.md +59 -0
  208. package/docs/adr/0154-matriz-paridad.md +79 -0
  209. package/docs/adr/0155-rtl-ambiente.md +73 -0
  210. package/docs/adr/0156-quickjs-ng-0170.md +55 -0
  211. package/docs/adr/0157-qjsc-bytecode-android.md +73 -0
  212. package/docs/adr/0158-abi-host-explicita.md +62 -0
  213. package/docs/adr/0159-entrada-desktop.md +59 -0
  214. package/docs/adr/0160-port-linux-hallazgos-plataforma.md +91 -0
  215. package/docs/adr/0161-paridad-deeplink-alineacion-estructural.md +76 -0
  216. package/docs/adr/0162-fontscale-linux-fuentes.md +63 -0
  217. package/docs/adr/0163-overflow-hidden-linux-clip.md +67 -0
  218. package/docs/adr/0164-nav-transitions-linux.md +126 -0
  219. package/docs/adr/0165-transiciones-declarativas.md +147 -0
  220. package/docs/adr/0166-ime-composition-linux.md +68 -0
  221. package/docs/adr/0167-spans-pango-linux.md +80 -0
  222. package/docs/adr/0168-statestyle-linux.md +65 -0
  223. package/docs/adr/0169-animate-linux.md +114 -0
  224. package/docs/adr/0170-image-service-linux.md +54 -0
  225. package/docs/adr/0171-semantics-atspi-linux.md +80 -0
  226. package/docs/adr/0172-conformidad-de-host-por-terceros.md +159 -0
  227. package/docs/adr/0173-licencias-espec-y-codigo.md +95 -0
  228. package/docs/adr/0174-tabla-estilo-yoga-compartida.md +67 -0
  229. package/docs/adr/0175-easings-normativos-cubic-bezier.md +68 -0
  230. package/docs/adr/0176-harness-plataforma-linux-y-locale-decimal.md +80 -0
  231. package/docs/adr/0177-gaps-linux-dir-as-navstate.md +84 -0
  232. package/docs/adr/0178-matriz-linux-y-tablas-normativas-generadas.md +104 -0
  233. package/docs/adr/0179-eventos-gesto-y-teclado.md +132 -0
  234. package/docs/adr/0180-desktop-nativo-linux-windows-macos-chromeos.md +58 -0
  235. package/docs/adr/0181-linux-platform-views-uiworklet-y-gaps-certificados.md +101 -0
  236. package/docs/adr/0182-sdui-envelope-dialecto-rico-y-lowering.md +452 -0
  237. package/docs/adr/0183-hermes-es6-block-scoping-en-source-eval.md +99 -0
  238. package/docs/adr/0184-sdui-consumidor-de-referencia-y-modulo-http.md +72 -0
  239. package/docs/adr/0185-sdui-modelo-de-seguridad-del-envelope.md +160 -0
  240. package/docs/adr/0186-linux-packaging-deb-rpm-flatpak.md +61 -0
  241. package/docs/adr/0187-modelo-de-hilos-ejecutores-logicos.md +163 -0
  242. package/docs/adr/0188-sdui-seguridad-hardening.md +214 -0
  243. package/docs/adr/0189-worklets-web-worker-y-egreso-pinning.md +235 -0
  244. package/docs/adr/0190-semantics-actions-linux-via-gaction-muxer.md +102 -0
  245. package/docs/adr/0191-reporte-de-errores-en-produccion.md +126 -0
  246. package/docs/adr/0192-source-maps-y-simbolizacion-de-stacks.md +107 -0
  247. package/docs/adr/0193-renderer-skia-opt-in-en-linux.md +143 -0
  248. package/docs/adr/0194-superficie-declarada-y-carril-skia-tree.md +96 -0
  249. package/docs/adr/0195-bundles-embebidos-subpaths-core.md +66 -0
  250. package/docs/adr/0196-matriz-capacidades-verdad.md +84 -0
  251. package/docs/adr/0197-entorno-reactivo-cableado.md +67 -0
  252. package/docs/adr/0198-csprng-host-wintertc.md +57 -0
  253. package/docs/adr/0199-testing-harness-dom-free.md +59 -0
  254. package/docs/adr/0200-overlays-back-foco.md +84 -0
  255. package/docs/adr/0201-paridad-nativa-props-texto-fase1.md +79 -0
  256. package/docs/adr/0202-node-ref-measure-web.md +61 -0
  257. package/docs/adr/0203-primitivas-headless.md +54 -0
  258. package/docs/adr/0204-imagen-load-error-fallback.md +123 -0
  259. package/docs/adr/0205-primitivas-controls-fase2.md +79 -0
  260. package/docs/adr/0206-a2ui-catalogo-tabs-modal-choicepicker-icon.md +110 -0
  261. package/docs/adr/0207-a2ui-superficie-viva.md +104 -0
  262. package/docs/adr/0208-a2ui-checks-validacion.md +94 -0
  263. package/docs/adr/0209-loaddata-nativo-default.md +56 -0
  264. package/docs/adr/0210-primitivas-navegacion-fase3.md +69 -0
  265. package/docs/adr/0211-a2ui-formato-localizado.md +113 -0
  266. package/docs/adr/0212-red-fuera-del-core.md +67 -0
  267. package/docs/adr/0213-dev-fast-y-rutas-automaticas.md +68 -0
  268. package/docs/adr/0214-dev-web-server-reload.md +55 -0
  269. package/docs/adr/0215-ui-host-noderef-back-http-linux.md +77 -0
  270. package/docs/adr/0216-paridad-nativa-switch-scroll-lista.md +53 -0
  271. package/docs/adr/0217-overlays-drag-y-popover-anclado.md +64 -0
  272. package/docs/adr/0218-sdui-gateway-live-mcp-y-scaffold.md +31 -0
  273. package/docs/adr/0219-event-ref-envelope-y-oracle-scroll-aware.md +82 -0
  274. package/docs/adr/README.md +229 -0
  275. package/docs/deuda/i18n-libreria-separada.md +50 -0
  276. package/docs/doc-data.json +2788 -0
  277. package/docs/propuestas/demo-google-devfest-a2ui-sdui.md +374 -0
  278. package/docs/propuestas/dx-y-paridad.md +684 -0
  279. package/docs/propuestas/investigacion-apps-completas/PENDIENTES-CORE-APPS-COMPLETAS.md +226 -0
  280. package/docs/propuestas/investigacion-apps-completas/arquitectura-motor-videojuegos-elur.md +254 -0
  281. package/docs/propuestas/investigacion-apps-completas/auditoria-paridad-frameworks-y-sdui.md +295 -0
  282. package/docs/propuestas/investigacion-apps-completas/ciclo-de-vida-dx-y-apps-completas.md +394 -0
  283. package/docs/propuestas/investigacion-apps-completas/crear-proyecto-desde-npm-y-agentes.md +477 -0
  284. package/docs/propuestas/investigacion-apps-completas/especificacion-arquitectura-capacidades-faltantes.md +407 -0
  285. package/docs/propuestas/investigacion-apps-completas/identidad-y-nombre-elur-universal.md +133 -0
  286. package/docs/propuestas/investigacion-apps-completas/migracion-elur-core-4.md +266 -0
  287. package/docs/propuestas/investigacion-apps-completas/sdui-a2ui-aplicaciones-completas.md +255 -0
  288. package/docs/propuestas/investigacion-apps-completas/verificacion-mejoras-y-brechas-nuevas.md +228 -0
  289. package/docs/propuestas/modelo-de-consumo.md +287 -0
  290. package/docs/propuestas/modulos-nativos.md +1062 -0
  291. package/docs/propuestas/palabras-clave-normativas.md +69 -0
  292. package/docs/propuestas/sdui-seguridad-hardening.md +322 -0
  293. package/docs/propuestas/skia-graphite.md +167 -0
  294. package/docs/propuestas/skia-renderer-arbol.md +603 -0
  295. package/docs/propuestas/targets-nativos-nuevos.md +359 -0
  296. package/docs/propuestas/toolchain-y-distribucion.md +311 -0
  297. package/docs/propuestas/ui-worklet-capacidades-exclusivas.md +114 -0
  298. package/examples/a11ylive/elur.app.json +8 -0
  299. package/examples/a11ylive/entry.ts +22 -0
  300. package/examples/a11ysem/elur.app.json +8 -0
  301. package/examples/a11ysem/entry.ts +24 -0
  302. package/examples/anim/elur.app.json +8 -0
  303. package/examples/anim/entry.ts +50 -0
  304. package/examples/app.ts +10 -0
  305. package/examples/cliprad/elur.app.json +8 -0
  306. package/examples/cliprad/entry.ts +16 -0
  307. package/examples/controls/app.ts +32 -0
  308. package/examples/controls/elur.app.json +8 -0
  309. package/examples/counter/app.ts +21 -0
  310. package/examples/counter/elur.app.json +8 -0
  311. package/examples/counter/entry.ts +7 -0
  312. package/examples/entry.ts +11 -0
  313. package/examples/feedstress/app.ts +334 -0
  314. package/examples/feedstress/elur.app.json +8 -0
  315. package/examples/feedstress/entry.ts +7 -0
  316. package/examples/i18n/app.ts +86 -0
  317. package/examples/i18n/elur.app.json +8 -0
  318. package/examples/i18n/entry.ts +22 -0
  319. package/examples/imecomp/elur.app.json +8 -0
  320. package/examples/imecomp/entry.ts +41 -0
  321. package/examples/imgtest/elur.app.json +8 -0
  322. package/examples/imgtest/entry.ts +18 -0
  323. package/examples/mareas/app/ajustes/page.ts +54 -0
  324. package/examples/mareas/app/page.ts +91 -0
  325. package/examples/mareas/app/puerto/[id]/page.ts +106 -0
  326. package/examples/mareas/app.ts +12 -0
  327. package/examples/mareas/elur.app.json +35 -0
  328. package/examples/mareas/entry.ts +11 -0
  329. package/examples/mareas/fonts/DejaVuSansMono-Bold.ttf +0 -0
  330. package/examples/mareas/fonts/DejaVuSansMono.ttf +0 -0
  331. package/examples/mareas/fonts/DejaVuSerif-Bold.ttf +0 -0
  332. package/examples/mareas/fonts/DejaVuSerif-Italic.ttf +0 -0
  333. package/examples/mareas/fonts/DejaVuSerif.ttf +0 -0
  334. package/examples/mareas/fonts/LICENSE-DejaVu.txt +187 -0
  335. package/examples/mareas/fonts.ts +6 -0
  336. package/examples/mareas/head.ts +12 -0
  337. package/examples/mareas/i18n.ts +163 -0
  338. package/examples/mareas/ports.ts +131 -0
  339. package/examples/mareas/routes.gen.ts +44 -0
  340. package/examples/mareas/serve.ts +70 -0
  341. package/examples/mareas/services.ts +5 -0
  342. package/examples/mareas/services.web.ts +6 -0
  343. package/examples/mareas/state.ts +64 -0
  344. package/examples/mareas/theme.ts +56 -0
  345. package/examples/mareas/ui/controls.ts +42 -0
  346. package/examples/mareas/ui/frame.ts +63 -0
  347. package/examples/mareas/ui/marigram.ts +52 -0
  348. package/examples/masonry/app.ts +32 -0
  349. package/examples/masonry/elur.app.json +8 -0
  350. package/examples/masonry/entry.ts +4 -0
  351. package/examples/natprobe/elur.app.json +8 -0
  352. package/examples/natprobe/entry.ts +196 -0
  353. package/examples/navdemo/app.ts +109 -0
  354. package/examples/navdemo/elur.app.json +8 -0
  355. package/examples/navdemo/entry.ts +7 -0
  356. package/examples/navtrans/elur.app.json +8 -0
  357. package/examples/navtrans/entry.ts +53 -0
  358. package/examples/platformview/app.ts +26 -0
  359. package/examples/platformview/elur.app.json +8 -0
  360. package/examples/sdui-demo/docs/home.envelope.json +588 -0
  361. package/examples/sdui-demo/docs/home.iife.json +582 -0
  362. package/examples/sdui-demo/elur.app.json +8 -0
  363. package/examples/sdui-demo/entry.ts +346 -0
  364. package/examples/select/elur.app.json +8 -0
  365. package/examples/select/entry.ts +20 -0
  366. package/examples/skiacanvas/app.ts +34 -0
  367. package/examples/skiacanvas/elur.app.json +8 -0
  368. package/examples/skiacanvas/entry.ts +4 -0
  369. package/examples/spans/elur.app.json +8 -0
  370. package/examples/spans/entry.ts +28 -0
  371. package/examples/ssr/app/about/page.ts +18 -0
  372. package/examples/ssr/app/items/[id]/page.ts +16 -0
  373. package/examples/ssr/app/layout.ts +21 -0
  374. package/examples/ssr/app/page.action.ts +10 -0
  375. package/examples/ssr/app/page.data.ts +5 -0
  376. package/examples/ssr/app/page.ts +95 -0
  377. package/examples/ssr/app/slow/loading.ts +10 -0
  378. package/examples/ssr/app/slow/page.data.ts +4 -0
  379. package/examples/ssr/app/slow/page.ts +16 -0
  380. package/examples/ssr/app/store.ts +3 -0
  381. package/examples/ssr/serve.ts +53 -0
  382. package/examples/statestyle/elur.app.json +8 -0
  383. package/examples/statestyle/entry.ts +25 -0
  384. package/examples/swipe/elur.app.json +8 -0
  385. package/examples/swipe/entry.ts +39 -0
  386. package/examples/tasks/app.ts +145 -0
  387. package/examples/tasks/elur.app.json +8 -0
  388. package/examples/uiwk/app.ts +288 -0
  389. package/examples/uiwk/elur.app.json +8 -0
  390. package/examples/uiwk/entry.ts +7 -0
  391. package/examples/vertical/app.ts +275 -0
  392. package/examples/vertical/elur.app.json +8 -0
  393. package/examples/vertical/entry.ts +31 -0
  394. package/examples/yogafeatures/app.ts +55 -0
  395. package/examples/yogafeatures/elur.app.json +8 -0
  396. package/examples/yogafeatures/entry.ts +4 -0
  397. package/native/cesm/README.md +94 -0
  398. package/native/cesm/adapters/hermes/HermesAdapter.h +432 -0
  399. package/native/cesm/adapters/quickjs/QuickJsAdapter.h +562 -0
  400. package/native/cesm/core/Bytes.h +236 -0
  401. package/native/cesm/core/Core.h +157 -0
  402. package/native/cesm/core/EngineAdapter.h +20 -0
  403. package/native/cesm/core/Region.h +77 -0
  404. package/native/cesm/core/Ring.h +99 -0
  405. package/native/cesm/core/Slots.h +132 -0
  406. package/native/cesm/core/Types.h +67 -0
  407. package/native/cesm/tests/CMakeLists.txt +50 -0
  408. package/native/cesm/tests/README.md +89 -0
  409. package/native/cesm/tests/compile_check_hermes.cpp +23 -0
  410. package/native/cesm/tests/test_core.cpp +101 -0
  411. package/native/cesm/tests/test_main.cpp +13 -0
  412. package/native/cesm/tests/test_quickjs_adapter.cpp +252 -0
  413. package/native/cesm/tests/test_ring.cpp +131 -0
  414. package/native/cesm/tests/test_slots.cpp +81 -0
  415. package/native/cesm/tests/test_sync.cpp +157 -0
  416. package/native/cesm/tests/test_util.h +24 -0
  417. package/native/layout/elur_layout_style.cpp +297 -0
  418. package/native/layout/elur_layout_style.h +36 -0
  419. package/native/layout-oracle/CMakeLists.txt +22 -0
  420. package/native/layout-oracle/oracle.cpp +140 -0
  421. package/native/rand/elur_random.h +43 -0
  422. package/native/skia-tree/elur_skia_tree.cpp +1293 -0
  423. package/native/skia-tree/elur_skia_tree.h +231 -0
  424. package/native/yoga/LICENSE +21 -0
  425. package/native/yoga/YGConfig.cpp +92 -0
  426. package/native/yoga/YGConfig.h +158 -0
  427. package/native/yoga/YGEnums.cpp +262 -0
  428. package/native/yoga/YGEnums.h +142 -0
  429. package/native/yoga/YGMacros.h +99 -0
  430. package/native/yoga/YGNode.cpp +366 -0
  431. package/native/yoga/YGNode.h +304 -0
  432. package/native/yoga/YGNodeLayout.cpp +92 -0
  433. package/native/yoga/YGNodeLayout.h +35 -0
  434. package/native/yoga/YGNodeStyle.cpp +405 -0
  435. package/native/yoga/YGNodeStyle.h +130 -0
  436. package/native/yoga/YGPixelGrid.cpp +22 -0
  437. package/native/yoga/YGPixelGrid.h +29 -0
  438. package/native/yoga/YGValue.cpp +20 -0
  439. package/native/yoga/YGValue.h +84 -0
  440. package/native/yoga/Yoga.h +21 -0
  441. package/native/yoga/algorithm/AbsoluteLayout.cpp +563 -0
  442. package/native/yoga/algorithm/AbsoluteLayout.h +41 -0
  443. package/native/yoga/algorithm/Align.h +72 -0
  444. package/native/yoga/algorithm/Baseline.cpp +78 -0
  445. package/native/yoga/algorithm/Baseline.h +21 -0
  446. package/native/yoga/algorithm/BoundAxis.h +79 -0
  447. package/native/yoga/algorithm/Cache.cpp +121 -0
  448. package/native/yoga/algorithm/Cache.h +30 -0
  449. package/native/yoga/algorithm/CalculateLayout.cpp +2428 -0
  450. package/native/yoga/algorithm/CalculateLayout.h +38 -0
  451. package/native/yoga/algorithm/FlexDirection.h +120 -0
  452. package/native/yoga/algorithm/FlexLine.cpp +124 -0
  453. package/native/yoga/algorithm/FlexLine.h +75 -0
  454. package/native/yoga/algorithm/PixelGrid.cpp +132 -0
  455. package/native/yoga/algorithm/PixelGrid.h +29 -0
  456. package/native/yoga/algorithm/SizingMode.h +73 -0
  457. package/native/yoga/algorithm/TrailingPosition.h +44 -0
  458. package/native/yoga/config/Config.cpp +135 -0
  459. package/native/yoga/config/Config.h +92 -0
  460. package/native/yoga/debug/AssertFatal.cpp +53 -0
  461. package/native/yoga/debug/AssertFatal.h +29 -0
  462. package/native/yoga/debug/Log.cpp +107 -0
  463. package/native/yoga/debug/Log.h +34 -0
  464. package/native/yoga/enums/Align.h +47 -0
  465. package/native/yoga/enums/BoxSizing.h +40 -0
  466. package/native/yoga/enums/Dimension.h +40 -0
  467. package/native/yoga/enums/Direction.h +41 -0
  468. package/native/yoga/enums/Display.h +41 -0
  469. package/native/yoga/enums/Edge.h +47 -0
  470. package/native/yoga/enums/Errata.h +41 -0
  471. package/native/yoga/enums/ExperimentalFeature.h +39 -0
  472. package/native/yoga/enums/FlexDirection.h +42 -0
  473. package/native/yoga/enums/Gutter.h +41 -0
  474. package/native/yoga/enums/Justify.h +44 -0
  475. package/native/yoga/enums/LogLevel.h +44 -0
  476. package/native/yoga/enums/MeasureMode.h +41 -0
  477. package/native/yoga/enums/NodeType.h +40 -0
  478. package/native/yoga/enums/Overflow.h +41 -0
  479. package/native/yoga/enums/PhysicalEdge.h +21 -0
  480. package/native/yoga/enums/PositionType.h +41 -0
  481. package/native/yoga/enums/Unit.h +42 -0
  482. package/native/yoga/enums/Wrap.h +41 -0
  483. package/native/yoga/enums/YogaEnums.h +85 -0
  484. package/native/yoga/event/event.cpp +87 -0
  485. package/native/yoga/event/event.h +130 -0
  486. package/native/yoga/node/CachedMeasurement.h +53 -0
  487. package/native/yoga/node/LayoutResults.cpp +48 -0
  488. package/native/yoga/node/LayoutResults.h +122 -0
  489. package/native/yoga/node/LayoutableChildren.h +148 -0
  490. package/native/yoga/node/Node.cpp +443 -0
  491. package/native/yoga/node/Node.h +337 -0
  492. package/native/yoga/numeric/Comparison.h +81 -0
  493. package/native/yoga/numeric/FloatOptional.h +93 -0
  494. package/native/yoga/style/SmallValueBuffer.h +133 -0
  495. package/native/yoga/style/Style.h +757 -0
  496. package/native/yoga/style/StyleLength.h +107 -0
  497. package/native/yoga/style/StyleValueHandle.h +98 -0
  498. package/native/yoga/style/StyleValuePool.h +127 -0
  499. package/package.json +112 -3
  500. package/src/adapters/kit-bridge.ts +72 -0
  501. package/src/adapters/kit-ssg.ts +219 -0
  502. package/src/adapters/kit-ssr.ts +577 -0
  503. package/src/adapters/kit-types.ts +28 -0
  504. package/src/adapters/request-adapter.ts +41 -0
  505. package/src/adapters/ssr-resolver.ts +177 -0
  506. package/src/adapters/web-history.ts +218 -0
  507. package/src/adapters/web-nav-executor.ts +72 -0
  508. package/src/animations/.gitkeep +0 -0
  509. package/src/animations/bindWorklets.ts +49 -0
  510. package/src/animations/captureCheck.ts +75 -0
  511. package/src/animations/compose.ts +127 -0
  512. package/src/animations/easing.ts +75 -0
  513. package/src/animations/gestureWorklets.ts +129 -0
  514. package/src/animations/index.ts +23 -0
  515. package/src/animations/runner.ts +404 -0
  516. package/src/animations/scrollWorklets.ts +48 -0
  517. package/src/animations/uiBindings.ts +83 -0
  518. package/src/animations/uiRunner.ts +449 -0
  519. package/src/animations/worklet.ts +157 -0
  520. package/src/animations/workletForm.ts +197 -0
  521. package/src/app/clock.ts +69 -0
  522. package/src/app/embedded.ts +232 -0
  523. package/src/app/index.ts +24 -0
  524. package/src/app/load-data.ts +36 -0
  525. package/src/app/mount.native.ts +18 -0
  526. package/src/app/mount.ts +26 -0
  527. package/src/app/mount.web.ts +21 -0
  528. package/src/app/state.ts +256 -0
  529. package/src/app/types.ts +146 -0
  530. package/src/app/web.ts +291 -0
  531. package/src/backends/native/hostAbi.ts +304 -0
  532. package/src/backends/native/index.ts +1132 -0
  533. package/src/backends/textInputProtocol.ts +111 -0
  534. package/src/backends/web/.gitkeep +0 -0
  535. package/src/backends/web/base-css.ts +148 -0
  536. package/src/backends/web/batcher.ts +162 -0
  537. package/src/backends/web/hydrate.ts +227 -0
  538. package/src/backends/web/index.ts +2231 -0
  539. package/src/backends/web/inspect.ts +80 -0
  540. package/src/backends/web/workerRunner.ts +513 -0
  541. package/src/context/index.ts +19 -0
  542. package/src/events.ts +139 -0
  543. package/src/forms/index.ts +264 -0
  544. package/src/hydration/.gitkeep +0 -0
  545. package/src/index.ts +169 -0
  546. package/src/ir/.gitkeep +0 -0
  547. package/src/ir/catalog.ts +166 -0
  548. package/src/ir/events.ts +54 -0
  549. package/src/ir/schema.ts +1103 -0
  550. package/src/ir/semantics.ts +189 -0
  551. package/src/ir/shortcut.ts +104 -0
  552. package/src/ir/signal-names.ts +27 -0
  553. package/src/ir/ui.ts +709 -0
  554. package/src/layout/.gitkeep +0 -0
  555. package/src/native/.gitkeep +0 -0
  556. package/src/native/binaryCodec.ts +230 -0
  557. package/src/native/codegen.ts +635 -0
  558. package/src/native/hostArtifacts.ts +386 -0
  559. package/src/native/http.ts +558 -0
  560. package/src/native/index.ts +54 -0
  561. package/src/native/manifest.ts +227 -0
  562. package/src/native/module.ts +1108 -0
  563. package/src/native/platformView.ts +107 -0
  564. package/src/native/pluginManifest.ts +269 -0
  565. package/src/native/sharedMemory.ts +168 -0
  566. package/src/native/specType.ts +164 -0
  567. package/src/native/tck.ts +436 -0
  568. package/src/native/trace.ts +97 -0
  569. package/src/native/webModule.ts +281 -0
  570. package/src/overlays/index.ts +579 -0
  571. package/src/platform.ts +89 -0
  572. package/src/primitives/controls.ts +725 -0
  573. package/src/primitives/index.ts +400 -0
  574. package/src/primitives/navigation.ts +407 -0
  575. package/src/reconciler/reconciler.ts +2857 -0
  576. package/src/router/guards.ts +129 -0
  577. package/src/router/index.ts +41 -0
  578. package/src/router/lifecycle.ts +133 -0
  579. package/src/router/match.ts +184 -0
  580. package/src/router/router.ts +508 -0
  581. package/src/router/screen-host.ts +918 -0
  582. package/src/router/state.ts +76 -0
  583. package/src/router/table.ts +55 -0
  584. package/src/router/transitions.ts +87 -0
  585. package/src/router/types.ts +161 -0
  586. package/src/runtime/environment.ts +332 -0
  587. package/src/runtime/wintertc-globals.ts +1067 -0
  588. package/src/sdui/a2ui.ts +1480 -0
  589. package/src/sdui/a2uiSurface.ts +214 -0
  590. package/src/sdui/client.ts +370 -0
  591. package/src/sdui/cryptoModule.ts +107 -0
  592. package/src/sdui/diagnostics.ts +39 -0
  593. package/src/sdui/downlevel.ts +375 -0
  594. package/src/sdui/envelope.ts +729 -0
  595. package/src/sdui/expr.ts +658 -0
  596. package/src/sdui/gateway.ts +223 -0
  597. package/src/sdui/httpModule.ts +29 -0
  598. package/src/sdui/index.ts +74 -0
  599. package/src/sdui/intents.ts +217 -0
  600. package/src/sdui/lower.ts +576 -0
  601. package/src/sdui/machines.ts +141 -0
  602. package/src/sdui/manifest.ts +167 -0
  603. package/src/sdui/oracle.ts +400 -0
  604. package/src/sdui/profile.ts +72 -0
  605. package/src/sdui/seqStore.ts +89 -0
  606. package/src/sdui/sign.ts +155 -0
  607. package/src/sdui/worklets.ts +164 -0
  608. package/src/ssr/html-applicator.ts +515 -0
  609. package/src/ssr/render-page.ts +264 -0
  610. package/src/store/index.ts +28 -0
  611. package/src/style/textInherit.ts +29 -0
  612. package/src/style/theme.ts +178 -0
  613. package/src/testing/index.ts +276 -0
  614. package/src/transport/.gitkeep +0 -0
  615. package/src/transport/format.ts +477 -0
  616. package/src/transport/wireSchema.ts +189 -0
  617. package/src/web.ts +31 -0
  618. package/targets/android/app/build.gradle.kts +192 -0
  619. package/targets/android/app/proguard-rules-elur.pro +12 -0
  620. package/targets/android/app/proguard-rules.pro +3 -0
  621. package/targets/android/app/src/main/AndroidManifest.xml +81 -0
  622. package/targets/android/app/src/main/cpp/CMakeLists.txt +117 -0
  623. package/targets/android/app/src/main/cpp/dlEncoder.h +117 -0
  624. package/targets/android/app/src/main/cpp/dlEncoderJsi.cpp +315 -0
  625. package/targets/android/app/src/main/cpp/dlEncoderQjs.cpp +394 -0
  626. package/targets/android/app/src/main/cpp/dlOps.inc +145 -0
  627. package/targets/android/app/src/main/cpp/elurBridge.cpp +1350 -0
  628. package/targets/android/app/src/main/cpp/elurBridgeHermes.cpp +1294 -0
  629. package/targets/android/app/src/main/cpp/elurSkia.cpp +287 -0
  630. package/targets/android/app/src/main/cpp/elurSkiaTree.cpp +448 -0
  631. package/targets/android/app/src/main/cpp/elurUiWorklet.cpp +1233 -0
  632. package/targets/android/app/src/main/cpp/elurYoga.cpp +1060 -0
  633. package/targets/android/app/src/main/cpp/elurYoga.h +82 -0
  634. package/targets/android/app/src/main/cpp/hermes-libs/LICENSE +21 -0
  635. package/targets/android/app/src/main/cpp/hermes-libs/arm64-v8a/libhermesvm.so +0 -0
  636. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/AsyncDebuggerAPI.h +276 -0
  637. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/CompileJS.h +97 -0
  638. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/DebuggerAPI.h +502 -0
  639. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/CrashManager.h +107 -0
  640. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/CtorConfig.h +145 -0
  641. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/DebuggerTypes.h +193 -0
  642. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/GCConfig.h +211 -0
  643. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/GCTripwireContext.h +40 -0
  644. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/HermesExport.h +14 -0
  645. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/JSOutOfMemoryError.h +27 -0
  646. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/RuntimeConfig.h +141 -0
  647. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/SamplingProfiler.h +270 -0
  648. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/RuntimeTaskRunner.h +64 -0
  649. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/SynthTrace.h +1566 -0
  650. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/SynthTraceParser.h +37 -0
  651. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/ThreadSafetyAnalysis.h +75 -0
  652. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/TimerStats.h +23 -0
  653. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/TraceInterpreter.h +334 -0
  654. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/TracingRuntime.h +328 -0
  655. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPAgent.h +131 -0
  656. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPDebugAPI.h +73 -0
  657. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/CallbackOStream.h +89 -0
  658. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/ConsoleMessage.h +135 -0
  659. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainAgent.h +280 -0
  660. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainCoordinator.h +137 -0
  661. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainAgent.h +107 -0
  662. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainState.h +140 -0
  663. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/HeapProfilerDomainAgent.h +71 -0
  664. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/JSONValueInterfaces.h +40 -0
  665. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageConverters.h +82 -0
  666. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageInterfaces.h +72 -0
  667. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypes.h +1279 -0
  668. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypesInlines.h +313 -0
  669. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/ProfilerDomainAgent.h +38 -0
  670. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectConverters.h +77 -0
  671. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectsTable.h +127 -0
  672. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/RuntimeDomainAgent.h +138 -0
  673. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/Dummy.h +24 -0
  674. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/Extensions.h +20 -0
  675. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/ExtensionsBytecode.h +23 -0
  676. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/Intrinsics.h +44 -0
  677. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/JSIUtils.h +123 -0
  678. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/TextEncoder.h +29 -0
  679. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribDummy.h +24 -0
  680. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribExtensions.h +23 -0
  681. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoder.h +30 -0
  682. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoderUtils.h +113 -0
  683. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/hermes.h +242 -0
  684. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/hermes_tracing.h +52 -0
  685. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIHelpers.h +295 -0
  686. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIRuntimeWrapper.h +25 -0
  687. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_abi.h +642 -0
  688. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_vtable.h +29 -0
  689. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/HermesSandboxRuntime.h +41 -0
  690. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_compiled.h +12 -0
  691. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled-impl.h +8516 -0
  692. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled.h +137 -0
  693. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled-impl.h +3945 -0
  694. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled.h +119 -0
  695. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-fb.h +124 -0
  696. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-impl.h +66 -0
  697. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt.h +456 -0
  698. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/JSIDynamic.h +26 -0
  699. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/decorator.h +1157 -0
  700. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/hermes-interfaces.h +242 -0
  701. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/instrumentation.h +132 -0
  702. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/jsi-inl.h +434 -0
  703. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/jsi.h +2266 -0
  704. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/jsilib.h +59 -0
  705. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/threadsafe.h +79 -0
  706. package/targets/android/app/src/main/cpp/hermes-libs/jsi-impl/jsi.cpp +1111 -0
  707. package/targets/android/app/src/main/cpp/hermes-libs/x86_64/libhermesvm.so +0 -0
  708. package/targets/android/app/src/main/java/com/elur/universal/BinaryCodec.kt +121 -0
  709. package/targets/android/app/src/main/java/com/elur/universal/DlDecoder.kt +260 -0
  710. package/targets/android/app/src/main/java/com/elur/universal/DlOpsDecode.kt +158 -0
  711. package/targets/android/app/src/main/java/com/elur/universal/ElurBoxDrawable.kt +161 -0
  712. package/targets/android/app/src/main/java/com/elur/universal/ElurBridge.kt +238 -0
  713. package/targets/android/app/src/main/java/com/elur/universal/ElurBridgeHermes.kt +223 -0
  714. package/targets/android/app/src/main/java/com/elur/universal/ElurCanvasView.kt +202 -0
  715. package/targets/android/app/src/main/java/com/elur/universal/ElurCryptoModule.kt +206 -0
  716. package/targets/android/app/src/main/java/com/elur/universal/ElurCustomLayout.kt +185 -0
  717. package/targets/android/app/src/main/java/com/elur/universal/ElurEditText.kt +17 -0
  718. package/targets/android/app/src/main/java/com/elur/universal/ElurFontRegistry.kt +190 -0
  719. package/targets/android/app/src/main/java/com/elur/universal/ElurHttpModule.kt +306 -0
  720. package/targets/android/app/src/main/java/com/elur/universal/ElurImageService.kt +348 -0
  721. package/targets/android/app/src/main/java/com/elur/universal/ElurLicensesActivity.kt +84 -0
  722. package/targets/android/app/src/main/java/com/elur/universal/ElurListView.kt +954 -0
  723. package/targets/android/app/src/main/java/com/elur/universal/ElurManifest.kt +117 -0
  724. package/targets/android/app/src/main/java/com/elur/universal/ElurMetrics.kt +325 -0
  725. package/targets/android/app/src/main/java/com/elur/universal/ElurModuleRegistrar.kt +14 -0
  726. package/targets/android/app/src/main/java/com/elur/universal/ElurPermissionGate.kt +36 -0
  727. package/targets/android/app/src/main/java/com/elur/universal/ElurRenderer.kt +6112 -0
  728. package/targets/android/app/src/main/java/com/elur/universal/ElurRowYoga.kt +130 -0
  729. package/targets/android/app/src/main/java/com/elur/universal/ElurScrollView.kt +240 -0
  730. package/targets/android/app/src/main/java/com/elur/universal/ElurShellView.kt +117 -0
  731. package/targets/android/app/src/main/java/com/elur/universal/ElurSkiaCanvasView.kt +162 -0
  732. package/targets/android/app/src/main/java/com/elur/universal/ElurSkiaTreeRenderer.kt +968 -0
  733. package/targets/android/app/src/main/java/com/elur/universal/ElurStateModule.kt +69 -0
  734. package/targets/android/app/src/main/java/com/elur/universal/ElurSwipeDriver.kt +34 -0
  735. package/targets/android/app/src/main/java/com/elur/universal/ElurTckModule.kt +99 -0
  736. package/targets/android/app/src/main/java/com/elur/universal/ElurTextMeasure.kt +16 -0
  737. package/targets/android/app/src/main/java/com/elur/universal/ElurTrace.kt +24 -0
  738. package/targets/android/app/src/main/java/com/elur/universal/ElurUiModule.kt +48 -0
  739. package/targets/android/app/src/main/java/com/elur/universal/ElurUiWorklet.kt +305 -0
  740. package/targets/android/app/src/main/java/com/elur/universal/JsBridge.kt +67 -0
  741. package/targets/android/app/src/main/java/com/elur/universal/JsThread.kt +189 -0
  742. package/targets/android/app/src/main/java/com/elur/universal/MainActivity.kt +844 -0
  743. package/targets/android/app/src/main/java/com/elur/universal/ModuleRegistry.kt +701 -0
  744. package/targets/android/app/src/main/java/com/elur/universal/YogaRowScope.kt +97 -0
  745. package/targets/android/app/src/main/res/values/ids.xml +10 -0
  746. package/targets/android/app/src/main/res/values/strings.xml +8 -0
  747. package/targets/android/app/src/main/res/values-es/strings.xml +5 -0
  748. package/targets/android/app/src/main/res/xml/network_security_config.xml +10 -0
  749. package/targets/android/build.gradle.kts +5 -0
  750. package/targets/android/gradle/libs.versions.toml +12 -0
  751. package/targets/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  752. package/targets/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  753. package/targets/android/gradle.properties +23 -0
  754. package/targets/android/gradlew +251 -0
  755. package/targets/android/gradlew.bat +94 -0
  756. package/targets/android/settings.gradle.kts +32 -0
  757. package/targets/web/.gitkeep +0 -0
  758. package/targets/web/index.html +13 -0
@@ -0,0 +1,2231 @@
1
+ // src/backends/web.ts
2
+ // ADR-0003: Backend web = aplicador puro de ops. El walker del IR vive
3
+ // en el reconciler compartido (src/reconciler/reconciler.ts).
4
+ //
5
+ // Este archivo implementa SOLO:
6
+ // - mapType: IR node type → HTML tag
7
+ // - mapEvent: universal event → DOM event
8
+ // - applyStyle: Style → CSS
9
+ // - applyDisplayOp: DisplayOp → DOM mutation
10
+ //
11
+ // Toda la lógica de walk, bindings reactivos y transaction model
12
+ // vive en el reconciler.
13
+
14
+ import { type Signal } from "@elurjs/core/signals";
15
+ import {
16
+ composeTransformCss, TRANSFORM_STYLE_KEYS,
17
+ spanTree, validateTextSpans,
18
+ type TextSpan, type TextSpanNode,
19
+ } from "../../ir/schema";
20
+ import { liveRegionValue } from "../../ir/semantics";
21
+ import {
22
+ clearNodeElementResolver, refreshNodeRefs, setNodeElementResolver,
23
+ } from "../../runtime/environment";
24
+ import { createTextInputProtocol, type TextInputProtocol } from "../textInputProtocol";
25
+ import type { IRDocument, ListItemFactory, Style } from "../../ir/schema";
26
+ import { type DisplayOp, type IdMap, type TransitionSpec } from "../../transport/format";
27
+ import {
28
+ registerTransition as coreRegisterTransition,
29
+ type TransitionDef,
30
+ type TransitionProps,
31
+ } from "../../router/transitions";
32
+ import { makeEnvelope, type EventDataMap, type EventName } from "../../events";
33
+ import { comboOfKey, firesWhileEditing } from "../../ir/shortcut";
34
+ import { createDisplayListBatcher } from "./batcher";
35
+ import { applyStateStyles, injectBaseCss } from "./base-css";
36
+ import {
37
+ setSystemColorScheme,
38
+ systemColorScheme,
39
+ setThemeCookieSink,
40
+ setThemeCookieSource,
41
+ } from "../../style/theme";
42
+ import { createReconciler } from "../../reconciler/reconciler";
43
+
44
+ // Tipos públicos
45
+
46
+ export interface RenderOptions {
47
+ container: HTMLElement;
48
+ ir: IRDocument;
49
+ signals?: Record<string, Signal<unknown>>;
50
+ handlers?: Record<string, (e?: unknown) => void>;
51
+ /** Funciones extractoras de keys para listas keyed */
52
+ keyFns?: Record<string, (item: any) => string>;
53
+ /** ADR-0037 — factories de repeat() por id (IR serializable). */
54
+ factories?: Record<string, ListItemFactory>;
55
+ }
56
+
57
+ // Props CSS que no llevan "px"
58
+
59
+ const UNITLESS_CSS = new Set([
60
+ "flexGrow", "flexShrink", "opacity", "fontWeight",
61
+ "lineHeight", "zIndex", "order", "zoom",
62
+ ]);
63
+
64
+ // Entry point — usa el reconciler compartido
65
+
66
+ export function renderIR(options: RenderOptions) {
67
+ const { container, ir } = options;
68
+ container.innerHTML = "";
69
+
70
+ // Mapa de id numérico (Display List) → elemento DOM real
71
+ const elementMap = new Map<number, HTMLElement>();
72
+ // ADR-0202 — NodeRef.measureInWindow: el reconciler es DOM-free;
73
+ // el backend resuelve el elemento real por id.
74
+ const resolveElement = (id: number): HTMLElement | undefined =>
75
+ elementMap.get(id);
76
+ setNodeElementResolver(resolveElement);
77
+
78
+ // Ref diferido: el idMap se llena durante el walk del reconciler,
79
+ // pero el batcher lo lee en flush (rAF), cuando ya está completo.
80
+ let idMapRef: IdMap | undefined;
81
+
82
+ const listeners: ListenerRegistry = new Map();
83
+
84
+ // Registry de handlers COMPARTIDO con el reconciler (V05): las filas
85
+ // factory mergean sus handlers aquí — el dispatch debe resolver el
86
+ // nombre en el momento del evento, no una foto del mount.
87
+ const handlerRegistry = (options.handlers ?? {}) as
88
+ Record<string, (e?: unknown) => void>;
89
+
90
+ // Batcher: recibe ops del reconciler y las aplica al DOM
91
+ const ctx: DomApplyCtx = {
92
+ elementMap,
93
+ handlers: handlerRegistry as Record<string, (e?: unknown) => void>,
94
+ container,
95
+ listeners,
96
+ };
97
+ const batcher = createDisplayListBatcher((op) => applyDomOp(op, ctx));
98
+
99
+ // Reconciler compartido — emite ops al batcher
100
+ const reconciler = createReconciler({
101
+ ir,
102
+ signals: options.signals ?? {},
103
+ emit: (op) => batcher.emit(op),
104
+ handlers: handlerRegistry,
105
+ keyFns: options.keyFns ?? {},
106
+ factories: options.factories,
107
+ });
108
+
109
+ // Ahora el idMap está completo — el ctx del aplicador lo usa para
110
+ // data-elur-name (mapa inverso construido una vez, no por nodo).
111
+ idMapRef = reconciler.idMap;
112
+ ctx.idMap = idMapRef;
113
+
114
+ // El root (id=1) no tiene padre en el IR → el reconciler no emite
115
+ // insert-child para él. El backend web inserta el root en el container.
116
+ // Usamos parentId=0 como sentinel: applyDisplayOp sabe que parentId=0
117
+ // significa "insertar en el container real".
118
+ batcher.emit({
119
+ op: "insert-child",
120
+ parentId: 0, // sentinel: container es el padre
121
+ childId: 1,
122
+ index: 0,
123
+ });
124
+
125
+ // Flush síncrono: aplicar todas las ops inmediatamente, sin esperar al rAF.
126
+ // Esto evita que ops de renders anteriores se mezclen con las nuevas.
127
+ batcher.flushSync();
128
+ refreshNodeRefs();
129
+
130
+ return {
131
+ unmount: () => {
132
+ // V02: dispose del reconciler ANTES de matar el batcher — los
133
+ // disposes pueden emitir detach-event que el batcher vivo
134
+ // aplica; después no quedan effects que emitan sobre un
135
+ // backend destruido.
136
+ reconciler.dispose();
137
+ batcher.destroy();
138
+ clearNodeElementResolver(resolveElement);
139
+ // U10: innerHTML solo retira el DOM — un elemento detachado
140
+ // retenido por referencia seguía despachando (el listener es
141
+ // una closure que captura el handler). Quitar los listeners
142
+ // DOM explícitamente antes de vaciar los índices.
143
+ for (const [id, perNode] of listeners) {
144
+ const el = elementMap.get(id);
145
+ if (el) for (const entry of perNode.values()) releaseListener(el, entry);
146
+ }
147
+ container.innerHTML = "";
148
+ // ADR-0131: dispose no emite delete-node — las reglas de la
149
+ // hoja de estados se retiran aquí por id, o quedarían
150
+ // huérfanas entre mounts del mismo documento.
151
+ for (const id of elementMap.keys()) {
152
+ applyStateStyles(container.ownerDocument, id, null);
153
+ }
154
+ listeners.clear();
155
+ elementMap.clear();
156
+ },
157
+ batcher,
158
+ elementMap,
159
+ idMap: reconciler.idMap,
160
+ reconciler,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Aplicador de bajo nivel: recibe ops continuas (p.ej. del ScreenHost con
166
+ * router) y las aplica al DOM via batcher. `handlers` es un registry
167
+ * compartido — el host puede mergear handlers de nuevas pantallas después.
168
+ */
169
+ /**
170
+ * Ambiente web del tema (ADR-0132/0141): matchMedia → signal de esquema
171
+ * del SO + sink/source de cookie para createTheme({cookie}). Lo llama
172
+ * tanto `createWebApplier` como la hidratación — el path SSR+hydrate no
173
+ * pasa por createWebApplier y sin esta llamada el esquema del SO jamás
174
+ * se leía (carril `dark` de la matriz de paridad lo expuso).
175
+ */
176
+ export function installWebThemeEnvironment(doc: Document): void {
177
+ // data-elur-scheme = esquema RESUELTO (lo escribe el SSR para el CSS
178
+ // anti-flash). Con elección explícita (cookie no nula) el override
179
+ // manda; con "system" sigue al SO. Sin esta escritura el attr queda
180
+ // congelado en lo que el SSR pintó.
181
+ let override: "light" | "dark" | null = null;
182
+ const syncAttr = () => doc.documentElement.setAttribute(
183
+ "data-elur-scheme", override ?? systemColorScheme.value);
184
+ const mq = doc.defaultView
185
+ ?.matchMedia?.("(prefers-color-scheme: dark)");
186
+ if (mq) {
187
+ setSystemColorScheme(mq.matches ? "dark" : "light");
188
+ syncAttr();
189
+ mq.addEventListener?.("change", (e: MediaQueryListEvent) => {
190
+ setSystemColorScheme(e.matches ? "dark" : "light");
191
+ syncAttr();
192
+ });
193
+ }
194
+ setThemeCookieSink((name, schemeV) => {
195
+ override = schemeV;
196
+ syncAttr();
197
+ doc.cookie = schemeV === null
198
+ ? `${name}=; Path=/; Max-Age=0; SameSite=Lax`
199
+ : `${name}=${schemeV}; Path=/; Max-Age=31536000; SameSite=Lax`;
200
+ });
201
+ setThemeCookieSource((name) => {
202
+ const m = doc.cookie.match(
203
+ new RegExp(`(?:^|;\\s*)${name}=(light|dark)(?:;|$)`));
204
+ return m ? (m[1] as "light" | "dark") : null;
205
+ });
206
+ }
207
+
208
+ export function createWebApplier(
209
+ container: HTMLElement,
210
+ handlers: Record<string, (e?: unknown) => void>,
211
+ ) {
212
+ const elementMap = new Map<number, HTMLElement>();
213
+ const listeners: ListenerRegistry = new Map();
214
+ const resolveElement = (id: number): HTMLElement | undefined =>
215
+ elementMap.get(id);
216
+ setNodeElementResolver(resolveElement);
217
+ injectBaseCss(container.ownerDocument);
218
+ container.setAttribute("data-elur-root", "");
219
+ installWebThemeEnvironment(container.ownerDocument);
220
+ const ctx: DomApplyCtx = { elementMap, handlers: handlers as Record<string, (e?: unknown) => void>, container, listeners };
221
+ const batcher = createDisplayListBatcher((op) => applyDomOp(op, ctx));
222
+ return {
223
+ emit: (op: DisplayOp) => batcher.emit(op),
224
+ flush: () => {
225
+ batcher.flushSync();
226
+ refreshNodeRefs();
227
+ },
228
+ elementMap,
229
+ destroy: () => {
230
+ batcher.destroy();
231
+ // U10: teardown explícito — los listeners DOM son closures
232
+ // vivas sobre elementos detachados; un elemento retenido
233
+ // seguiría despachando tras el destroy.
234
+ for (const [id, perNode] of listeners) {
235
+ const el = elementMap.get(id);
236
+ if (el) for (const entry of perNode.values()) releaseListener(el, entry);
237
+ }
238
+ listeners.clear();
239
+ elementMap.clear();
240
+ clearNodeElementResolver(resolveElement);
241
+ },
242
+ };
243
+ }
244
+
245
+ // Mapeos (específicos del backend web)
246
+
247
+ function mapType(type: string): string {
248
+ const map: Record<string, string> = {
249
+ column: "div",
250
+ row: "div",
251
+ text: "span",
252
+ button: "button",
253
+ image: "img",
254
+ "text-input": "input",
255
+ "scroll-view": "div",
256
+ switch: "input",
257
+ slider: "input",
258
+ list: "div",
259
+ canvas: "canvas",
260
+ shell: "div",
261
+ "platform-view": "div", // placeholder; el backend real lo resuelve por módulo
262
+ };
263
+ return map[type] ?? "div";
264
+ }
265
+
266
+ // Registry de platform-views en web: module:view → { create, apply }.
267
+ // El contrato de props lo define el módulo; `apply` lo mapea al DOM.
268
+ // "web:webview" = iframe (espejo del WebView nativo de Android): url → src.
269
+ interface PlatformViewDef {
270
+ create: () => HTMLElement;
271
+ apply?: (el: HTMLElement, props: Record<string, unknown>) => void;
272
+ }
273
+ const platformViews = new Map<string, PlatformViewDef>();
274
+ platformViews.set("web:webview", {
275
+ create: () => {
276
+ const f = document.createElement("iframe");
277
+ f.style.border = "none";
278
+ return f;
279
+ },
280
+ apply: (el, props) => {
281
+ for (const [k, v] of Object.entries(props)) {
282
+ (el as any)[k === "url" ? "src" : k] = v;
283
+ }
284
+ },
285
+ });
286
+
287
+ export function registerPlatformView(
288
+ module: string, view: string, def: PlatformViewDef,
289
+ ) {
290
+ platformViews.set(`${module}:${view}`, def);
291
+ }
292
+
293
+ const pvDefsById = new Map<number, PlatformViewDef>();
294
+
295
+ // Transiciones de navegación (Phase 1.5 · WAAPI). Se anima la pantalla
296
+ // entrante/revelada: cuando la op nav llega, la saliente ya está
297
+ // detached → parallax de dos pantallas exige deferred-detach (diseño
298
+ // en ADR-0013). `custom` busca en el registry por nombre.
299
+ const customTransitions = new Map<string, (el: HTMLElement, navOp: string, dur?: number) => void>();
300
+ // shell element → última pantalla detachada este frame (remove-child).
301
+ // La op nav-* la consume para el parallax saliente (ADR-0013).
302
+ const detachedScreens = new Map<HTMLElement, HTMLElement>();
303
+
304
+ /** Registra el hijo detachado de un shell para el parallax (ADR-0013). */
305
+ export function trackDetachedScreen(shellEl: HTMLElement, child: HTMLElement): void {
306
+ detachedScreens.set(shellEl, child);
307
+ }
308
+
309
+ /** Registra una transición custom: descriptor declarativo (ADR-0165 —
310
+ * va al registry compartido DOM-free y viaja a nativo) o función WAAPI
311
+ * directa (solo web — registry local). */
312
+ export function registerTransition(
313
+ name: string,
314
+ fn: (el: HTMLElement, navOp: string, dur?: number) => void,
315
+ ): void;
316
+ export function registerTransition(name: string, def: TransitionDef): void;
317
+ export function registerTransition(
318
+ name: string,
319
+ fnOrDef:
320
+ | TransitionDef
321
+ | ((el: HTMLElement, navOp: string, dur?: number) => void),
322
+ ): void {
323
+ if (typeof fnOrDef === "function") customTransitions.set(name, fnOrDef);
324
+ else coreRegisterTransition(name, fnOrDef);
325
+ }
326
+
327
+ /** Swipe-back interactivo (ADR-0013): edge-drag desde el borde izquierdo
328
+ * del shell conduce las DOS pantallas — la previa montada por
329
+ * hooks.begin() (popPreview del screen-host: ops de preview, sin commit
330
+ * de router) y la top. Al soltar: progress ≥33% o flick rápido →
331
+ * settle animado + commit() (router.back con transition none); si no →
332
+ * vuelta a posición + cancel() (re-detach de la previa).
333
+ * Los transforms del gesto son inline (el gesto es input, no estado —
334
+ * igual que el scroll); el commit intercambia el stack real. */
335
+ export interface SwipeBackHooks {
336
+ begin(): { prevId: number; topId: number } | null;
337
+ commit(): void;
338
+ cancel(): void;
339
+ }
340
+
341
+ const SWIPE_EDGE_PX = 24;
342
+ const SWIPE_COMMIT_RATIO = 0.33;
343
+ const SWIPE_FLICK_PX_MS = 0.3;
344
+
345
+ export function attachSwipeBack(
346
+ shell: HTMLElement,
347
+ hooks: SwipeBackHooks,
348
+ elementMap: Map<number, HTMLElement>,
349
+ ): void {
350
+ let prev: HTMLElement | null = null;
351
+ let top: HTMLElement | null = null;
352
+ let active = false;
353
+ let startX = 0;
354
+ let lastX = 0;
355
+ let lastT = 0;
356
+
357
+ shell.addEventListener("pointerdown", (e) => {
358
+ const pe = e as PointerEvent;
359
+ if (active || pe.clientX > SWIPE_EDGE_PX || pe.isPrimary === false) return;
360
+ const ids = hooks.begin();
361
+ if (!ids) return;
362
+ prev = elementMap.get(ids.prevId) ?? null;
363
+ top = elementMap.get(ids.topId) ?? null;
364
+ if (!prev || !top) { hooks.cancel(); return; }
365
+ active = true;
366
+ startX = lastX = pe.clientX;
367
+ lastT = pe.timeStamp;
368
+ try { shell.setPointerCapture(pe.pointerId); } catch { /* jsdom */ }
369
+ prev.style.transform = "translateX(-30%)";
370
+ });
371
+
372
+ shell.addEventListener("pointermove", (e) => {
373
+ const pe = e as PointerEvent;
374
+ if (!active || !prev || !top) return;
375
+ const w = shell.clientWidth || shell.getBoundingClientRect().width || 1;
376
+ const dx = Math.max(0, pe.clientX - startX);
377
+ const t = Math.min(dx / w, 1);
378
+ lastX = pe.clientX;
379
+ lastT = pe.timeStamp;
380
+ top.style.transform = `translateX(${dx}px)`;
381
+ prev.style.transform = `translateX(${-30 + 30 * t}%)`;
382
+ });
383
+
384
+ const finish = (e: Event, isCancel: boolean) => {
385
+ const pe = e as PointerEvent;
386
+ if (!active || !prev || !top) return;
387
+ active = false;
388
+ const w = shell.clientWidth || shell.getBoundingClientRect().width || 1;
389
+ const dx = Math.max(0, (pe.clientX ?? lastX) - startX);
390
+ const t = Math.min(dx / w, 1);
391
+ const dt = Math.max(pe.timeStamp - lastT, 1);
392
+ const vx = Math.abs(pe.clientX - lastX) / dt;
393
+ const doCommit = !isCancel && (t >= SWIPE_COMMIT_RATIO || vx >= SWIPE_FLICK_PX_MS);
394
+ const p = prev, tp = top;
395
+ prev = null; top = null;
396
+
397
+ const done = () => {
398
+ p.style.transform = "";
399
+ if (doCommit) {
400
+ // top muere por delete-node al commitear — limpiar su
401
+ // transform aquí la haría reaparecer un frame a x=0.
402
+ hooks.commit();
403
+ } else {
404
+ tp.style.transform = "";
405
+ hooks.cancel();
406
+ }
407
+ };
408
+ if (typeof tp.animate === "function") {
409
+ const rest = doCommit ? w : 0;
410
+ const a = tp.animate(
411
+ [{ transform: `translateX(${dx}px)` }, { transform: `translateX(${rest}px)` }],
412
+ { duration: 180, easing: "ease-out" },
413
+ );
414
+ p.animate(
415
+ [{ transform: p.style.transform }, { transform: doCommit ? "translateX(0%)" : "translateX(-30%)" }],
416
+ { duration: 180, easing: "ease-out" },
417
+ );
418
+ a.finished.catch(() => { }).then(done);
419
+ } else {
420
+ done();
421
+ }
422
+ };
423
+ shell.addEventListener("pointerup", (e) => finish(e, false));
424
+ shell.addEventListener("pointercancel", (e) => finish(e, true));
425
+ }
426
+
427
+ /** Aplica la transición de una op nav-* a la pantalla entrante
428
+ * (último hijo del shell) y, si el frame detachó la saliente, parallax
429
+ * de dos pantallas (ADR-0013): el saliente se re-inserta como overlay
430
+ * absoluto, se desplaza y se retira al terminar. kind:"none" → no-op. */
431
+ export function applyNavTransition(
432
+ op: { op: string; shellId: string; transition?: TransitionSpec },
433
+ elementMap: Map<number, HTMLElement>,
434
+ ): void {
435
+ if (op.transition?.kind === "none") return;
436
+ const shellEl = [...elementMap.values()].find(
437
+ (e) => e.getAttribute("data-elur-type") === "shell",
438
+ );
439
+ const screen = shellEl?.lastElementChild as HTMLElement | null;
440
+ if (!shellEl || !screen || typeof screen.animate !== "function") return;
441
+ if (op.transition?.kind === "custom") {
442
+ const fn = customTransitions.get(op.transition.name);
443
+ if (fn) { fn(screen, op.op, op.transition.duration); return; }
444
+ // ADR-0165: descriptor declarativo adjunto por el screen-host.
445
+ if (op.transition.def) {
446
+ applyDefTransition(op, screen, shellEl);
447
+ return;
448
+ }
449
+ }
450
+ const dur = op.transition?.kind === "custom"
451
+ ? (op.transition.duration ?? 250)
452
+ : 250;
453
+ const easing = "cubic-bezier(.32,.72,0,1)";
454
+
455
+ // Saliente: consumir el detach de este frame (puede no existir —
456
+ // p.ej. primera pantalla). Re-insert como overlay: position absolute
457
+ // + inset 0 la pone encima de la entrante sin tocar layout.
458
+ const outgoing = detachedScreens.get(shellEl);
459
+ detachedScreens.delete(shellEl);
460
+ const canParallax = outgoing && outgoing.parentNode === null && outgoing !== screen;
461
+
462
+ if (op.op === "nav-push") {
463
+ // La entrante va ENCIMA (lectura iOS del push): sin position ni
464
+ // zIndex el overlay absoluto del saliente la taparía aunque
465
+ // venga antes en DOM — ese era el "salto" de la transición.
466
+ screen.style.position = "relative";
467
+ screen.style.zIndex = "2";
468
+ const anim = screen.animate(
469
+ [{ transform: "translateX(100%)", opacity: 0.98 }, { transform: "translateX(0)", opacity: 1 }],
470
+ { duration: dur, easing },
471
+ );
472
+ Promise.resolve(anim?.finished).catch(() => { }).then(() => {
473
+ anim?.cancel();
474
+ screen.style.position = "";
475
+ screen.style.zIndex = "";
476
+ });
477
+ if (canParallax) {
478
+ slideOutgoing(shellEl, outgoing, "-30%", dur, easing, "0");
479
+ }
480
+ } else if (op.op === "nav-pop") {
481
+ // La entrante (debajo) se revela desde la izquierda; la saliente
482
+ // (overlay encima) sale por la derecha — lectura iOS del gesto back.
483
+ screen.animate(
484
+ [{ transform: "translateX(-30%)" }, { transform: "translateX(0)" }],
485
+ { duration: dur, easing },
486
+ );
487
+ if (canParallax) {
488
+ slideOutgoing(shellEl, outgoing, "100%", dur, easing, "2");
489
+ }
490
+ } else {
491
+ screen.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 180 });
492
+ }
493
+ }
494
+
495
+ // ADR-0165 — descriptor declarativo → keyframes WAAPI. Props cerradas
496
+ // {x,y,scale,opacity}; x/y numéricos son px, "±N%" pasa literal a CSS
497
+ // (el % de translate es del propio elemento — las pantallas ocupan el
498
+ // shell completo, coincide con el % del shell del contrato).
499
+ function navKf(p: TransitionProps | undefined): Keyframe {
500
+ const kf: Keyframe = {};
501
+ const tf: string[] = [];
502
+ if (p) {
503
+ if (p.x !== undefined)
504
+ tf.push(`translateX(${typeof p.x === "number" ? `${p.x}px` : p.x})`);
505
+ if (p.y !== undefined)
506
+ tf.push(`translateY(${typeof p.y === "number" ? `${p.y}px` : p.y})`);
507
+ if (p.scale !== undefined) tf.push(`scale(${p.scale})`);
508
+ if (p.opacity !== undefined) kf.opacity = String(p.opacity);
509
+ }
510
+ if (tf.length) kf.transform = tf.join(" ");
511
+ return kf;
512
+ }
513
+
514
+ function navEasingCss(e: string | undefined): string {
515
+ // spring ≈ sobreimpulso suave — aproximación documentada (ADR-0165);
516
+ // el resto pasa literal (nombres WAAPI + cubic-bezier(a,b,c,d)).
517
+ if (e === "spring") return "cubic-bezier(.34,1.56,.64,1)";
518
+ return e ?? "cubic-bezier(.32,.72,0,1)";
519
+ }
520
+
521
+ /** Transición declarativa (ADR-0165): incoming se anima sobre `screen`;
522
+ * outgoing re-inserta como overlay con sus keyframes. Capas ausentes
523
+ * del def quedan quietas (la saliente se consume pero no se anima). */
524
+ function applyDefTransition(
525
+ op: { op: string; transition?: TransitionSpec },
526
+ screen: HTMLElement,
527
+ shellEl: HTMLElement,
528
+ ): void {
529
+ const def = op.transition?.kind === "custom" ? op.transition.def : undefined;
530
+ if (!def) return;
531
+ // spec.duration (hint por-navegación) gana al default del def.
532
+ const dur = op.transition?.kind === "custom" && op.transition.duration !== undefined
533
+ ? op.transition.duration
534
+ : (def.duration ?? 250);
535
+ const easing = navEasingCss(def.easing);
536
+ const outgoing = detachedScreens.get(shellEl);
537
+ detachedScreens.delete(shellEl);
538
+ const canParallax = !!outgoing && outgoing.parentNode === null && outgoing !== screen;
539
+ if (def.incoming) {
540
+ if (op.op !== "nav-pop") {
541
+ screen.style.position = "relative";
542
+ screen.style.zIndex = "2";
543
+ }
544
+ const anim = screen.animate(
545
+ [navKf(def.incoming.from), navKf(def.incoming.to)],
546
+ { duration: dur, easing },
547
+ );
548
+ Promise.resolve(anim?.finished).catch(() => { }).then(() => {
549
+ anim?.cancel();
550
+ screen.style.position = "";
551
+ screen.style.zIndex = "";
552
+ });
553
+ }
554
+ if (def.outgoing && canParallax && outgoing) {
555
+ shellEl.appendChild(outgoing);
556
+ outgoing.style.position = "absolute";
557
+ outgoing.style.inset = "0";
558
+ outgoing.style.zIndex = op.op === "nav-pop" ? "2" : "0";
559
+ outgoing.style.pointerEvents = "none";
560
+ const anim = outgoing.animate(
561
+ [navKf(def.outgoing.from), navKf(def.outgoing.to)],
562
+ { duration: dur, easing },
563
+ );
564
+ anim.finished.catch(() => { }).then(() => {
565
+ anim.cancel();
566
+ outgoing.remove();
567
+ outgoing.style.position = "";
568
+ outgoing.style.inset = "";
569
+ outgoing.style.zIndex = "";
570
+ outgoing.style.pointerEvents = "";
571
+ outgoing.style.transform = "";
572
+ outgoing.style.opacity = "";
573
+ });
574
+ }
575
+ }
576
+
577
+ /** Overlay temporal del saliente durante la transición: absolute +
578
+ * translateX hacia `to`; al terminar se retira del DOM y se restauran
579
+ * los estilos inline (el nodo sigue vivo en elementMap para reattach). */
580
+ function slideOutgoing(
581
+ shellEl: HTMLElement,
582
+ outgoing: HTMLElement,
583
+ to: string,
584
+ dur: number,
585
+ easing: string,
586
+ z: string,
587
+ ): void {
588
+ shellEl.appendChild(outgoing);
589
+ outgoing.style.position = "absolute";
590
+ outgoing.style.inset = "0";
591
+ outgoing.style.zIndex = z;
592
+ outgoing.style.pointerEvents = "none";
593
+ // Sin fill:forwards — el fill persistiría sobre el elemento incluso
594
+ // tras limpiar style.transform, y al re-attachar esta pantalla
595
+ // quedaría corrida (bug: pop dejaba la entrante a -30%). La limpieza
596
+ // corre en el mismo microtask que finished → sin flash visual.
597
+ const anim = outgoing.animate(
598
+ [{ transform: "translateX(0)" }, { transform: `translateX(${to})` }],
599
+ { duration: dur, easing },
600
+ );
601
+ anim.finished.catch(() => { }).then(() => {
602
+ anim.cancel(); // libera el efecto de animación sobre el elemento
603
+ outgoing.remove();
604
+ outgoing.style.position = "";
605
+ outgoing.style.inset = "";
606
+ outgoing.style.zIndex = "";
607
+ outgoing.style.pointerEvents = "";
608
+ outgoing.style.transform = "";
609
+ });
610
+ }
611
+
612
+ function mapEvent(event: string): string {
613
+ // Vocabulario universal (Capa 0) → evento DOM real (Capa 4 web)
614
+ const map: Record<string, string> = {
615
+ press: "click",
616
+ hover: "mouseenter",
617
+ focus: "focus",
618
+ blur: "blur",
619
+ input: "input",
620
+ contextMenu: "contextmenu",
621
+ select: "select",
622
+ key: "keydown", // ADR-0159 — tecla física
623
+ contextmenu: "contextmenu", // alias en minúsculas (ADR-0159)
624
+ // ADR-0152: acción a11y — sin evento DOM nativo; CustomEvent
625
+ // `elur:action` (detail.action = id) es el canal programático.
626
+ action: "elur:action",
627
+ endReached: "elur:endreached",
628
+ };
629
+ return map[event] ?? event;
630
+ }
631
+
632
+ function attachRefresh(el: HTMLElement, emit: (d: object) => void): () => void {
633
+ let startY: number | null = null;
634
+ let armed = false;
635
+ const onTouchStart = (ev: TouchEvent) => {
636
+ if (el.scrollTop <= 0 && ev.touches.length === 1) {
637
+ startY = ev.touches[0].clientY;
638
+ armed = false;
639
+ } else {
640
+ startY = null;
641
+ armed = false;
642
+ }
643
+ };
644
+ const onTouchMove = (ev: TouchEvent) => {
645
+ if (startY === null || ev.touches.length !== 1) return;
646
+ if (el.scrollTop > 0) {
647
+ startY = null;
648
+ armed = false;
649
+ return;
650
+ }
651
+ const dy = ev.touches[0].clientY - startY;
652
+ armed = dy >= 56;
653
+ };
654
+ const onTouchEnd = () => {
655
+ if (armed) emit({});
656
+ startY = null;
657
+ armed = false;
658
+ };
659
+ const onCustom = () => emit({});
660
+ el.addEventListener("touchstart", onTouchStart, { passive: true });
661
+ el.addEventListener("touchmove", onTouchMove, { passive: true });
662
+ el.addEventListener("touchend", onTouchEnd);
663
+ el.addEventListener("touchcancel", onTouchEnd);
664
+ el.addEventListener("elur:refresh", onCustom);
665
+ return () => {
666
+ el.removeEventListener("touchstart", onTouchStart);
667
+ el.removeEventListener("touchmove", onTouchMove);
668
+ el.removeEventListener("touchend", onTouchEnd);
669
+ el.removeEventListener("touchcancel", onTouchEnd);
670
+ el.removeEventListener("elur:refresh", onCustom);
671
+ };
672
+ }
673
+
674
+ // ADR-0109 — guarda de composición IME por elemento (web). El protocolo
675
+ // (textInputProtocol.ts) decide deferral; aquí se materializa: listeners
676
+ // composition* mantienen el estado y drenan la escritura programática
677
+ // diferida al `end`. `__elurComp` marca hooks ya instalados.
678
+ interface WebComp {
679
+ proto: TextInputProtocol;
680
+ /** Handler de app si el evento `composition` está attachado. */
681
+ handler?: (phase: "start" | "update" | "end", text: string) => void;
682
+ }
683
+
684
+ function ensureComp(el: HTMLElement): WebComp {
685
+ let c = (el as any).__elurComp as WebComp | undefined;
686
+ if (c) return c;
687
+ const proto = createTextInputProtocol();
688
+ const comp: WebComp = { proto };
689
+ const fire = (phase: "start" | "update" | "end", e: Event) => {
690
+ const pending = proto.onPhase(phase, (e as CompositionEvent).data ?? "");
691
+ comp.handler?.(phase, (e as CompositionEvent).data ?? "");
692
+ if (pending !== undefined) {
693
+ // Escritura programática diferida — aplica tras el commit.
694
+ const input = el as HTMLInputElement;
695
+ input.value = pending;
696
+ const sel = (el as any).__elurCompSel as
697
+ | { start?: number; end?: number } | undefined;
698
+ if (sel && typeof sel.start === "number") {
699
+ input.setSelectionRange(sel.start, sel.end ?? sel.start);
700
+ }
701
+ (el as any).__elurCompSel = undefined;
702
+ }
703
+ };
704
+ el.addEventListener("compositionstart", (e) => fire("start", e));
705
+ el.addEventListener("compositionupdate", (e) => fire("update", e));
706
+ el.addEventListener("compositionend", (e) => fire("end", e));
707
+ (el as any).__elurComp = comp;
708
+ return comp;
709
+ }
710
+
711
+ /**
712
+ * ADR-0204 — estado de carga/fallback de un <img>. El listener de
713
+ * error interno corre en captura: decide si el fallback va a intentar
714
+ * recuperar la imagen ANTES de que el listener de app (burbuja) vea el
715
+ * evento. Así `error` solo se despacha si no hay fallback o si el
716
+ * fallback también falló.
717
+ */
718
+ interface WebImageState {
719
+ primary: string;
720
+ fallback: string | null;
721
+ usingFallback: boolean;
722
+ suppressError: boolean;
723
+ }
724
+
725
+ function imageState(el: HTMLImageElement): WebImageState {
726
+ const tagged = el as unknown as { __elurImage?: WebImageState };
727
+ if (tagged.__elurImage) return tagged.__elurImage;
728
+ const st: WebImageState = {
729
+ primary: el.getAttribute("src") ?? "",
730
+ fallback: null,
731
+ usingFallback: false,
732
+ suppressError: false,
733
+ };
734
+ tagged.__elurImage = st;
735
+ // Captura: el fallback reacciona antes del listener de app.
736
+ el.addEventListener("error", () => {
737
+ if (!st.fallback || st.usingFallback ||
738
+ st.fallback === el.getAttribute("src")) {
739
+ st.suppressError = false;
740
+ return;
741
+ }
742
+ st.suppressError = true;
743
+ st.usingFallback = true;
744
+ el.src = st.fallback;
745
+ }, true);
746
+ el.addEventListener("load", () => {
747
+ // La carga (primaria o fallback) cierra el error pendiente.
748
+ st.suppressError = false;
749
+ }, true);
750
+ return st;
751
+ }
752
+
753
+ /** `src` nuevo: re-arma el fallback (un fallback usado no sobrevive a
754
+ * un cambio de recurso). */
755
+ function setImageSrc(el: HTMLImageElement, src: string): void {
756
+ const st = imageState(el);
757
+ st.primary = src;
758
+ st.usingFallback = false;
759
+ st.suppressError = false;
760
+ if (!src) {
761
+ // Retirar src no debe pedir la URL del documento como imagen.
762
+ el.removeAttribute("src");
763
+ return;
764
+ }
765
+ if (el.getAttribute("src") !== src) el.src = src;
766
+ }
767
+
768
+ /** `fallbackSrc`: si la imagen ya está mostrando el fallback anterior,
769
+ * vuelve a intentar el primario con el fallback nuevo. */
770
+ function setImageFallback(el: HTMLImageElement, fallback: string | null): void {
771
+ const st = imageState(el);
772
+ st.fallback = fallback || null;
773
+ st.usingFallback = false;
774
+ st.suppressError = false;
775
+ if (st.primary && el.getAttribute("src") !== st.primary) {
776
+ el.src = st.primary;
777
+ }
778
+ }
779
+
780
+ /** ADR-0047 — extrae el payload tipado del DOM hacia el envelope.
781
+ * `el` es la fuente de verdad (el Event puede faltar en el reporte
782
+ * inicial de scroll). */
783
+ function pickEventData(
784
+ event: string,
785
+ el: HTMLElement,
786
+ e?: Event,
787
+ ): EventDataMap[EventName] {
788
+ const input = el as HTMLInputElement;
789
+ switch (event) {
790
+ case "scroll":
791
+ return {
792
+ y: el.scrollTop,
793
+ x: el.scrollLeft,
794
+ vh: el.clientHeight,
795
+ vw: el.clientWidth,
796
+ ch: el.scrollHeight,
797
+ cw: el.scrollWidth,
798
+ };
799
+ case "input":
800
+ return {
801
+ text: input.value ?? "",
802
+ // Slider (type=range) reporta además progress numérico —
803
+ // misma clave que el SeekBar de Android.
804
+ ...(input.type === "range"
805
+ ? { progress: Number(input.value) }
806
+ : {}),
807
+ // Composición IME en curso — el dato es provisional.
808
+ composing: (e as InputEvent | undefined)?.isComposing ?? false,
809
+ };
810
+ case "change":
811
+ return { checked: input.checked === true };
812
+ case "select":
813
+ return {
814
+ start: input.selectionStart ?? 0,
815
+ end: input.selectionEnd ?? 0,
816
+ };
817
+ case "pointer": {
818
+ // ADR-0159 — fase por tipo DOM; offsetX/Y = relativas al
819
+ // nodo (padding edge — misma referencia que las coords del
820
+ // gestor en hosts nativos).
821
+ const pe = e as PointerEvent | undefined;
822
+ const phase =
823
+ pe?.type === "pointerenter" ? "enter" :
824
+ pe?.type === "pointerleave" ? "leave" : "move";
825
+ return { phase, x: pe?.offsetX ?? 0, y: pe?.offsetY ?? 0 };
826
+ }
827
+ case "contextMenu":
828
+ case "contextmenu": {
829
+ const me = e as MouseEvent | undefined;
830
+ return { x: me?.offsetX ?? 0, y: me?.offsetY ?? 0 };
831
+ }
832
+ case "key": {
833
+ const ke = e as KeyboardEvent | undefined;
834
+ const d: Record<string, unknown> = { key: ke?.key ?? "" };
835
+ if (ke?.ctrlKey) d.ctrl = true;
836
+ if (ke?.altKey) d.alt = true;
837
+ if (ke?.shiftKey) d.shift = true;
838
+ if (ke?.metaKey) d.meta = true;
839
+ return d;
840
+ }
841
+ case "action":
842
+ // ADR-0152: CustomEvent `elur:action` — detail.action = id
843
+ // declarado en la clave semántica `actions`.
844
+ return {
845
+ action: String((e as CustomEvent | undefined)?.detail?.action ?? ""),
846
+ };
847
+ // ADR-0204 — carga de imagen (solo tiene sentido sobre <img>).
848
+ case "load": {
849
+ if (!(el instanceof HTMLImageElement)) return {};
850
+ const st = imageState(el);
851
+ return {
852
+ width: el.naturalWidth || undefined,
853
+ height: el.naturalHeight || undefined,
854
+ ...(st.usingFallback ? { fallback: true } : {}),
855
+ };
856
+ }
857
+ case "error": {
858
+ if (!(el instanceof HTMLImageElement)) return {};
859
+ const st = imageState(el);
860
+ return {
861
+ message: "image load failed",
862
+ ...(st.usingFallback ? { fallback: true } : {}),
863
+ };
864
+ }
865
+ default:
866
+ return {};
867
+ }
868
+ }
869
+
870
+ // Shell kind=tabs → <nav> con un <button> por tab (semántico).
871
+ // Tab click → handlers["__elur_tab:<id>"] (ScreenHost lo registra → setTab).
872
+ /** Materialización del shell tabs (V09 — ÚNICA para mount e hydrate):
873
+ * adopta el `<nav data-elur-tabbar>` servido por SSR si existe (sin
874
+ * duplicar), si no lo crea; en ambos casos enlaza los handlers. */
875
+ function materializeShell(
876
+ el: HTMLElement,
877
+ def: { kind?: string; chrome?: string; tabs?: Array<{ id: string; label: string }> },
878
+ handlers: Record<string, (e?: unknown) => void>,
879
+ ) {
880
+ if (def.kind !== "tabs" || !def.tabs || def.chrome === "none") return;
881
+ el.style.display = "flex";
882
+ el.style.flexDirection = "column";
883
+ el.style.minHeight = "100vh"; // margin-top:auto empuja el nav al fondo
884
+
885
+ let nav = el.querySelector<HTMLElement>("[data-elur-tabbar]");
886
+ if (!nav) {
887
+ nav = document.createElement("nav");
888
+ nav.setAttribute("data-elur-tabbar", "");
889
+ Object.assign(nav.style, {
890
+ display: "flex", flexDirection: "row", gap: "8px",
891
+ order: "1", marginTop: "auto", padding: "8px",
892
+ borderTop: "1px solid #ddd",
893
+ });
894
+ for (const tab of def.tabs) {
895
+ const btn = document.createElement("button");
896
+ btn.textContent = tab.label;
897
+ btn.setAttribute("data-elur-tab", tab.id);
898
+ nav.appendChild(btn);
899
+ }
900
+ el.appendChild(nav);
901
+ }
902
+ for (const tab of def.tabs) {
903
+ const btn = nav.querySelector(`[data-elur-tab="${tab.id}"]`);
904
+ const h = handlers[`__elur_tab:${tab.id}`];
905
+ if (btn && h) btn.addEventListener("click", h);
906
+ }
907
+ }
908
+
909
+ /** Replay del draw-list de `canvas` (ADR-0020): cada comando lleva su
910
+ * pintura; sin estado ambiente. getContext puede devolver null (jsdom
911
+ * sin node-canvas) — entonces se omite el replay sin error. */
912
+ /**
913
+ * Spec de animación declarativa (ADR-0023) — prop `animate`, JSON-
914
+ * serializable (cruza el wire como changedProps, sin cambiar el ABI).
915
+ * Keyframes estilo WAAPI; `iterations: -1` = infinito (JSON no lleva
916
+ * Infinity). El spec bound a un signal re-emite update-props → replay.
917
+ */
918
+ export type AnimationSpec = {
919
+ keyframes: Array<Record<string, string | number>>;
920
+ duration?: number;
921
+ delay?: number;
922
+ easing?: string;
923
+ iterations?: number | "infinite";
924
+ fill?: "none" | "forwards" | "backwards" | "both";
925
+ direction?: "normal" | "reverse" | "alternate" | "alternate-reverse";
926
+ };
927
+
928
+ function resolveIterations(it: number | "infinite" | undefined): number {
929
+ if (it === -1 || it === "infinite") return Infinity;
930
+ return it ?? 1;
931
+ }
932
+
933
+ /** Reproduce un AnimationSpec sobre el elemento vía WAAPI. Sin WAAPI →
934
+ * no-op. Una animación previa del mismo elemento se cancela (replay
935
+ * reactivo: el último spec gana). */
936
+ export function playAnimation(el: HTMLElement, spec: unknown): void {
937
+ if (typeof el.animate !== "function") return;
938
+ const s = spec as AnimationSpec | null | undefined;
939
+ if (!s || !Array.isArray(s.keyframes) || s.keyframes.length === 0) return;
940
+ if (typeof el.getAnimations === "function") {
941
+ for (const a of el.getAnimations()) a.cancel();
942
+ }
943
+ el.animate(s.keyframes as Keyframe[], {
944
+ duration: s.duration ?? 300,
945
+ delay: s.delay ?? 0,
946
+ easing: s.easing ?? "ease",
947
+ iterations: resolveIterations(s.iterations),
948
+ fill: s.fill ?? "none",
949
+ direction: s.direction ?? "normal",
950
+ });
951
+ }
952
+
953
+ /** Ejecuta la exit animation (ADR-0023): spec + fill:forwards forzado
954
+ * — el elemento desaparece visualmente al final y se remueve vía
955
+ * `finished` en el llamador. Devuelve la Animation o null si el spec
956
+ * es inválido/no hay WAAPI. */
957
+ export function playExitAnimation(el: HTMLElement, spec: unknown): Animation | null {
958
+ if (typeof el.animate !== "function") return null;
959
+ const s = spec as AnimationSpec | null | undefined;
960
+ if (!s || !Array.isArray(s.keyframes) || s.keyframes.length === 0) return null;
961
+ if (typeof el.getAnimations === "function") {
962
+ for (const a of el.getAnimations()) a.cancel();
963
+ }
964
+ return el.animate(s.keyframes as Keyframe[], {
965
+ duration: s.duration ?? 200,
966
+ delay: s.delay ?? 0,
967
+ easing: s.easing ?? "ease",
968
+ iterations: resolveIterations(s.iterations),
969
+ fill: "forwards", // exit siempre retiene el frame final
970
+ direction: s.direction ?? "normal",
971
+ });
972
+ }
973
+
974
+ export function replayCanvas(canvas: HTMLCanvasElement, cmds: unknown): void {
975
+ if (!Array.isArray(cmds)) return;
976
+ const ctx = canvas.getContext("2d");
977
+ if (!ctx) return;
978
+ for (const raw of cmds) {
979
+ const c = raw as import("../../ir/schema").CanvasCmd;
980
+ switch (c.op) {
981
+ case "clear": {
982
+ if (c.color) {
983
+ ctx.save();
984
+ ctx.fillStyle = c.color;
985
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
986
+ ctx.restore();
987
+ } else {
988
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
989
+ }
990
+ break;
991
+ }
992
+ case "rect": {
993
+ if (c.fill) {
994
+ ctx.fillStyle = c.fill;
995
+ if (c.radius && "roundRect" in ctx) {
996
+ ctx.beginPath();
997
+ (ctx as CanvasRenderingContext2D & { roundRect: (x: number, y: number, w: number, h: number, r: number) => void }).roundRect(c.x, c.y, c.w, c.h, c.radius);
998
+ ctx.fill();
999
+ } else {
1000
+ ctx.fillRect(c.x, c.y, c.w, c.h);
1001
+ }
1002
+ }
1003
+ if (c.stroke) {
1004
+ ctx.strokeStyle = c.stroke;
1005
+ ctx.lineWidth = c.lineWidth ?? 1;
1006
+ ctx.strokeRect(c.x, c.y, c.w, c.h);
1007
+ }
1008
+ break;
1009
+ }
1010
+ case "circle": {
1011
+ ctx.beginPath();
1012
+ ctx.arc(c.x, c.y, c.r, 0, Math.PI * 2);
1013
+ if (c.fill) { ctx.fillStyle = c.fill; ctx.fill(); }
1014
+ if (c.stroke) {
1015
+ ctx.strokeStyle = c.stroke;
1016
+ ctx.lineWidth = c.lineWidth ?? 1;
1017
+ ctx.stroke();
1018
+ }
1019
+ break;
1020
+ }
1021
+ case "arc": {
1022
+ ctx.beginPath();
1023
+ ctx.arc(
1024
+ c.x,
1025
+ c.y,
1026
+ c.r,
1027
+ (c.startAngle * Math.PI) / 180,
1028
+ (c.endAngle * Math.PI) / 180,
1029
+ Boolean(c.counterclockwise),
1030
+ );
1031
+ if (c.fill) { ctx.fillStyle = c.fill; ctx.fill(); }
1032
+ if (c.stroke) {
1033
+ ctx.strokeStyle = c.stroke;
1034
+ ctx.lineWidth = c.lineWidth ?? 1;
1035
+ ctx.stroke();
1036
+ }
1037
+ break;
1038
+ }
1039
+ case "line": {
1040
+ ctx.beginPath();
1041
+ ctx.moveTo(c.x1, c.y1);
1042
+ ctx.lineTo(c.x2, c.y2);
1043
+ ctx.strokeStyle = c.stroke ?? "#000";
1044
+ ctx.lineWidth = c.lineWidth ?? 1;
1045
+ ctx.stroke();
1046
+ break;
1047
+ }
1048
+ case "path":
1049
+ case "svgPath": {
1050
+ const p = new Path2D(c.d);
1051
+ if (c.fill) { ctx.fillStyle = c.fill; ctx.fill(p); }
1052
+ if (c.stroke) {
1053
+ ctx.strokeStyle = c.stroke;
1054
+ ctx.lineWidth = c.lineWidth ?? 1;
1055
+ ctx.stroke(p);
1056
+ }
1057
+ break;
1058
+ }
1059
+ case "text": {
1060
+ ctx.fillStyle = c.color ?? "#000";
1061
+ ctx.font = `${c.size ?? 14}px ${c.font ?? "sans-serif"}`;
1062
+ ctx.textAlign = c.align ?? "left";
1063
+ ctx.fillText(c.text, c.x, c.y);
1064
+ break;
1065
+ }
1066
+ case "save": ctx.save(); break;
1067
+ case "restore": ctx.restore(); break;
1068
+ case "translate": ctx.translate(c.x, c.y); break;
1069
+ case "rotate": ctx.rotate((c.deg * Math.PI) / 180); break;
1070
+ case "scale": ctx.scale(c.x, c.y ?? c.x); break;
1071
+ }
1072
+ }
1073
+ }
1074
+
1075
+ const TRANSFORM_KEYS = TRANSFORM_STYLE_KEYS;
1076
+
1077
+ /**
1078
+ * ADR-0038 — update-style llega por clave, pero CSS transform es una
1079
+ * propiedad única: el elemento conserva las partes por clave
1080
+ * (`__elurTransform`) y se recompone con la regla compartida
1081
+ * `composeTransformCss` (misma que el aplicador SSR — V09).
1082
+ * `null`/`undefined` retira la parte.
1083
+ */
1084
+ export function applyTransformKey(
1085
+ el: HTMLElement, key: string, value: unknown,
1086
+ ): void {
1087
+ const anyEl = el as HTMLElement & {
1088
+ __elurTransform?: Record<string, unknown>;
1089
+ };
1090
+ const t = (anyEl.__elurTransform ??= {});
1091
+ if (value == null) delete t[key];
1092
+ else t[key] = value;
1093
+ el.style.transform = composeTransformCss(t);
1094
+ }
1095
+
1096
+ export function isTransformKey(key: string): boolean {
1097
+ return TRANSFORM_KEYS.has(key);
1098
+ }
1099
+
1100
+ function applyStyle(el: HTMLElement, style: Style): void {
1101
+ for (const [key, value] of Object.entries(style)) {
1102
+ // Transform keys llegan aunque value sea null — retira la parte
1103
+ // (ADR-0038). El resto de claves null se ignoran como siempre.
1104
+ if (TRANSFORM_KEYS.has(key)) {
1105
+ applyTransformKey(el, key, value);
1106
+ continue;
1107
+ }
1108
+ if (key === "backgroundGradient") {
1109
+ el.style.backgroundImage = value == null ? "" : String(value);
1110
+ continue;
1111
+ }
1112
+ if (value == null) continue;
1113
+ if (typeof value === "number" && !UNITLESS_CSS.has(key)) {
1114
+ (el.style as any)[key] = `${value}px`;
1115
+ } else {
1116
+ (el.style as any)[key] = value;
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * ADR-0147 — `spans`: texto enriquecido inline. El elemento guarda el
1123
+ * texto fuente (`__elurText`, set por update-text) y los rangos
1124
+ * (`__elurSpans`, prop); cualquier cambio de uno re-materializa el
1125
+ * contenido — update-text con spans activos no puede usar el guard de
1126
+ * igualdad de textContent (los elementos internos hay que rehacerlos).
1127
+ * El click delegado resuelve `href` interno por `__elur_span_href`
1128
+ * (registrado por ui`` finalizeNode → linkNavigator); los externos
1129
+ * navegan nativos por el <a> (mismo split que el href de nodo).
1130
+ */
1131
+ type SpanCarrier = HTMLElement & {
1132
+ __elurText?: string;
1133
+ __elurSpans?: unknown;
1134
+ __elurSpanNav?: boolean;
1135
+ };
1136
+
1137
+ function spanFrag(doc: Document, text: string, node: TextSpanNode): DocumentFragment {
1138
+ const frag = doc.createDocumentFragment();
1139
+ let cur = node.start;
1140
+ for (const c of node.children) {
1141
+ if (c.start > cur) {
1142
+ frag.appendChild(doc.createTextNode(text.slice(cur, c.start)));
1143
+ }
1144
+ const se = c.href ? doc.createElement("a") : doc.createElement("span");
1145
+ if (c.href) {
1146
+ se.setAttribute("href", c.href);
1147
+ se.setAttribute("data-elur-href", "");
1148
+ }
1149
+ if (c.style) applyStyle(se as HTMLElement, c.style as Style);
1150
+ se.appendChild(spanFrag(doc, text, c));
1151
+ frag.appendChild(se);
1152
+ cur = c.end;
1153
+ }
1154
+ if (node.end > cur) {
1155
+ frag.appendChild(doc.createTextNode(text.slice(cur, node.end)));
1156
+ }
1157
+ return frag;
1158
+ }
1159
+
1160
+ function treeHasHref(node: TextSpanNode): boolean {
1161
+ return node.href !== undefined || node.children.some(treeHasHref);
1162
+ }
1163
+
1164
+ function renderSpans(
1165
+ el: HTMLElement,
1166
+ handlers: Record<string, (e?: unknown) => void>,
1167
+ ): void {
1168
+ const host = el as SpanCarrier;
1169
+ if (el.getAttribute("data-elur-type") !== "text") {
1170
+ host.__elurSpans = null;
1171
+ return;
1172
+ }
1173
+ const text = host.__elurText ?? el.textContent ?? "";
1174
+ const spans = validateTextSpans(host.__elurSpans);
1175
+ if (!spans || !spans.length) {
1176
+ host.__elurSpans = null;
1177
+ if (el.textContent !== text) el.textContent = text;
1178
+ return;
1179
+ }
1180
+ host.__elurSpans = spans;
1181
+ const root = spanTree(text, spans);
1182
+ el.replaceChildren(spanFrag(el.ownerDocument, text, root));
1183
+ if (treeHasHref(root) && !host.__elurSpanNav) {
1184
+ host.__elurSpanNav = true;
1185
+ el.addEventListener("click", (e) => {
1186
+ const me = e as MouseEvent;
1187
+ const target = me.target as Element | null;
1188
+ const a = target?.closest?.("a[data-elur-href]") ??
1189
+ target?.parentElement?.closest?.("a[data-elur-href]");
1190
+ if (!a || !el.contains(a)) return;
1191
+ const href = a.getAttribute("href") ?? "";
1192
+ const internal = /^\/(?!\/)/.test(href) || href.charAt(0) === "?";
1193
+ if (internal && me.button === 0 && !me.metaKey && !me.ctrlKey &&
1194
+ !me.shiftKey && !me.altKey) {
1195
+ me.preventDefault();
1196
+ handlers["__elur_span_href"]?.(href);
1197
+ }
1198
+ });
1199
+ }
1200
+ }
1201
+
1202
+ // Aplicador de ops — la única lógica específica del backend web
1203
+
1204
+ /** Registro real de listeners por (nodo, evento universal) — R2.2/F13:
1205
+ * detach-event y delete-node deben poder llamar removeEventListener con
1206
+ * la función exacta; sin el registro el listener quedaba vivo. */
1207
+ export type ListenerEntry = {
1208
+ domEvent: string;
1209
+ fn: (e?: unknown) => void;
1210
+ /** Eventos compuestos (gestos, atajos) — retira todo lo que instalaron. */
1211
+ dispose?: () => void;
1212
+ };
1213
+ export type ListenerRegistry = Map<number, Map<string, ListenerEntry>>;
1214
+
1215
+ /** Retirada única de un listener del registro — detach, delete-node y
1216
+ * reset-node pasan por aquí (antes divergían: delete-node dejaba vivas
1217
+ * las tres fases de `pointer`). */
1218
+ function releaseListener(el: HTMLElement, entry: ListenerEntry): void {
1219
+ if (entry.dispose) entry.dispose();
1220
+ else if (entry.domEvent === "composition") entry.fn();
1221
+ else if (entry.domEvent === "pointer") {
1222
+ el.removeEventListener("pointerenter", entry.fn);
1223
+ el.removeEventListener("pointerleave", entry.fn);
1224
+ el.removeEventListener("pointermove", entry.fn);
1225
+ } else el.removeEventListener(entry.domEvent, entry.fn);
1226
+ }
1227
+
1228
+ /** ADR-0179 — umbrales web de longPress/pan. Los hosts nativos usan los
1229
+ * del SO (ViewConfiguration en Android, gestos GTK en Linux). */
1230
+ export const LONG_PRESS_MS = 500;
1231
+ export const GESTURE_SLOP_PX = 8;
1232
+
1233
+ type GestureGuard = { suppress: boolean };
1234
+
1235
+ /** Un longPress disparado o un pan completado consumen el gesto: el
1236
+ * `click` que el navegador sintetiza al soltar no es un `press`. */
1237
+ function gestureGuard(el: HTMLElement): GestureGuard {
1238
+ let g = (el as any).__elurGesture as GestureGuard | undefined;
1239
+ if (g) return g;
1240
+ const guard: GestureGuard = { suppress: false };
1241
+ el.addEventListener("pointerdown", () => { guard.suppress = false; });
1242
+ (el as any).__elurGesture = guard;
1243
+ return guard;
1244
+ }
1245
+
1246
+ function consumeSuppressedClick(el: HTMLElement): boolean {
1247
+ const g = (el as any).__elurGesture as GestureGuard | undefined;
1248
+ if (!g?.suppress) return false;
1249
+ g.suppress = false;
1250
+ return true;
1251
+ }
1252
+
1253
+ function relPoint(el: HTMLElement, e: MouseEvent): { x: number; y: number } {
1254
+ const r = el.getBoundingClientRect();
1255
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
1256
+ }
1257
+
1258
+ function listen(el: EventTarget, pairs: Array<[string, (e: any) => void]>): () => void {
1259
+ for (const [t, f] of pairs) el.addEventListener(t, f);
1260
+ return () => { for (const [t, f] of pairs) el.removeEventListener(t, f); };
1261
+ }
1262
+
1263
+ function attachLongPress(el: HTMLElement, emit: (d: { x: number; y: number }) => void): () => void {
1264
+ const guard = gestureGuard(el);
1265
+ let timer: ReturnType<typeof setTimeout> | undefined;
1266
+ let sx = 0, sy = 0;
1267
+ const clear = () => {
1268
+ if (timer !== undefined) { clearTimeout(timer); timer = undefined; }
1269
+ };
1270
+ const off = listen(el, [
1271
+ ["pointerdown", (e: PointerEvent) => {
1272
+ if (e.button !== 0) return;
1273
+ clear();
1274
+ sx = e.clientX; sy = e.clientY;
1275
+ const at = relPoint(el, e);
1276
+ timer = setTimeout(() => {
1277
+ timer = undefined;
1278
+ guard.suppress = true;
1279
+ emit(at);
1280
+ }, LONG_PRESS_MS);
1281
+ }],
1282
+ ["pointermove", (e: PointerEvent) => {
1283
+ if (timer !== undefined &&
1284
+ Math.hypot(e.clientX - sx, e.clientY - sy) > GESTURE_SLOP_PX) clear();
1285
+ }],
1286
+ ["pointerup", clear], ["pointercancel", clear], ["pointerleave", clear],
1287
+ ]);
1288
+ return () => { clear(); off(); };
1289
+ }
1290
+
1291
+ type PanData = EventDataMap["pan"];
1292
+
1293
+ function attachPan(el: HTMLElement, emit: (d: PanData) => void): () => void {
1294
+ const guard = gestureGuard(el);
1295
+ let g: { id: number; sx: number; sy: number; started: boolean } | null = null;
1296
+ const data = (phase: PanData["phase"], e: PointerEvent): PanData =>
1297
+ ({ phase, ...relPoint(el, e), dx: e.clientX - g!.sx, dy: e.clientY - g!.sy });
1298
+ const finish = (phase: "end" | "cancel") => (e: PointerEvent) => {
1299
+ if (!g || (e.pointerId ?? 0) !== g.id) return;
1300
+ if (g.started) {
1301
+ if (phase === "end") guard.suppress = true;
1302
+ emit(data(phase, e));
1303
+ }
1304
+ g = null;
1305
+ };
1306
+ // Sin esto el navegador táctil se queda el gesto para hacer scroll.
1307
+ const prevTouch = el.style.touchAction;
1308
+ el.style.touchAction = "none";
1309
+ const off = listen(el, [
1310
+ ["pointerdown", (e: PointerEvent) => {
1311
+ if (e.button !== 0) return;
1312
+ g = { id: e.pointerId ?? 0, sx: e.clientX, sy: e.clientY, started: false };
1313
+ }],
1314
+ ["pointermove", (e: PointerEvent) => {
1315
+ if (!g || (e.pointerId ?? 0) !== g.id) return;
1316
+ if (!g.started) {
1317
+ if (Math.hypot(e.clientX - g.sx, e.clientY - g.sy) <= GESTURE_SLOP_PX) return;
1318
+ g.started = true;
1319
+ try { el.setPointerCapture(g.id); } catch { /* sin captura */ }
1320
+ emit(data("start", e));
1321
+ return;
1322
+ }
1323
+ emit(data("move", e));
1324
+ }],
1325
+ ["pointerup", finish("end")], ["pointercancel", finish("cancel")],
1326
+ ]);
1327
+ return () => { off(); el.style.touchAction = prevTouch; };
1328
+ }
1329
+
1330
+ function attachSubmit(el: HTMLElement, emit: (d: { text: string }) => void): () => void {
1331
+ // Textarea: Enter es salto de línea, no acción principal.
1332
+ if (!(el instanceof HTMLInputElement)) return () => { };
1333
+ return listen(el, [["keydown", (e: KeyboardEvent) => {
1334
+ if (e.key !== "Enter" || e.isComposing || e.keyCode === 229) return;
1335
+ emit({ text: el.value });
1336
+ }]]);
1337
+ }
1338
+
1339
+ type ShortcutBind = { combo: string; el: HTMLElement; fire: () => void };
1340
+ const shortcutStacks = new WeakMap<Document, ShortcutBind[]>();
1341
+ const NON_TEXT_INPUTS = new Set(["checkbox", "radio", "range", "button", "submit", "reset", "color", "file"]);
1342
+
1343
+ function isEditing(a: Element | null): boolean {
1344
+ if (!a) return false;
1345
+ if (a instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(a.type);
1346
+ return a.tagName === "TEXTAREA" || (a as HTMLElement).isContentEditable === true;
1347
+ }
1348
+
1349
+ /** ADR-0179 — atajo de ámbito ventana: un keydown por documento, pila
1350
+ * de bindings; gana el último adjuntado cuyo nodo sigue en el DOM. */
1351
+ function attachShortcut(el: HTMLElement, combo: string, fire: () => void): () => void {
1352
+ const doc = el.ownerDocument;
1353
+ let stack = shortcutStacks.get(doc);
1354
+ if (!stack) {
1355
+ const s: ShortcutBind[] = [];
1356
+ stack = s;
1357
+ shortcutStacks.set(doc, s);
1358
+ doc.addEventListener("keydown", (e) => {
1359
+ if (e.repeat || e.isComposing) return;
1360
+ const c = comboOfKey({
1361
+ key: e.key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, meta: e.metaKey,
1362
+ });
1363
+ if (isEditing(doc.activeElement) && !firesWhileEditing(c)) return;
1364
+ for (let i = s.length - 1; i >= 0; i--) {
1365
+ if (s[i].combo === c && s[i].el.isConnected) {
1366
+ e.preventDefault();
1367
+ s[i].fire();
1368
+ return;
1369
+ }
1370
+ }
1371
+ });
1372
+ }
1373
+ const bind: ShortcutBind = { combo, el, fire };
1374
+ stack.push(bind);
1375
+ const s = stack;
1376
+ return () => {
1377
+ const i = s.indexOf(bind);
1378
+ if (i >= 0) s.splice(i, 1);
1379
+ };
1380
+ }
1381
+
1382
+ /** Contexto del aplicador DOM único (V09): mount e hidratación corren el
1383
+ * MISMO switch — `adopt` decide create-vs-adopt en create-node (la
1384
+ * hidratación busca el nodo servido por SSR en `adoptIndex`, construido
1385
+ * una vez — nunca un querySelector por op) y `hydrated` gatea las
1386
+ * animaciones nav-* durante el replay inicial (animar contenido
1387
+ * adoptado sería un flash). Los defaults de create (containing block
1388
+ * relative, input subtypes, content-visibility, scroll marker, shell
1389
+ * height) se aplican igual en ambos modos — son el contrato Yoga. */
1390
+ export type DomApplyCtx = {
1391
+ elementMap: Map<number, HTMLElement>;
1392
+ handlers: Record<string, (e?: unknown) => void>;
1393
+ container: HTMLElement;
1394
+ idMap?: IdMap;
1395
+ listeners?: ListenerRegistry;
1396
+ adopt?: boolean;
1397
+ hydrated?: () => boolean;
1398
+ /** Caches internos — construidos lazy por el aplicador. */
1399
+ _adoptIndex?: Map<number, HTMLElement>;
1400
+ _nameById?: Map<number, string>;
1401
+ };
1402
+
1403
+ export function applyDomOp(op: DisplayOp, ctx: DomApplyCtx): void {
1404
+ const { elementMap, handlers, container, idMap, listeners } = ctx;
1405
+ switch (op.op) {
1406
+ case "create-node": {
1407
+ let el: HTMLElement | undefined;
1408
+ if (ctx.adopt) {
1409
+ // Índice único de data-elur-id (V09) — O(1) por create
1410
+ // en vez de querySelector O(dom) por nodo.
1411
+ if (!ctx._adoptIndex) {
1412
+ ctx._adoptIndex = new Map();
1413
+ for (const found of container.querySelectorAll<HTMLElement>(
1414
+ "[data-elur-id]",
1415
+ )) {
1416
+ const id = Number(found.getAttribute("data-elur-id"));
1417
+ if (!Number.isNaN(id)) ctx._adoptIndex.set(id, found);
1418
+ }
1419
+ }
1420
+ el = ctx._adoptIndex.get(op.id);
1421
+ }
1422
+ if (!el) {
1423
+ el = document.createElement(mapType(op.type));
1424
+ elementMap.set(op.id, el);
1425
+ el.setAttribute("data-elur-id", String(op.id));
1426
+ el.setAttribute("data-elur-type", op.type);
1427
+ // data-elur-name con mapa inverso (V09): el barrido del
1428
+ // idMap se hace UNA vez, no por nodo.
1429
+ if (idMap) {
1430
+ if (!ctx._nameById) {
1431
+ ctx._nameById = new Map();
1432
+ for (const [name, num] of idMap) {
1433
+ ctx._nameById.set(num, name);
1434
+ }
1435
+ }
1436
+ const name = ctx._nameById.get(op.id);
1437
+ if (name) el.setAttribute("data-elur-name", name);
1438
+ }
1439
+ // Subtipos de <input>
1440
+ if (op.type === "switch") {
1441
+ (el as HTMLInputElement).type = "checkbox";
1442
+ el.setAttribute("role", "switch");
1443
+ } else if (op.type === "slider") {
1444
+ (el as HTMLInputElement).type = "range";
1445
+ } else if (op.type === "text-input") {
1446
+ (el as HTMLInputElement).type = "text";
1447
+ }
1448
+ // Containing block por defecto: en Yoga `position:absolute`
1449
+ // ancla al padre; en CSS al ancestro posicionado más
1450
+ // cercano. relative en todo nodo emula la semántica Yoga —
1451
+ // un `position` del style de la app (update-style llega
1452
+ // después) gana.
1453
+ el.style.position = "relative";
1454
+ if (op.type === "column" || op.type === "row") {
1455
+ el.style.display = "flex";
1456
+ el.style.flexDirection = op.type === "row" ? "row" : "column";
1457
+ }
1458
+ // Scroll restoration: scroll-views llevan marcador para
1459
+ // que web-history capture/restaure su posición por entry.
1460
+ if (op.type === "scroll-view") {
1461
+ el.setAttribute("data-elur-scroll", "");
1462
+ el.style.overflow = "auto";
1463
+ }
1464
+ // El shell llena a su padre (en Yoga ocupa el surface
1465
+ // entero) — sin height la cadena #root→shell→screen
1466
+ // colapsa a 0.
1467
+ if (op.type === "shell") {
1468
+ el.style.height = "100%";
1469
+ }
1470
+ } else {
1471
+ elementMap.set(op.id, el); // adoptado del DOM servido
1472
+ }
1473
+ break;
1474
+ }
1475
+ case "update-text": {
1476
+ const el = elementMap.get(op.id);
1477
+ if (!el) break;
1478
+ // ADR-0147: el texto fuente queda para re-materializar spans.
1479
+ (el as SpanCarrier).__elurText = op.value;
1480
+ // Guard de igualdad (V09): reemplazar textContent idéntico
1481
+ // regenera el Text child — mutation + layout innecesarios.
1482
+ // Con spans activos el contenido son elementos — re-render.
1483
+ if ((el as SpanCarrier).__elurSpans) {
1484
+ renderSpans(el, handlers);
1485
+ } else if (el.textContent !== op.value) {
1486
+ el.textContent = op.value;
1487
+ }
1488
+ break;
1489
+ }
1490
+ case "update-style": {
1491
+ const el = elementMap.get(op.id);
1492
+ if (el) applyStyle(el, op.style as any);
1493
+ break;
1494
+ }
1495
+ case "update-semantics": {
1496
+ // ADR-0108: a11y como op dedicada — vocabulario normativo
1497
+ // SEMANTIC_PROPS (src/ir/semantics.ts); null retira la clave.
1498
+ const el = elementMap.get(op.id);
1499
+ if (el) {
1500
+ // focused se aplica al final — un focus() antes de
1501
+ // focusable/tabindex sería no-op en DOM real.
1502
+ let focusIntent: boolean | null = null;
1503
+ for (const [key, value] of Object.entries(op.semantics)) {
1504
+ if (key === "label") {
1505
+ if (value == null) {
1506
+ if (el instanceof HTMLImageElement) el.alt = "";
1507
+ else el.removeAttribute("aria-label");
1508
+ } else if (el instanceof HTMLImageElement) {
1509
+ el.alt = String(value);
1510
+ } else {
1511
+ el.setAttribute("aria-label", String(value));
1512
+ }
1513
+ } else if (key === "accessible") {
1514
+ const off = value === false || value === "false";
1515
+ if (off) el.setAttribute("aria-hidden", "true");
1516
+ else el.removeAttribute("aria-hidden");
1517
+ } else if (key === "role") {
1518
+ if (value == null) el.removeAttribute("role");
1519
+ else el.setAttribute("role", String(value));
1520
+ } else if (key === "live") {
1521
+ const lv = liveRegionValue(value);
1522
+ if (lv) el.setAttribute("aria-live", lv === 2 ? "assertive" : "polite");
1523
+ else el.removeAttribute("aria-live");
1524
+ } else if (key === "checked") {
1525
+ // ADR-0117: input real → propiedad checked (a11y
1526
+ // nativa); resto → aria-checked como estado.
1527
+ // "mixed" (ADR-0152): indeterminate en input.
1528
+ const mixed = value === "mixed";
1529
+ const on = value === true || value === "true";
1530
+ if (el instanceof HTMLInputElement) {
1531
+ el.checked = value == null ? false : on && !mixed;
1532
+ el.indeterminate = mixed;
1533
+ } else if (value == null) {
1534
+ el.removeAttribute("aria-checked");
1535
+ } else {
1536
+ el.setAttribute("aria-checked", mixed ? "mixed" : String(on));
1537
+ }
1538
+ } else if (key === "selected") {
1539
+ if (value == null) el.removeAttribute("aria-selected");
1540
+ else el.setAttribute("aria-selected", String(value === true || value === "true"));
1541
+ } else if (key === "disabled") {
1542
+ const off = value === true || value === "true";
1543
+ if (value == null || !off) {
1544
+ el.removeAttribute("aria-disabled");
1545
+ if ("disabled" in el) (el as any).disabled = false;
1546
+ } else {
1547
+ el.setAttribute("aria-disabled", "true");
1548
+ if ("disabled" in el) (el as any).disabled = true;
1549
+ }
1550
+ } else if (key === "hint") {
1551
+ if (value == null) {
1552
+ el.removeAttribute("aria-placeholder");
1553
+ el.removeAttribute("aria-description");
1554
+ } else if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
1555
+ el.setAttribute("aria-placeholder", String(value));
1556
+ } else {
1557
+ el.setAttribute("aria-description", String(value));
1558
+ }
1559
+ } else if (key === "expanded") {
1560
+ // ADR-0152
1561
+ if (value == null) el.removeAttribute("aria-expanded");
1562
+ else el.setAttribute("aria-expanded", String(value === true || value === "true"));
1563
+ } else if (key === "invalid") {
1564
+ // bool según contrato; tokens ARIA (grammar/
1565
+ // spelling) pasan directos — falsy-safe.
1566
+ if (value == null || value === false || value === "false") {
1567
+ el.removeAttribute("aria-invalid");
1568
+ } else if (value === "grammar" || value === "spelling") {
1569
+ el.setAttribute("aria-invalid", String(value));
1570
+ } else {
1571
+ el.setAttribute("aria-invalid", "true");
1572
+ }
1573
+ } else if (key === "required") {
1574
+ const on = value === true || value === "true";
1575
+ const formEl = el instanceof HTMLInputElement ||
1576
+ el instanceof HTMLTextAreaElement ||
1577
+ el instanceof HTMLSelectElement;
1578
+ if (value == null || !on) {
1579
+ el.removeAttribute("aria-required");
1580
+ if (formEl) el.removeAttribute("required");
1581
+ } else {
1582
+ el.setAttribute("aria-required", "true");
1583
+ if (formEl) el.setAttribute("required", "");
1584
+ }
1585
+ } else if (key === "valueMin" || key === "valueMax" || key === "valueNow") {
1586
+ const attr = key === "valueMin" ? "aria-valuemin"
1587
+ : key === "valueMax" ? "aria-valuemax" : "aria-valuenow";
1588
+ if (value == null) el.removeAttribute(attr);
1589
+ else el.setAttribute(attr, String(value));
1590
+ } else if (key === "valueText") {
1591
+ if (value == null) el.removeAttribute("aria-valuetext");
1592
+ else el.setAttribute("aria-valuetext", String(value));
1593
+ } else if (key === "actions") {
1594
+ // Sin API DOM de acciones SR — la declaración es
1595
+ // informativa; el evento `action` despacha el
1596
+ // CustomEvent `elur:action` (attach-event).
1597
+ if (value == null) el.removeAttribute("data-elur-actions");
1598
+ else el.setAttribute("data-elur-actions", String(value));
1599
+ } else if (key === "focused") {
1600
+ if (value != null) focusIntent = value === true || value === "true";
1601
+ } else if (key === "focusable") {
1602
+ const on = value === true || value === "true";
1603
+ if (value == null) el.removeAttribute("tabindex");
1604
+ else el.setAttribute("tabindex", on ? "0" : "-1");
1605
+ }
1606
+ }
1607
+ if (focusIntent === true) {
1608
+ // ADR-0117: update-semantics puede llegar antes de
1609
+ // insert-child — focus() sobre detached es no-op, así
1610
+ // que la intención queda pendiente y la materializa
1611
+ // insert-child una vez conectado.
1612
+ (el as any).__elurFocus = true;
1613
+ if (el.isConnected) {
1614
+ (el as HTMLElement).focus();
1615
+ (el as any).__elurFocus = false;
1616
+ }
1617
+ } else if (focusIntent === false) {
1618
+ (el as any).__elurFocus = false;
1619
+ (el as HTMLElement).blur();
1620
+ }
1621
+ }
1622
+ break;
1623
+ }
1624
+ case "update-props": {
1625
+ const got = elementMap.get(op.id);
1626
+ if (got) {
1627
+ // Tag semántico `as` (paridad con el serializador SSR):
1628
+ // create-node fijó el tag por defecto — swap una vez en
1629
+ // mount, antes de attach-event/insert-child (listeners y
1630
+ // children caen en el nuevo nodo vía elementMap).
1631
+ const asVal = op.changedProps["as"];
1632
+ let el = typeof asVal === "string" && got.tagName.toLowerCase() !== asVal
1633
+ ? (() => {
1634
+ const next = document.createElement(asVal);
1635
+ for (const a of Array.from(got.attributes)) {
1636
+ next.setAttribute(a.name, a.value);
1637
+ }
1638
+ while (got.firstChild) next.appendChild(got.firstChild);
1639
+ got.replaceWith(next);
1640
+ elementMap.set(op.id, next);
1641
+ return next;
1642
+ })()
1643
+ : got;
1644
+ // Multiline se resuelve ANTES del loop: el resto de props
1645
+ // del mismo update-props debe aterrizar en el <textarea>
1646
+ // (readOnly/rows/autoCapitalize/spellcheck), no en el
1647
+ // <input> que se retira.
1648
+ if (op.changedProps["multiline"] === true &&
1649
+ el instanceof HTMLInputElement) {
1650
+ const ta = document.createElement("textarea");
1651
+ for (const a of Array.from(el.attributes)) {
1652
+ if (a.name !== "type") ta.setAttribute(a.name, a.value);
1653
+ }
1654
+ ta.value = el.value;
1655
+ ta.placeholder = el.placeholder;
1656
+ el.replaceWith(ta);
1657
+ elementMap.set(op.id, ta);
1658
+ el = ta;
1659
+ }
1660
+ for (const [key, value] of Object.entries(op.changedProps)) {
1661
+ if (key === "as") {
1662
+ // ya aplicado arriba (swap de tag)
1663
+ } else if (key === "draw" && el instanceof HTMLCanvasElement) {
1664
+ replayCanvas(el, value);
1665
+ } else if (key === "animate") {
1666
+ // ADR-0023: animación declarativa → WAAPI
1667
+ playAnimation(el, value);
1668
+ } else if (key === "animate-exit") {
1669
+ // ADR-0023: spec guardada en el elemento — se
1670
+ // ejecuta cuando llegue delete-node (deferred).
1671
+ (el as any).__elurExit = value;
1672
+ } else if (key === "activeTab") {
1673
+ // ADR-0075: la selección de tab sigue al modelo —
1674
+ // restore/deeplink aterrizan en tabs no-default.
1675
+ const nav = el.querySelector("[data-elur-tabbar]");
1676
+ nav?.querySelectorAll("[data-elur-tab]").forEach((b) => {
1677
+ const on = b.getAttribute("data-elur-tab") === value;
1678
+ if (on) b.setAttribute("aria-current", "page");
1679
+ else b.removeAttribute("aria-current");
1680
+ });
1681
+ } else if (key === "label") {
1682
+ // §1.4 accesibilidad: label → alt (img) / aria-label
1683
+ if (el instanceof HTMLImageElement) el.alt = String(value);
1684
+ else el.setAttribute("aria-label", String(value));
1685
+ } else if (key === "accessible") {
1686
+ // accessible=false → fuera del árbol a11y
1687
+ if (value === false || value === "false") el.setAttribute("aria-hidden", "true");
1688
+ else el.removeAttribute("aria-hidden");
1689
+ } else if (key === "dir") {
1690
+ // U17/ADR-0071: dir ltr|rtl — atributo HTML nativo.
1691
+ el.setAttribute("dir", String(value));
1692
+ } else if (key === "scrollTop") {
1693
+ // ADR-0148 — restore/set puntual de scroll. La
1694
+ // op puede llegar antes del primer layout
1695
+ // (scrollHeight=0 clampearía a 0): reintenta por
1696
+ // rAF hasta que pegue o se agoten los frames
1697
+ // (contenido genuinamente más corto que la
1698
+ // posición guardada queda en su tope natural).
1699
+ const y = Number(value) || 0;
1700
+ el.scrollTop = y;
1701
+ if (el.scrollTop !== y) {
1702
+ let tries = 0;
1703
+ const retry = () => {
1704
+ if (el.scrollTop === y || ++tries > 10) return;
1705
+ el.scrollTop = y;
1706
+ requestAnimationFrame(retry);
1707
+ };
1708
+ requestAnimationFrame(retry);
1709
+ }
1710
+ } else if (key === "sticky") {
1711
+ // ADR-0150: pin al top del scroll-view ancestro.
1712
+ // CSS resuelve offset y containing block sola —
1713
+ // `top` aquí es el umbral, no posición absoluta.
1714
+ // Al retirarla se restaura el default (relative).
1715
+ if (value === false || value === null) {
1716
+ el.style.position = "relative";
1717
+ el.style.top = "";
1718
+ } else {
1719
+ const thr = value === true ? 0 : Number(value);
1720
+ el.style.position = "sticky";
1721
+ el.style.top = `${Number.isFinite(thr) ? thr : 0}px`;
1722
+ }
1723
+ } else if (key === "keyboard" && el instanceof HTMLInputElement) {
1724
+ // ADR-0021: intención → type + inputmode
1725
+ const t = {
1726
+ email: "email",
1727
+ number: "number",
1728
+ decimal: "text",
1729
+ phone: "tel",
1730
+ url: "url",
1731
+ password: "password",
1732
+ date: "date",
1733
+ time: "time",
1734
+ datetime: "datetime-local",
1735
+ default: "text",
1736
+ } as Record<string, string>;
1737
+ el.type = t[String(value)] ?? "text";
1738
+ const im = { decimal: "decimal", number: "numeric", phone: "tel", email: "email", url: "url" } as Record<string, string>;
1739
+ if (im[String(value)]) el.setAttribute("inputmode", im[String(value)]);
1740
+ else el.removeAttribute("inputmode");
1741
+ } else if (key === "maxLines") {
1742
+ const n = Number(value);
1743
+ if (n > 0) {
1744
+ el.style.display = "-webkit-box";
1745
+ (el.style as any).webkitBoxOrient = "vertical";
1746
+ (el.style as any).webkitLineClamp = String(n);
1747
+ el.style.overflow = "hidden";
1748
+ } else {
1749
+ (el.style as any).webkitLineClamp = "";
1750
+ }
1751
+ } else if (key === "textOverflow") {
1752
+ el.style.textOverflow = value == null ? "" : String(value);
1753
+ if (value === "ellipsis") el.style.overflow = "hidden";
1754
+ } else if (key === "selectable") {
1755
+ el.style.userSelect = value === false ? "none" : "text";
1756
+ } else if (key === "multiline") {
1757
+ // Conversión hecha arriba (antes del loop) para que
1758
+ // el resto de props del batch vean el <textarea>.
1759
+ } else if (key === "rows") {
1760
+ const target = elementMap.get(op.id) ?? el;
1761
+ if (target instanceof HTMLTextAreaElement) {
1762
+ target.rows = Number(value) || 3;
1763
+ }
1764
+ } else if (key === "readOnly") {
1765
+ (el as HTMLInputElement).readOnly = Boolean(value);
1766
+ } else if (key === "autoCapitalize") {
1767
+ el.setAttribute("autocapitalize", String(value));
1768
+ } else if (key === "spellcheck") {
1769
+ (el as HTMLElement).spellcheck = Boolean(value);
1770
+ } else if (key === "variant" && el instanceof HTMLInputElement) {
1771
+ const v = String(value);
1772
+ if (v === "radio") {
1773
+ el.type = "radio";
1774
+ el.setAttribute("role", "radio");
1775
+ } else if (v === "checkbox") {
1776
+ el.type = "checkbox";
1777
+ el.setAttribute("role", "checkbox");
1778
+ } else {
1779
+ el.type = "checkbox";
1780
+ el.setAttribute("role", "switch");
1781
+ }
1782
+ } else if (key === "horizontal") {
1783
+ if (value) {
1784
+ el.style.overflowX = "auto";
1785
+ el.style.overflowY = "hidden";
1786
+ el.style.display = "flex";
1787
+ el.style.flexDirection = "row";
1788
+ }
1789
+ } else if (key === "scrollLeft") {
1790
+ el.scrollLeft = Number(value) || 0;
1791
+ } else if (key === "paging") {
1792
+ el.style.scrollSnapType = value ? "both mandatory" : "";
1793
+ } else if (key === "inverted") {
1794
+ const horiz = el.style.overflowX === "auto";
1795
+ el.style.flexDirection = value
1796
+ ? (horiz ? "row-reverse" : "column-reverse")
1797
+ : (horiz ? "row" : "column");
1798
+ } else if (key === "refreshing") {
1799
+ if (value) el.setAttribute("data-elur-refreshing", "true");
1800
+ else el.removeAttribute("data-elur-refreshing");
1801
+ } else if (key === "endReachedThreshold") {
1802
+ if (value == null) el.removeAttribute("data-elur-end-threshold");
1803
+ else el.setAttribute("data-elur-end-threshold", String(value));
1804
+ } else if (key === "columns") {
1805
+ const cols = Number(value);
1806
+ if (cols > 1) {
1807
+ el.style.display = "grid";
1808
+ el.style.gridTemplateColumns = `repeat(${cols}, minmax(0, 1fr))`;
1809
+ }
1810
+ } else if (key === "src" && el instanceof HTMLImageElement) {
1811
+ // ADR-0204: un src nuevo re-arma el fallback.
1812
+ setImageSrc(el, value == null ? "" : String(value));
1813
+ } else if (key === "fallbackSrc" && el instanceof HTMLImageElement) {
1814
+ setImageFallback(el, value == null ? null : String(value));
1815
+ } else if (key === "autocomplete" && el instanceof HTMLInputElement) {
1816
+ el.setAttribute("autocomplete", String(value));
1817
+ } else if (key === "enterkey" && el instanceof HTMLInputElement) {
1818
+ el.setAttribute("enterkeyhint", String(value));
1819
+ } else if (key === "maxlength" && el instanceof HTMLInputElement) {
1820
+ el.maxLength = Number(value) || -1;
1821
+ } else if (key === "selection" && el instanceof HTMLInputElement) {
1822
+ const sel = value as { start?: number; end?: number } | null;
1823
+ // ADR-0109: selección programática durante
1824
+ // composición activa se difiere como `value`.
1825
+ const comp = ensureComp(el);
1826
+ if (sel && typeof sel.start === "number") {
1827
+ if (comp.proto.isComposing()) {
1828
+ (el as any).__elurCompSel = sel;
1829
+ } else {
1830
+ el.setSelectionRange(sel.start, sel.end ?? sel.start);
1831
+ }
1832
+ }
1833
+ } else if (key === "shell") {
1834
+ materializeShell(el, value as { kind?: string; chrome?: string; tabs?: Array<{ id: string; label: string }> }, handlers);
1835
+ } else if (key === "stateStyle") {
1836
+ // ADR-0131: variantes por estado → hoja gestionada
1837
+ // (selectores [data-elur-id]:active/[aria-*]…).
1838
+ applyStateStyles(el.ownerDocument, op.id,
1839
+ value as import("../../ir/schema").StateStyleSpec | null);
1840
+ } else if (key === "layoutParams") {
1841
+ // ADR-0122: sin delegados de layout en web —
1842
+ // capability `approx`: recibida e ignorada, no expando.
1843
+ } else if (key === "spans") {
1844
+ // ADR-0147: rangos inline sobre el texto del nodo.
1845
+ (el as SpanCarrier).__elurSpans = value;
1846
+ renderSpans(el, handlers);
1847
+ } else if (key === "renderPolicy") {
1848
+ // ADR-0123: única superficie en web (canvas DOM
1849
+ // acelerado) — capability `approx`: ignorada.
1850
+ } else if (key === "placeholder") {
1851
+ (el as HTMLInputElement).placeholder = String(value);
1852
+ } else if (key === "value") {
1853
+ // Guard contra loop: solo actualizar si es diferente
1854
+ const input = el as HTMLInputElement;
1855
+ // ADR-0109: con composición IME activa la escritura
1856
+ // programática se difiere — setValue pisaría el
1857
+ // tramo provisional y rompería el IME.
1858
+ const comp = ensureComp(input);
1859
+ if (input.value !== String(value)) {
1860
+ if (comp.proto.onProgramWrite(String(value)) === "defer") {
1861
+ // queda pendiente — se aplica al `end`
1862
+ } else {
1863
+ input.value = String(value);
1864
+ }
1865
+ }
1866
+ } else {
1867
+ (el as any)[key] = value;
1868
+ }
1869
+ }
1870
+ }
1871
+ break;
1872
+ }
1873
+ case "create-platform-view": {
1874
+ const def = platformViews.get(`${op.module}:${op.view}`);
1875
+ let el: HTMLElement | undefined;
1876
+ if (ctx.adopt) {
1877
+ if (!ctx._adoptIndex) {
1878
+ ctx._adoptIndex = new Map();
1879
+ for (const found of container.querySelectorAll<HTMLElement>(
1880
+ "[data-elur-id]",
1881
+ )) {
1882
+ const id = Number(found.getAttribute("data-elur-id"));
1883
+ if (!Number.isNaN(id)) ctx._adoptIndex.set(id, found);
1884
+ }
1885
+ }
1886
+ el = ctx._adoptIndex.get(op.id);
1887
+ }
1888
+ if (!el) {
1889
+ el = def ? def.create() : document.createElement("div");
1890
+ el.setAttribute("data-elur-id", String(op.id));
1891
+ el.setAttribute("data-elur-type", `platform-view:${op.module}/${op.view}`);
1892
+ if (op.props) {
1893
+ if (def?.apply) def.apply(el, op.props);
1894
+ else for (const [k, v] of Object.entries(op.props)) (el as any)[k] = v;
1895
+ }
1896
+ }
1897
+ elementMap.set(op.id, el);
1898
+ if (def) pvDefsById.set(op.id, def);
1899
+ break;
1900
+ }
1901
+ case "update-platform-view-props": {
1902
+ const el = elementMap.get(op.id);
1903
+ if (el) {
1904
+ const def = pvDefsById.get(op.id);
1905
+ if (def?.apply) def.apply(el, op.changedProps);
1906
+ else for (const [k, v] of Object.entries(op.changedProps)) (el as any)[k] = v;
1907
+ }
1908
+ break;
1909
+ }
1910
+ case "set-platform-view-visible": {
1911
+ const el = elementMap.get(op.id);
1912
+ if (el) el.style.display = op.visible ? "" : "none";
1913
+ break;
1914
+ }
1915
+ case "insert-child": {
1916
+ const child = elementMap.get(op.childId);
1917
+ if (!child) break;
1918
+ const parent = op.parentId === 0
1919
+ ? container
1920
+ : elementMap.get(op.parentId);
1921
+ if (!parent) break;
1922
+ // Adoptado (V09): el SSR ya posicionó el hijo en su padre —
1923
+ // insertarlo de nuevo sería no-op que invalida layout.
1924
+ if (ctx.adopt && child.parentElement === parent) break;
1925
+ // ADR-0129: virtualización nativa del browser solo para filas
1926
+ // de lista — en cabeceras o tarjetas sueltas pintaba en blanco
1927
+ // fuera de pantalla y hacía saltar el scroll.
1928
+ if (parent.getAttribute("data-elur-type") === "list") {
1929
+ (child.style as any).contentVisibility = "auto";
1930
+ (child.style as any).containIntrinsicSize = "auto 168px";
1931
+ }
1932
+ parent.insertBefore(child, parent.children[op.index] ?? null);
1933
+ // ADR-0117: foco declarado pendiente — se materializa al
1934
+ // conectar (update-semantics llegó antes del attach).
1935
+ if ((child as any).__elurFocus) {
1936
+ (child as any).__elurFocus = false;
1937
+ (child as HTMLElement).focus();
1938
+ }
1939
+ break;
1940
+ }
1941
+ case "delete-node": {
1942
+ const el = elementMap.get(op.id);
1943
+ // Purga de listeners del nodo antes de soltar el elemento —
1944
+ // el registry no puede crecer con nodos muertos (F01/F13).
1945
+ const nodeListeners = listeners?.get(op.id);
1946
+ if (el && nodeListeners) {
1947
+ for (const [, entry] of nodeListeners) releaseListener(el, entry);
1948
+ }
1949
+ listeners?.delete(op.id);
1950
+ applyStateStyles(el?.ownerDocument ?? container.ownerDocument, op.id, null);
1951
+ if (el) {
1952
+ // ADR-0023: exit animation — el nodo ya está muerto en el
1953
+ // IR (no llegarán más ops para él); el DOM se difiere:
1954
+ // animar con fill:forwards y remover al terminar.
1955
+ const exit = (el as any).__elurExit;
1956
+ if (exit && typeof el.animate === "function") {
1957
+ // Consumir el flag ANTES de animar: el microtask de
1958
+ // remove-child (ADR-0023 deferred detach) chequea el
1959
+ // flag para no quitar la vista a media animación.
1960
+ delete (el as any).__elurExit;
1961
+ const anim = playExitAnimation(el, exit);
1962
+ if (anim) {
1963
+ // finished rechaza si la animación se cancela —
1964
+ // remover igual (el nodo ya no existe en el IR).
1965
+ anim.finished.catch(() => { })
1966
+ .then(() => { el.remove(); elementMap.delete(op.id); });
1967
+ break;
1968
+ }
1969
+ }
1970
+ el.remove();
1971
+ elementMap.delete(op.id);
1972
+ }
1973
+ break;
1974
+ }
1975
+ case "remove-child": {
1976
+ // parentId 0 = container raíz (mismo convenio que insert-child).
1977
+ const parent = op.parentId === 0
1978
+ ? container
1979
+ : elementMap.get(op.parentId);
1980
+ const child = elementMap.get(op.childId);
1981
+ if (parent && child && child.parentNode === parent) {
1982
+ // ADR-0023: un hijo con exit-spec queda en el DOM — el
1983
+ // delete-node del mismo batch lo anima visible. Si el
1984
+ // delete no llega (pool/detach), el microtask post-flush
1985
+ // lo remueve como un detach normal.
1986
+ if ((child as any).__elurExit) {
1987
+ queueMicrotask(() => {
1988
+ if ((child as any).__elurExit &&
1989
+ child.parentNode === parent) {
1990
+ parent.removeChild(child);
1991
+ }
1992
+ });
1993
+ } else {
1994
+ parent.removeChild(child);
1995
+ }
1996
+ // ADR-0013 parallax: si el padre es un shell, el hijo
1997
+ // detachado (sigue vivo en elementMap) puede re-insertarse
1998
+ // como overlay cuando llegue la op nav-* de este frame.
1999
+ if (parent.getAttribute("data-elur-type") === "shell") {
2000
+ trackDetachedScreen(parent, child);
2001
+ }
2002
+ }
2003
+ break;
2004
+ }
2005
+ case "move-child": {
2006
+ const parent = elementMap.get(op.parentId);
2007
+ const child = elementMap.get(op.childId);
2008
+ if (parent && child) {
2009
+ parent.removeChild(child);
2010
+ parent.insertBefore(child, parent.children[op.index] ?? null);
2011
+ }
2012
+ break;
2013
+ }
2014
+ case "attach-event": {
2015
+ const el = elementMap.get(op.id);
2016
+ if (el) {
2017
+ const handler = handlers[op.handler];
2018
+ if (handler) {
2019
+ if (op.event === "composition") {
2020
+ // ADR-0109: un evento de vocabulario → tres
2021
+ // listeners DOM (start/update/end); el guard de
2022
+ // value/selection vive en los mismos hooks.
2023
+ const comp = ensureComp(el);
2024
+ comp.handler = (phase, text) => handler(makeEnvelope(
2025
+ "composition" as EventName,
2026
+ "user",
2027
+ { phase, text } as EventDataMap[EventName],
2028
+ Date.now(),
2029
+ ));
2030
+ let perNode = listeners?.get(op.id);
2031
+ if (!perNode) {
2032
+ perNode = new Map();
2033
+ listeners?.set(op.id, perNode);
2034
+ }
2035
+ // Marker: el detach limpia el handler; los
2036
+ // listeners DOM quedan (sostienen el deferral).
2037
+ perNode.set(op.event, { domEvent: "composition", fn: () => { comp.handler = undefined; } });
2038
+ break;
2039
+ }
2040
+ // ADR-0159: `pointer` = tres listeners DOM que
2041
+ // comparten el emit (phase llega por e.type) —
2042
+ // mismo patrón que composition.
2043
+ if (op.event === "pointer") {
2044
+ const emit = (e?: unknown) => {
2045
+ handler(makeEnvelope(
2046
+ "pointer" as EventName,
2047
+ "user",
2048
+ pickEventData("pointer", el, e as Event | undefined) as
2049
+ EventDataMap[EventName],
2050
+ Date.now(),
2051
+ ));
2052
+ };
2053
+ const prev = listeners?.get(op.id)?.get(op.event);
2054
+ if (prev) {
2055
+ el.removeEventListener("pointerenter", prev.fn);
2056
+ el.removeEventListener("pointerleave", prev.fn);
2057
+ el.removeEventListener("pointermove", prev.fn);
2058
+ }
2059
+ el.addEventListener("pointerenter", emit);
2060
+ el.addEventListener("pointerleave", emit);
2061
+ el.addEventListener("pointermove", emit);
2062
+ let perNode = listeners?.get(op.id);
2063
+ if (!perNode) {
2064
+ perNode = new Map();
2065
+ listeners?.set(op.id, perNode);
2066
+ }
2067
+ perNode.set(op.event, { domEvent: "pointer", fn: emit });
2068
+ break;
2069
+ }
2070
+ // ADR-0179: eventos compuestos — cada uno instala sus
2071
+ // listeners y devuelve el dispose que el registro usa
2072
+ // en detach/delete/reset.
2073
+ if (op.event === "longPress" || op.event === "pan" ||
2074
+ op.event === "submit" || op.event === "shortcut" ||
2075
+ op.event === "refresh") {
2076
+ const extra = op.payload !== undefined
2077
+ ? JSON.parse(op.payload) as Record<string, unknown>
2078
+ : {};
2079
+ const ev = op.event as EventName;
2080
+ const emit = (d: object) => handler(makeEnvelope(
2081
+ ev, "user", { ...d, ...extra } as EventDataMap[EventName], Date.now(),
2082
+ ));
2083
+ const prev = listeners?.get(op.id)?.get(op.event);
2084
+ if (prev) releaseListener(el, prev);
2085
+ const dispose =
2086
+ op.event === "longPress" ? attachLongPress(el, emit) :
2087
+ op.event === "pan" ? attachPan(el, emit) :
2088
+ op.event === "submit" ? attachSubmit(el, emit) :
2089
+ op.event === "refresh" ? attachRefresh(el, emit) :
2090
+ typeof extra.combo === "string"
2091
+ ? attachShortcut(el, extra.combo, () => emit({}))
2092
+ : () => { };
2093
+ let perNode = listeners?.get(op.id);
2094
+ if (!perNode) {
2095
+ perNode = new Map();
2096
+ listeners?.set(op.id, perNode);
2097
+ }
2098
+ perNode.set(op.event, { domEvent: op.event, fn: () => { }, dispose });
2099
+ break;
2100
+ }
2101
+ const domEvent = mapEvent(op.event);
2102
+ // Idempotente: re-attach del mismo (nodo,evento)
2103
+ // reemplaza el listener anterior, nunca acumula.
2104
+ // Orden: quitar el previo ANTES de añadir — si el fn
2105
+ // es el mismo, removeEventListener tras add lo
2106
+ // desconectaría.
2107
+ const prev = listeners?.get(op.id)?.get(op.event);
2108
+ if (prev) el.removeEventListener(prev.domEvent, prev.fn);
2109
+ // ADR-0047: TODA entrega pasa por el envelope
2110
+ // normalizado — la app recibe {v,event,origin,ts,data}
2111
+ // igual que en Android; nunca el Event DOM crudo.
2112
+ // origin:"user" — un set programático no dispara el
2113
+ // listener DOM.
2114
+ // ADR-0054: attach-event puede llevar `payload`
2115
+ // (JSON objeto) — contexto del item para filas
2116
+ // template de una lista; se mergea en `data` del
2117
+ // envelope igual que en el host nativo.
2118
+ const extra = op.payload !== undefined
2119
+ ? JSON.parse(op.payload) as Record<string, unknown>
2120
+ : undefined;
2121
+ const fn = (e?: unknown) => {
2122
+ // ADR-0204: un error que el fallback va a
2123
+ // recuperar no llega a la app; el fallback corre
2124
+ // en captura y ya marcó el estado.
2125
+ if (op.event === "error" && el instanceof HTMLImageElement &&
2126
+ imageState(el).suppressError) return;
2127
+ // ADR-0179: el click que cierra un longPress o un
2128
+ // pan no es un press (ni navega si es <a>).
2129
+ if (op.event === "press" && consumeSuppressedClick(el)) {
2130
+ (e as Event | undefined)?.preventDefault();
2131
+ return;
2132
+ }
2133
+ // Enlace real (<a href>) del mismo origen: un clic plano
2134
+ // lo resuelve el router — sin esto el navegador recargaría
2135
+ // el documento. Ctrl/Meta/Shift/Alt, target externo u
2136
+ // otro origen conservan la navegación nativa (ADR-0133).
2137
+ const me = e as MouseEvent | undefined;
2138
+ if (op.event === "press" && el instanceof HTMLAnchorElement &&
2139
+ el.hasAttribute("href") && me && me.button === 0 &&
2140
+ !me.metaKey && !me.ctrlKey && !me.shiftKey && !me.altKey &&
2141
+ (!el.target || el.target === "_self") &&
2142
+ (typeof location === "undefined" || el.origin === location.origin)) {
2143
+ me.preventDefault();
2144
+ }
2145
+ handler(makeEnvelope(
2146
+ op.event as EventName,
2147
+ "user",
2148
+ {
2149
+ ...(pickEventData(op.event, el, e as Event | undefined) as
2150
+ Record<string, unknown>),
2151
+ ...extra,
2152
+ } as EventDataMap[EventName],
2153
+ Date.now(),
2154
+ ));
2155
+ };
2156
+ el.addEventListener(domEvent, fn as EventListener);
2157
+ // Viewport inicial: el reconciler arranca con vh=0
2158
+ // (ventana mínima) — el primer reporte la expande.
2159
+ // Microtask para no reentrar en el apply en curso.
2160
+ if (op.event === "scroll") queueMicrotask(() => fn());
2161
+ let perNode = listeners?.get(op.id);
2162
+ if (!perNode) {
2163
+ perNode = new Map();
2164
+ listeners?.set(op.id, perNode);
2165
+ }
2166
+ perNode.set(op.event, { domEvent, fn });
2167
+ }
2168
+ }
2169
+ break;
2170
+ }
2171
+ case "detach-event": {
2172
+ const el = elementMap.get(op.id);
2173
+ const entry = listeners?.get(op.id)?.get(op.event);
2174
+ // ADR-0109: composition desregistra solo el handler de app (los
2175
+ // hooks composition* guardan el deferral); ADR-0159: pointer
2176
+ // quita sus tres fases; ADR-0179: gestos/atajos su dispose.
2177
+ if (el && entry) releaseListener(el, entry);
2178
+ listeners?.get(op.id)?.delete(op.event);
2179
+ if (el) {
2180
+ el.removeAttribute(`data-elur-event-${op.event}`);
2181
+ el.removeAttribute(`data-elur-on-${op.event}`);
2182
+ }
2183
+ break;
2184
+ }
2185
+ case "reset-node": {
2186
+ // ADR-0057 (U03): estado efímero por item, no por holder —
2187
+ // al rebind del pool estructural se limpia todo lo que no se
2188
+ // deriva del IR antes de re-emitir los bindings del item
2189
+ // nuevo. Los listeners salientes se quitan primero: ningún
2190
+ // callback del reset puede despachar un handler viejo.
2191
+ const el = elementMap.get(op.id);
2192
+ if (!el) break;
2193
+ const perNode = listeners?.get(op.id);
2194
+ if (perNode) {
2195
+ for (const [ev, entry] of perNode) {
2196
+ releaseListener(el, entry);
2197
+ el.removeAttribute(`data-elur-event-${ev}`);
2198
+ el.removeAttribute(`data-elur-on-${ev}`);
2199
+ }
2200
+ perNode.clear();
2201
+ }
2202
+ if (document.activeElement && el.contains(document.activeElement)) {
2203
+ (document.activeElement as HTMLElement).blur();
2204
+ }
2205
+ if (el.scrollTop !== 0 || el.scrollLeft !== 0) {
2206
+ el.scrollTop = 0;
2207
+ el.scrollLeft = 0;
2208
+ }
2209
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
2210
+ el.value = el.defaultValue;
2211
+ el.setSelectionRange(0, 0);
2212
+ }
2213
+ if (el instanceof HTMLInputElement) el.checked = el.defaultChecked;
2214
+ el.getAnimations?.().forEach((a) => a.cancel());
2215
+ break;
2216
+ }
2217
+ case "nav-push": case "nav-pop": case "nav-replace": {
2218
+ // Gate de hidratación (V09): durante el replay inicial el DOM
2219
+ // ya está servido — animar la transición nav sería un flash.
2220
+ if (!ctx.hydrated || ctx.hydrated()) {
2221
+ applyNavTransition(op, elementMap);
2222
+ }
2223
+ break;
2224
+ }
2225
+ case "batch-update":
2226
+ for (const inner of op.ops) applyDomOp(inner, ctx);
2227
+ break;
2228
+ case "layout":
2229
+ break;
2230
+ }
2231
+ }