@lynx-js/react 0.128.0 → 0.129.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 (334) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/components/tsconfig.tsbuildinfo +1 -1
  3. package/package.json +3 -4
  4. package/refresh/.turbo/turbo-build.log +1 -1
  5. package/runtime/__test__/core/entry-re-eval.test.ts +161 -0
  6. package/runtime/__test__/core/hooks/useLynxGlobalEventListener.test.jsx +1 -1
  7. package/runtime/__test__/core/reload-scoped-dual-thread-communication.test.ts +129 -0
  8. package/runtime/__test__/core/thread-function-call.test.ts +1 -0
  9. package/runtime/__test__/element-template/fixtures/background/render/_shared.tsx +2 -0
  10. package/runtime/__test__/element-template/imports/no-legacy-imports.test.ts +7 -6
  11. package/runtime/__test__/element-template/internal/legacy-internal-guardrail.test.ts +1 -2
  12. package/runtime/__test__/element-template/native/index.test.ts +8 -0
  13. package/runtime/__test__/element-template/native/main-thread-api.test.ts +5 -2
  14. package/runtime/__test__/element-template/native/main-thread-ref-init-value.test.ts +100 -0
  15. package/runtime/__test__/element-template/native/mts-destroy.test.ts +83 -0
  16. package/runtime/__test__/element-template/native/reload-dual-thread-communication.test.ts +104 -0
  17. package/runtime/__test__/element-template/native/reload.test.ts +79 -1
  18. package/runtime/__test__/element-template/runtime/background/commit-hook.test.ts +104 -47
  19. package/runtime/__test__/element-template/runtime/background/main-thread-function/compiled-fixtures.test.tsx +7 -1
  20. package/runtime/__test__/element-template/runtime/background/re-eval-reload.test.ts +69 -0
  21. package/runtime/__test__/element-template/runtime/background/update-timing.test.ts +15 -0
  22. package/runtime/__test__/element-template/runtime/hydration/hydration-listener.test.ts +31 -5
  23. package/runtime/__test__/element-template/runtime/patch/element-template-patch.test.tsx +214 -10
  24. package/runtime/__test__/element-template/runtime/patch/update-timing.test.ts +4 -1
  25. package/runtime/__test__/element-template/runtime/render/render-direct-suspense.test.ts +4 -1
  26. package/runtime/__test__/element-template/runtime/render/render-direct.test.ts +4 -1
  27. package/runtime/__test__/element-template/runtime/render/render-main-thread.test.ts +101 -1
  28. package/runtime/__test__/element-template/runtime/render/render-transform.contract.test.ts +2 -0
  29. package/runtime/__test__/element-template/runtime/template/element-template-handle.test.ts +32 -0
  30. package/runtime/__test__/element-template/runtime/template/main-thread-dynamic-attr-state.test.ts +121 -26
  31. package/runtime/__test__/element-template/runtime/template/main-thread-function.test.ts +89 -2
  32. package/runtime/__test__/element-template/test-utils/debug/compiledFixtureModule.ts +5 -0
  33. package/runtime/__test__/element-template/test-utils/debug/envManager.ts +8 -5
  34. package/runtime/__test__/element-template/test-utils/mock/mockNativePapi.ts +35 -2
  35. package/runtime/__test__/guardrails/snapshot-containment.test.ts +45 -11
  36. package/runtime/__test__/shared/component-stack.test.ts +211 -0
  37. package/runtime/__test__/snapshot/debug/formatPatch.test.ts +0 -8
  38. package/runtime/__test__/snapshot/gesture/prepareGestureForCommit.test.js +1 -1
  39. package/runtime/__test__/snapshot/lifecycle/re-eval-reload.test.jsx +114 -0
  40. package/runtime/__test__/snapshot/lifecycle/reload-background-function.test.jsx +169 -0
  41. package/runtime/__test__/snapshot/lifecycle/reload-delayed-background.test.jsx +63 -0
  42. package/runtime/__test__/snapshot/lifecycle/reload-delayed-main-thread.test.jsx +103 -0
  43. package/runtime/__test__/snapshot/lifecycle.test.jsx +61 -1
  44. package/runtime/__test__/snapshot/lynx/lazy-effect-scheduling.test.jsx +105 -0
  45. package/runtime/__test__/snapshot/lynx/timing.test.jsx +3 -0
  46. package/runtime/__test__/snapshot/preact.test.jsx +0 -3
  47. package/runtime/__test__/snapshot/snapshotPatch.test.jsx +0 -33
  48. package/runtime/__test__/snapshot/ssr.test.jsx +2 -2
  49. package/runtime/__test__/snapshot/worklet/runOnBackground.test.js +6 -11
  50. package/runtime/__test__/snapshot/worklet/runOnMainThread.test.jsx +1 -1
  51. package/runtime/__test__/snapshot/worklet/workletRef.test.jsx +24 -1
  52. package/runtime/__test__/worklet-runtime/jsFunctionLifecycle.test.js +27 -1
  53. package/runtime/__test__/worklet-runtime/loadRuntime.test.js +68 -0
  54. package/runtime/__test__/worklet-runtime/mainThreadObject.test.js +46 -0
  55. package/runtime/__test__/worklet-runtime/runOnMainThread.test.js +3 -3
  56. package/runtime/__test__/worklet-runtime/workletRuntime.test.js +30 -0
  57. package/runtime/lazy/element-template-internal.js +0 -1
  58. package/runtime/lazy/internal.js +1 -1
  59. package/runtime/lazy/jsx-dev-runtime.js +1 -1
  60. package/runtime/lazy/jsx-runtime.js +1 -1
  61. package/runtime/lazy/legacy-react-runtime.js +1 -1
  62. package/runtime/lazy/react-lepus.js +1 -1
  63. package/runtime/lazy/react.js +1 -1
  64. package/runtime/lib/core/background-function/exec-map.d.ts +2 -0
  65. package/runtime/lib/core/background-function/exec-map.js +7 -0
  66. package/runtime/lib/core/background-function/exec-map.js.map +1 -1
  67. package/runtime/lib/core/background-function/run-on-background.js +15 -16
  68. package/runtime/lib/core/background-function/run-on-background.js.map +1 -1
  69. package/runtime/lib/core/capture-main-thread-object.js +2 -1
  70. package/runtime/lib/core/capture-main-thread-object.js.map +1 -1
  71. package/runtime/lib/core/card-lifetime.d.ts +5 -0
  72. package/runtime/lib/core/card-lifetime.js +17 -0
  73. package/runtime/lib/core/card-lifetime.js.map +1 -0
  74. package/runtime/lib/core/compat/legacy-react-runtime.js +1 -1
  75. package/runtime/lib/core/compat/legacy-react-runtime.js.map +1 -1
  76. package/runtime/lib/core/entry-reload.d.ts +7 -0
  77. package/runtime/lib/core/entry-reload.js +49 -0
  78. package/runtime/lib/core/entry-reload.js.map +1 -0
  79. package/runtime/lib/core/lynx/lazy-bundle.js +5 -2
  80. package/runtime/lib/core/lynx/lazy-bundle.js.map +1 -1
  81. package/runtime/lib/core/lynx-data-processors.d.ts +125 -1
  82. package/runtime/lib/core/lynx-data-processors.js +3 -0
  83. package/runtime/lib/core/lynx-data-processors.js.map +1 -1
  84. package/runtime/lib/core/main-thread-ref-id.js +4 -4
  85. package/runtime/lib/core/main-thread-ref-id.js.map +1 -1
  86. package/runtime/lib/core/reload-scoped-event.d.ts +5 -0
  87. package/runtime/lib/core/reload-scoped-event.js +26 -0
  88. package/runtime/lib/core/reload-scoped-event.js.map +1 -0
  89. package/runtime/lib/core/reload-version.js +4 -3
  90. package/runtime/lib/core/reload-version.js.map +1 -1
  91. package/runtime/lib/core/runtime-destroy.d.ts +2 -0
  92. package/runtime/lib/core/runtime-destroy.js +10 -1
  93. package/runtime/lib/core/runtime-destroy.js.map +1 -1
  94. package/runtime/lib/core/thread-function-call/main-thread.js +5 -4
  95. package/runtime/lib/core/thread-function-call/main-thread.js.map +1 -1
  96. package/runtime/lib/core/thread-function-call/return-value.js +6 -5
  97. package/runtime/lib/core/thread-function-call/return-value.js.map +1 -1
  98. package/runtime/lib/document.js +0 -5
  99. package/runtime/lib/document.js.map +1 -1
  100. package/runtime/lib/element-template/background/commit-hook.js +24 -22
  101. package/runtime/lib/element-template/background/commit-hook.js.map +1 -1
  102. package/runtime/lib/element-template/background/hydration-listener.js +2 -6
  103. package/runtime/lib/element-template/background/hydration-listener.js.map +1 -1
  104. package/runtime/lib/element-template/client/root.d.ts +1 -1
  105. package/runtime/lib/element-template/client/root.js.map +1 -1
  106. package/runtime/lib/element-template/index.d.ts +2 -2
  107. package/runtime/lib/element-template/index.js.map +1 -1
  108. package/runtime/lib/element-template/internal.d.ts +1 -1
  109. package/runtime/lib/element-template/internal.js +0 -13
  110. package/runtime/lib/element-template/internal.js.map +1 -1
  111. package/runtime/lib/element-template/lynx/env.js.map +1 -1
  112. package/runtime/lib/element-template/main-thread-ref-init-value.d.ts +3 -0
  113. package/runtime/lib/element-template/main-thread-ref-init-value.js +38 -0
  114. package/runtime/lib/element-template/main-thread-ref-init-value.js.map +1 -0
  115. package/runtime/lib/element-template/native/flush.d.ts +1 -0
  116. package/runtime/lib/element-template/native/flush.js +9 -0
  117. package/runtime/lib/element-template/native/flush.js.map +1 -0
  118. package/runtime/lib/element-template/native/index.js +2 -0
  119. package/runtime/lib/element-template/native/index.js.map +1 -1
  120. package/runtime/lib/element-template/native/main-thread-api.js +3 -7
  121. package/runtime/lib/element-template/native/main-thread-api.js.map +1 -1
  122. package/runtime/lib/element-template/native/mts-destroy.js +10 -2
  123. package/runtime/lib/element-template/native/mts-destroy.js.map +1 -1
  124. package/runtime/lib/element-template/native/patch-listener.js +58 -54
  125. package/runtime/lib/element-template/native/patch-listener.js.map +1 -1
  126. package/runtime/lib/element-template/native/reload-background.d.ts +1 -1
  127. package/runtime/lib/element-template/native/reload-background.js +12 -1
  128. package/runtime/lib/element-template/native/reload-background.js.map +1 -1
  129. package/runtime/lib/element-template/native/reload-main-thread.d.ts +6 -0
  130. package/runtime/lib/element-template/native/reload-main-thread.js +20 -3
  131. package/runtime/lib/element-template/native/reload-main-thread.js.map +1 -1
  132. package/runtime/lib/element-template/protocol/lifecycle-constant.d.ts +2 -1
  133. package/runtime/lib/element-template/protocol/lifecycle-constant.js +1 -0
  134. package/runtime/lib/element-template/protocol/lifecycle-constant.js.map +1 -1
  135. package/runtime/lib/element-template/protocol/types.d.ts +0 -2
  136. package/runtime/lib/element-template/protocol/types.js.map +1 -1
  137. package/runtime/lib/element-template/runtime/page/root-instance.d.ts +0 -1
  138. package/runtime/lib/element-template/runtime/page/root-instance.js.map +1 -1
  139. package/runtime/lib/element-template/runtime/patch.js +4 -0
  140. package/runtime/lib/element-template/runtime/patch.js.map +1 -1
  141. package/runtime/lib/element-template/runtime/render/render-components.js +4 -4
  142. package/runtime/lib/element-template/runtime/render/render-components.js.map +1 -1
  143. package/runtime/lib/element-template/runtime/render/render-main-thread.js +2 -0
  144. package/runtime/lib/element-template/runtime/render/render-main-thread.js.map +1 -1
  145. package/runtime/lib/element-template/runtime/template/main-thread-background-function.js +8 -1
  146. package/runtime/lib/element-template/runtime/template/main-thread-background-function.js.map +1 -1
  147. package/runtime/lib/element-template/runtime/template/main-thread-dynamic-attr-state.d.ts +1 -0
  148. package/runtime/lib/element-template/runtime/template/main-thread-dynamic-attr-state.js +41 -21
  149. package/runtime/lib/element-template/runtime/template/main-thread-dynamic-attr-state.js.map +1 -1
  150. package/runtime/lib/element-template/runtime/template/main-thread-ref-ctx.d.ts +1 -1
  151. package/runtime/lib/element-template/runtime/template/main-thread-ref-ctx.js.map +1 -1
  152. package/runtime/lib/internal.d.ts +1 -1
  153. package/runtime/lib/internal.js +1 -1
  154. package/runtime/lib/internal.js.map +1 -1
  155. package/runtime/lib/lynx-api.d.ts +2 -125
  156. package/runtime/lib/lynx-api.js.map +1 -1
  157. package/runtime/lib/shared/component-stack.d.ts +0 -4
  158. package/runtime/lib/shared/component-stack.js +21 -5
  159. package/runtime/lib/shared/component-stack.js.map +1 -1
  160. package/runtime/lib/shared/index-map.d.ts +4 -1
  161. package/runtime/lib/shared/index-map.js +5 -2
  162. package/runtime/lib/shared/index-map.js.map +1 -1
  163. package/runtime/lib/snapshot/gesture/{processGestureBagkround.js → processGestureBackground.js} +1 -1
  164. package/runtime/lib/snapshot/gesture/processGestureBackground.js.map +1 -0
  165. package/runtime/lib/snapshot/lifecycle/destroy.js +6 -0
  166. package/runtime/lib/snapshot/lifecycle/destroy.js.map +1 -1
  167. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.d.ts +6 -2
  168. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.js +21 -18
  169. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.js.map +1 -1
  170. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatch.d.ts +0 -1
  171. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatch.js +0 -5
  172. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatch.js.map +1 -1
  173. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.js +0 -10
  174. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.js.map +1 -1
  175. package/runtime/lib/snapshot/lifecycle/patch/updateMainThread.js +56 -51
  176. package/runtime/lib/snapshot/lifecycle/patch/updateMainThread.js.map +1 -1
  177. package/runtime/lib/snapshot/lifecycle/reload.d.ts +9 -2
  178. package/runtime/lib/snapshot/lifecycle/reload.js +29 -8
  179. package/runtime/lib/snapshot/lifecycle/reload.js.map +1 -1
  180. package/runtime/lib/snapshot/list/list.js +3 -2
  181. package/runtime/lib/snapshot/list/list.js.map +1 -1
  182. package/runtime/lib/snapshot/list/listUpdateInfo.js +0 -30
  183. package/runtime/lib/snapshot/list/listUpdateInfo.js.map +1 -1
  184. package/runtime/lib/snapshot/lynx/calledByNative.js +14 -11
  185. package/runtime/lib/snapshot/lynx/calledByNative.js.map +1 -1
  186. package/runtime/lib/snapshot/renderToOpcodes/hydrate.js +0 -52
  187. package/runtime/lib/snapshot/renderToOpcodes/hydrate.js.map +1 -1
  188. package/runtime/lib/snapshot/renderToOpcodes/index.js +10 -10
  189. package/runtime/lib/snapshot/renderToOpcodes/index.js.map +1 -1
  190. package/runtime/lib/snapshot/renderToOpcodes/opcodes.js +0 -51
  191. package/runtime/lib/snapshot/renderToOpcodes/opcodes.js.map +1 -1
  192. package/runtime/lib/snapshot/snapshot/backgroundSnapshot.js +1 -1
  193. package/runtime/lib/snapshot/snapshot/backgroundSnapshot.js.map +1 -1
  194. package/runtime/lib/snapshot/snapshot/list.js +2 -1
  195. package/runtime/lib/snapshot/snapshot/list.js.map +1 -1
  196. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.d.ts +4 -2
  197. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.js +11 -11
  198. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.js.map +1 -1
  199. package/runtime/lib/snapshot/worklet/call/runOnMainThread.d.ts +1 -0
  200. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js +6 -1
  201. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js.map +1 -1
  202. package/runtime/lib/snapshot/worklet/ctx.d.ts +1 -1
  203. package/runtime/lib/snapshot/worklet/ctx.js +6 -1
  204. package/runtime/lib/snapshot/worklet/ctx.js.map +1 -1
  205. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js +6 -0
  206. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js.map +1 -1
  207. package/runtime/lib/tsconfig.tsbuildinfo +1 -1
  208. package/runtime/lib/worklet-runtime/bindings/index.d.ts +1 -0
  209. package/runtime/lib/worklet-runtime/bindings/index.js +1 -0
  210. package/runtime/lib/worklet-runtime/bindings/index.js.map +1 -1
  211. package/runtime/lib/worklet-runtime/bindings/loadRuntime.d.ts +8 -0
  212. package/runtime/lib/worklet-runtime/bindings/loadRuntime.js +23 -0
  213. package/runtime/lib/worklet-runtime/bindings/loadRuntime.js.map +1 -0
  214. package/runtime/lib/worklet-runtime/delayRunOnBackground.js +3 -1
  215. package/runtime/lib/worklet-runtime/delayRunOnBackground.js.map +1 -1
  216. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.d.ts +2 -0
  217. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js +8 -1
  218. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js.map +1 -1
  219. package/runtime/lib/worklet-runtime/listeners.js +2 -2
  220. package/runtime/lib/worklet-runtime/listeners.js.map +1 -1
  221. package/runtime/lib/worklet-runtime/mainThreadObject.js +3 -1
  222. package/runtime/lib/worklet-runtime/mainThreadObject.js.map +1 -1
  223. package/runtime/lib/worklet-runtime/runOnMainThread.js +4 -3
  224. package/runtime/lib/worklet-runtime/runOnMainThread.js.map +1 -1
  225. package/runtime/lib/worklet-runtime/workletRuntime.js +2 -0
  226. package/runtime/lib/worklet-runtime/workletRuntime.js.map +1 -1
  227. package/runtime/package.json +2 -3
  228. package/runtime/src/core/background-function/exec-map.ts +9 -0
  229. package/runtime/src/core/background-function/run-on-background.ts +14 -16
  230. package/runtime/src/core/capture-main-thread-object.ts +2 -1
  231. package/runtime/src/core/card-lifetime.ts +18 -0
  232. package/runtime/src/core/compat/legacy-react-runtime.ts +1 -1
  233. package/runtime/src/core/entry-reload.ts +63 -0
  234. package/runtime/src/core/lynx/lazy-bundle.ts +5 -2
  235. package/runtime/src/core/lynx-data-processors.ts +124 -1
  236. package/runtime/src/core/main-thread-ref-id.ts +5 -4
  237. package/runtime/src/core/reload-scoped-event.ts +35 -0
  238. package/runtime/src/core/reload-version.ts +5 -3
  239. package/runtime/src/core/runtime-destroy.ts +12 -1
  240. package/runtime/src/core/thread-function-call/main-thread.ts +4 -4
  241. package/runtime/src/core/thread-function-call/return-value.ts +6 -5
  242. package/runtime/src/document.ts +0 -6
  243. package/runtime/src/element-template/background/commit-hook.ts +32 -23
  244. package/runtime/src/element-template/background/hydration-listener.ts +2 -6
  245. package/runtime/src/element-template/client/root.ts +1 -3
  246. package/runtime/src/element-template/index.ts +2 -2
  247. package/runtime/src/element-template/internal.ts +0 -20
  248. package/runtime/src/element-template/lynx/env.ts +1 -1
  249. package/runtime/src/element-template/main-thread-ref-init-value.ts +44 -0
  250. package/runtime/src/element-template/native/flush.ts +10 -0
  251. package/runtime/src/element-template/native/index.ts +2 -0
  252. package/runtime/src/element-template/native/main-thread-api.ts +3 -6
  253. package/runtime/src/element-template/native/mts-destroy.ts +10 -2
  254. package/runtime/src/element-template/native/patch-listener.ts +62 -62
  255. package/runtime/src/element-template/native/reload-background.ts +13 -1
  256. package/runtime/src/element-template/native/reload-main-thread.ts +32 -3
  257. package/runtime/src/element-template/protocol/lifecycle-constant.ts +1 -0
  258. package/runtime/src/element-template/protocol/types.ts +0 -15
  259. package/runtime/src/element-template/runtime/page/root-instance.ts +0 -1
  260. package/runtime/src/element-template/runtime/patch.ts +5 -0
  261. package/runtime/src/element-template/runtime/render/render-components.ts +3 -3
  262. package/runtime/src/element-template/runtime/render/render-main-thread.ts +2 -0
  263. package/runtime/src/element-template/runtime/template/main-thread-background-function.ts +8 -1
  264. package/runtime/src/element-template/runtime/template/main-thread-dynamic-attr-state.ts +51 -21
  265. package/runtime/src/element-template/runtime/template/main-thread-ref-ctx.ts +2 -2
  266. package/runtime/src/element-template/types.d.ts +6 -0
  267. package/runtime/src/internal.ts +1 -1
  268. package/runtime/src/lynx-api.ts +2 -124
  269. package/runtime/src/shared/component-stack.ts +22 -5
  270. package/runtime/src/shared/index-map.ts +3 -2
  271. package/runtime/src/snapshot/lifecycle/destroy.ts +7 -0
  272. package/runtime/src/snapshot/lifecycle/event/firstScreenSync.ts +26 -19
  273. package/runtime/src/snapshot/lifecycle/patch/snapshotPatch.ts +0 -5
  274. package/runtime/src/snapshot/lifecycle/patch/snapshotPatchApply.ts +0 -10
  275. package/runtime/src/snapshot/lifecycle/patch/updateMainThread.ts +62 -58
  276. package/runtime/src/snapshot/lifecycle/reload.ts +47 -11
  277. package/runtime/src/snapshot/list/list.ts +9 -2
  278. package/runtime/src/snapshot/list/listUpdateInfo.ts +0 -52
  279. package/runtime/src/snapshot/lynx/calledByNative.ts +14 -13
  280. package/runtime/src/snapshot/renderToOpcodes/hydrate.ts +0 -58
  281. package/runtime/src/snapshot/renderToOpcodes/index.ts +8 -8
  282. package/runtime/src/snapshot/renderToOpcodes/opcodes.ts +0 -57
  283. package/runtime/src/snapshot/snapshot/backgroundSnapshot.ts +1 -1
  284. package/runtime/src/snapshot/snapshot/list.ts +5 -1
  285. package/runtime/src/snapshot/snapshot/snapshotInstanceManager.ts +19 -12
  286. package/runtime/src/snapshot/worklet/call/runOnMainThread.ts +10 -1
  287. package/runtime/src/snapshot/worklet/ctx.ts +10 -1
  288. package/runtime/src/snapshot/worklet/ref/updateInitValue.ts +6 -0
  289. package/runtime/src/worklet-runtime/README.md +33 -0
  290. package/runtime/src/worklet-runtime/bindings/index.ts +2 -0
  291. package/runtime/src/worklet-runtime/bindings/loadRuntime.ts +25 -0
  292. package/runtime/src/worklet-runtime/delayRunOnBackground.ts +3 -1
  293. package/runtime/src/worklet-runtime/jsFunctionLifecycle.ts +8 -1
  294. package/runtime/src/worklet-runtime/listeners.ts +4 -7
  295. package/runtime/src/worklet-runtime/mainThreadObject.ts +2 -1
  296. package/runtime/src/worklet-runtime/runOnMainThread.ts +4 -3
  297. package/runtime/src/worklet-runtime/workletRuntime.ts +2 -0
  298. package/runtime/types/types.d.ts +3 -1
  299. package/runtime/vitest.config.ts +0 -2
  300. package/testing-library/.turbo/turbo-build.log +7 -7
  301. package/testing-library/src/__tests__/act.test.jsx +0 -7
  302. package/testing-library/src/__tests__/alog.test.jsx +12 -54
  303. package/testing-library/src/__tests__/end-to-end.test.jsx +0 -7
  304. package/testing-library/src/__tests__/renderComponent.test.jsx +0 -14
  305. package/testing-library/src/__tests__/worklet.test.jsx +59 -5
  306. package/transform/.turbo/turbo-build$colon$wasm.log +63 -136
  307. package/transform/__test__/defines.spec.js +137 -0
  308. package/transform/__test__/object-methods.spec.js +79 -0
  309. package/transform/crates/swc_plugin_worklet/definition_imports.rs +97 -0
  310. package/transform/crates/swc_plugin_worklet/extract_ident.rs +99 -49
  311. package/transform/crates/swc_plugin_worklet/gen_stmt.rs +56 -48
  312. package/transform/crates/swc_plugin_worklet/lib.rs +400 -595
  313. package/transform/crates/swc_plugin_worklet/napi.rs +4 -6
  314. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_2_js.js +6 -1
  315. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_2_lepus.js +7 -1
  316. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_js.js +9 -0
  317. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_lepus.js +12 -1
  318. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_preserve_main_thread_objects_in_class_js.js +1 -1
  319. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_preserve_main_thread_objects_in_class_lepus.js +1 -1
  320. package/transform/dist/wasm.cjs +1 -1
  321. package/transform/index.d.ts +3 -1
  322. package/transform/package.json +0 -1
  323. package/transform/src/lib.rs +173 -12
  324. package/transform/swc-plugin-reactlynx/.turbo/turbo-build.log +105 -32
  325. package/transform/swc-plugin-reactlynx/src/lib.rs +1 -4
  326. package/transform/swc-plugin-reactlynx/swc_plugin_reactlynx.wasm +0 -0
  327. package/transform/swc-plugin-reactlynx-compat/.turbo/turbo-build.log +193 -194
  328. package/runtime/lib/snapshot/gesture/processGestureBagkround.js.map +0 -1
  329. package/runtime/lib/snapshot/worklet/hmr.d.ts +0 -1
  330. package/runtime/lib/snapshot/worklet/hmr.js +0 -28
  331. package/runtime/lib/snapshot/worklet/hmr.js.map +0 -1
  332. package/runtime/src/snapshot/worklet/hmr.ts +0 -34
  333. /package/runtime/lib/snapshot/gesture/{processGestureBagkround.d.ts → processGestureBackground.d.ts} +0 -0
  334. /package/runtime/src/snapshot/gesture/{processGestureBagkround.ts → processGestureBackground.ts} +0 -0
@@ -1,3 +1,4 @@
1
+ export { loadWorkletRuntime } from './loadRuntime.js';
1
2
  export * from './bindings.js';
2
3
  export * from './observers.js';
3
4
  export type * from './types.js';
@@ -1,6 +1,7 @@
1
1
  // Copyright 2024 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
+ export { loadWorkletRuntime } from './loadRuntime.js';
4
5
  export * from './bindings.js';
5
6
  export * from './observers.js';
6
7
  export { WorkletEvents } from './events.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/worklet-runtime/bindings/index.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,cAAc,eAAe,CAAC;AAE9B,cAAc,gBAAgB,CAAC;AAI/B,OAAO,EAAE,aAAa,EAAqD,MAAM,aAAa,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\n\nexport * from './bindings.js';\n\nexport * from './observers.js';\n\nexport type * from './types.js';\n\nexport { WorkletEvents, type RunWorkletCtxData, type RunWorkletCtxRetData } from './events.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/worklet-runtime/bindings/index.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD,cAAc,eAAe,CAAC;AAE9B,cAAc,gBAAgB,CAAC;AAI/B,OAAO,EAAE,aAAa,EAAqD,MAAM,aAAa,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\n\nexport { loadWorkletRuntime } from './loadRuntime.js';\n\nexport * from './bindings.js';\n\nexport * from './observers.js';\n\nexport type * from './types.js';\n\nexport { WorkletEvents, type RunWorkletCtxData, type RunWorkletCtxRetData } from './events.js';\n"]}
@@ -0,0 +1,8 @@
1
+ import '../global.js';
2
+ /**
3
+ * Loads the legacy main-thread worklet chunk or reuses an initialized runtime.
4
+ * @param __schema - The dynamic component entry for loading the Lepus chunk.
5
+ * @returns Whether the worklet runtime was loaded and initialized successfully.
6
+ */
7
+ declare function loadWorkletRuntime(__schema?: string): boolean;
8
+ export { loadWorkletRuntime };
@@ -0,0 +1,23 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import '../global.js';
5
+ /**
6
+ * Loads the legacy main-thread worklet chunk or reuses an initialized runtime.
7
+ * @param __schema - The dynamic component entry for loading the Lepus chunk.
8
+ * @returns Whether the worklet runtime was loaded and initialized successfully.
9
+ */
10
+ function loadWorkletRuntime(__schema) {
11
+ if (typeof __LoadLepusChunk === 'undefined') {
12
+ return false;
13
+ }
14
+ if (globalThis.lynxWorkletImpl) {
15
+ return true;
16
+ }
17
+ return __LoadLepusChunk('worklet-runtime', {
18
+ dynamicComponentEntry: __schema,
19
+ chunkType: 0,
20
+ });
21
+ }
22
+ export { loadWorkletRuntime };
23
+ //# sourceMappingURL=loadRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loadRuntime.js","sourceRoot":"","sources":["../../../src/worklet-runtime/bindings/loadRuntime.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,cAAc,CAAC;AAEtB;;;;GAIG;AACH,SAAS,kBAAkB,CAAC,QAAiB;IAC3C,IAAI,OAAO,gBAAgB,KAAK,WAAW,EAAE,CAAC;QAC5C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,UAAU,CAAC,eAAe,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,gBAAgB,CAAC,iBAAiB,EAAE;QACzC,qBAAqB,EAAE,QAAQ;QAC/B,SAAS,EAAE,CAAC;KACb,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\n\nimport '../global.js';\n\n/**\n * Loads the legacy main-thread worklet chunk or reuses an initialized runtime.\n * @param __schema - The dynamic component entry for loading the Lepus chunk.\n * @returns Whether the worklet runtime was loaded and initialized successfully.\n */\nfunction loadWorkletRuntime(__schema?: string): boolean {\n if (typeof __LoadLepusChunk === 'undefined') {\n return false;\n }\n if (globalThis.lynxWorkletImpl) {\n return true;\n }\n return __LoadLepusChunk('worklet-runtime', {\n dynamicComponentEntry: __schema,\n chunkType: 0,\n });\n}\n\nexport { loadWorkletRuntime };\n"]}
@@ -13,7 +13,9 @@ function delayRunOnBackground(fnObj, task) {
13
13
  delayIndices.push(impl.delayedBackgroundFunctionArray.length - 1);
14
14
  }
15
15
  function clearDelayedBackgroundFunctions() {
16
- impl.delayedBackgroundFunctionArray.length = 0;
16
+ // PrimJS can keep truncated array storage alive; drop the consumed queue so
17
+ // its tasks and hydrated handles stop retaining their background executions.
18
+ impl.delayedBackgroundFunctionArray = [];
17
19
  }
18
20
  function runDelayedBackgroundFunctions() {
19
21
  for (const details of impl.delayedBackgroundFunctionArray) {
@@ -1 +1 @@
1
- {"version":3,"file":"delayRunOnBackground.js","sourceRoot":"","sources":["../../src/worklet-runtime/delayRunOnBackground.ts"],"names":[],"mappings":"AAoBA,IAAI,IAA0C,CAAC;AAE/C,SAAS,wBAAwB;IAC/B,OAAO,CAAC,IAAI,GAAG;QACb,8BAA8B,EAAE,EAAE;QAClC,+BAA+B;QAC/B,oBAAoB;QACpB,6BAA6B;KAC9B,CAAC,CAAC;AACL,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAiB,EAAE,IAA4C;IAC3F,IAAK,CAAC,8BAA8B,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,YAAY,GAAG,KAAK,CAAC,aAAa,KAAK,EAAE,CAAC;IAChD,YAAY,CAAC,IAAI,CAAC,IAAK,CAAC,8BAA8B,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACrE,CAAC;AAED,SAAS,+BAA+B;IACtC,IAAK,CAAC,8BAA8B,CAAC,MAAM,GAAG,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,6BAA6B;IACpC,KAAK,MAAM,OAAO,IAAI,IAAK,CAAC,8BAA8B,EAAE,CAAC;QAC3D,IAAI,OAAO,EAAE,UAAU,EAAE,CAAC;YACxB,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,OAAQ,EAAE,OAAO,CAAC,UAAU,CAAC,OAAQ,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IACD,+BAA+B,EAAE,CAAC;AACpC,CAAC;AAED,OAAO,EAAiC,wBAAwB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport type { JsFnHandle } from './bindings/types.js';\n\ninterface Details {\n task: (fnId: number, execId: number) => void;\n\n // This comes from the background thread, inserted here during ctx hydration.\n jsFnHandle?: JsFnHandle;\n}\n\ninterface RunOnBackgroundDelayImpl {\n // Elements should keep the order being called by the user.\n delayedBackgroundFunctionArray: Array<Details | undefined>;\n clearDelayedBackgroundFunctions(): void;\n delayRunOnBackground(fnObj: JsFnHandle, fn: (fnId: number, execId: number) => void): void;\n runDelayedBackgroundFunctions(): void;\n}\n\nlet impl: RunOnBackgroundDelayImpl | undefined;\n\nfunction initRunOnBackgroundDelay(): RunOnBackgroundDelayImpl {\n return (impl = {\n delayedBackgroundFunctionArray: [],\n clearDelayedBackgroundFunctions,\n delayRunOnBackground,\n runDelayedBackgroundFunctions,\n });\n}\n\nfunction delayRunOnBackground(fnObj: JsFnHandle, task: (fnId: number, execId: number) => void) {\n impl!.delayedBackgroundFunctionArray.push({ task });\n const delayIndices = fnObj._delayIndices ??= [];\n delayIndices.push(impl!.delayedBackgroundFunctionArray.length - 1);\n}\n\nfunction clearDelayedBackgroundFunctions(): void {\n impl!.delayedBackgroundFunctionArray.length = 0;\n}\n\nfunction runDelayedBackgroundFunctions(): void {\n for (const details of impl!.delayedBackgroundFunctionArray) {\n if (details?.jsFnHandle) {\n details.task(details.jsFnHandle._jsFnId!, details.jsFnHandle._execId!);\n }\n }\n clearDelayedBackgroundFunctions();\n}\n\nexport { type RunOnBackgroundDelayImpl, initRunOnBackgroundDelay };\n"]}
1
+ {"version":3,"file":"delayRunOnBackground.js","sourceRoot":"","sources":["../../src/worklet-runtime/delayRunOnBackground.ts"],"names":[],"mappings":"AAoBA,IAAI,IAA0C,CAAC;AAE/C,SAAS,wBAAwB;IAC/B,OAAO,CAAC,IAAI,GAAG;QACb,8BAA8B,EAAE,EAAE;QAClC,+BAA+B;QAC/B,oBAAoB;QACpB,6BAA6B;KAC9B,CAAC,CAAC;AACL,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAiB,EAAE,IAA4C;IAC3F,IAAK,CAAC,8BAA8B,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,YAAY,GAAG,KAAK,CAAC,aAAa,KAAK,EAAE,CAAC;IAChD,YAAY,CAAC,IAAI,CAAC,IAAK,CAAC,8BAA8B,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACrE,CAAC;AAED,SAAS,+BAA+B;IACtC,4EAA4E;IAC5E,6EAA6E;IAC7E,IAAK,CAAC,8BAA8B,GAAG,EAAE,CAAC;AAC5C,CAAC;AAED,SAAS,6BAA6B;IACpC,KAAK,MAAM,OAAO,IAAI,IAAK,CAAC,8BAA8B,EAAE,CAAC;QAC3D,IAAI,OAAO,EAAE,UAAU,EAAE,CAAC;YACxB,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,OAAQ,EAAE,OAAO,CAAC,UAAU,CAAC,OAAQ,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;IACD,+BAA+B,EAAE,CAAC;AACpC,CAAC;AAED,OAAO,EAAiC,wBAAwB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport type { JsFnHandle } from './bindings/types.js';\n\ninterface Details {\n task: (fnId: number, execId: number) => void;\n\n // This comes from the background thread, inserted here during ctx hydration.\n jsFnHandle?: JsFnHandle;\n}\n\ninterface RunOnBackgroundDelayImpl {\n // Elements should keep the order being called by the user.\n delayedBackgroundFunctionArray: Array<Details | undefined>;\n clearDelayedBackgroundFunctions(): void;\n delayRunOnBackground(fnObj: JsFnHandle, fn: (fnId: number, execId: number) => void): void;\n runDelayedBackgroundFunctions(): void;\n}\n\nlet impl: RunOnBackgroundDelayImpl | undefined;\n\nfunction initRunOnBackgroundDelay(): RunOnBackgroundDelayImpl {\n return (impl = {\n delayedBackgroundFunctionArray: [],\n clearDelayedBackgroundFunctions,\n delayRunOnBackground,\n runDelayedBackgroundFunctions,\n });\n}\n\nfunction delayRunOnBackground(fnObj: JsFnHandle, task: (fnId: number, execId: number) => void) {\n impl!.delayedBackgroundFunctionArray.push({ task });\n const delayIndices = fnObj._delayIndices ??= [];\n delayIndices.push(impl!.delayedBackgroundFunctionArray.length - 1);\n}\n\nfunction clearDelayedBackgroundFunctions(): void {\n // PrimJS can keep truncated array storage alive; drop the consumed queue so\n // its tasks and hydrated handles stop retaining their background executions.\n impl!.delayedBackgroundFunctionArray = [];\n}\n\nfunction runDelayedBackgroundFunctions(): void {\n for (const details of impl!.delayedBackgroundFunctionArray) {\n if (details?.jsFnHandle) {\n details.task(details.jsFnHandle._jsFnId!, details.jsFnHandle._execId!);\n }\n }\n clearDelayedBackgroundFunctions();\n}\n\nexport { type RunOnBackgroundDelayImpl, initRunOnBackgroundDelay };\n"]}
@@ -9,10 +9,12 @@ declare class JsFunctionLifecycleManager {
9
9
  private execIdSetToFire;
10
10
  private retainedObjects;
11
11
  private willFire;
12
+ private active;
12
13
  private registry;
13
14
  constructor();
14
15
  addRef(execId: number, objToRef: object): void;
15
16
  removeRef(execId: number): void;
17
+ dispose(): void;
16
18
  fire(): void;
17
19
  }
18
20
  declare function isRunOnBackgroundEnabled(): boolean;
@@ -15,6 +15,7 @@ class JsFunctionLifecycleManager {
15
15
  execIdSetToFire = new Set();
16
16
  retainedObjects = new WeakSet();
17
17
  willFire = false;
18
+ active = true;
18
19
  registry;
19
20
  constructor() {
20
21
  this.registry = new FinalizationRegistry(this.removeRef.bind(this));
@@ -23,9 +24,10 @@ class JsFunctionLifecycleManager {
23
24
  if (this.retainedObjects.has(objToRef)) {
24
25
  return;
25
26
  }
27
+ // A failed engine registration must leave the target eligible for a retry.
28
+ this.registry.register(objToRef, execId);
26
29
  this.retainedObjects.add(objToRef);
27
30
  this.execIdRefCount.set(execId, (this.execIdRefCount.get(execId) ?? 0) + 1);
28
- this.registry.register(objToRef, execId);
29
31
  }
30
32
  removeRef(execId) {
31
33
  const rc = this.execIdRefCount.get(execId);
@@ -42,7 +44,12 @@ class JsFunctionLifecycleManager {
42
44
  });
43
45
  }
44
46
  }
47
+ dispose() {
48
+ this.active = false;
49
+ }
45
50
  fire() {
51
+ if (!this.active)
52
+ return;
46
53
  profile('JsFunctionLifecycleManager.fire', () => {
47
54
  lynx.getJSContext().dispatchEvent({
48
55
  type: WorkletEvents.releaseBackgroundWorkletCtx,
@@ -1 +1 @@
1
- {"version":3,"file":"jsFunctionLifecycle.js","sourceRoot":"","sources":["../../src/worklet-runtime/jsFunctionLifecycle.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,0BAA0B;IACtB,cAAc,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,eAAe,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,eAAe,GAAG,IAAI,OAAO,EAAU,CAAC;IACxC,QAAQ,GAAG,KAAK,CAAC;IACjB,QAAQ,CAA+B;IAE/C;QACE,IAAI,CAAC,QAAQ,GAAG,IAAI,oBAAoB,CAAS,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,QAAgB;QACrC,IAAI,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACvC,OAAO;QACT,CAAC;QACD,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,CAAC,cAAc,CAAC,GAAG,CACrB,MAAM,EACN,CAAC,IAAI,CAAC,cAAc,CAA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E,0BAA0B,EAAE,wBAAwB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { WorkletEvents } from './bindings/events.js';\nimport { profile } from './utils/profile.js';\nimport { isSdkVersionGt } from './utils/version.js';\n\n/**\n * `JsFunctionLifecycleManager` monitors references to JS function handles to be called by `runOnBackground()`.\n * In JS context, functions to be called by `runOnBackground()` is referenced by `JsFnHandle`s and finally by `execId`.\n * When all `JsFnHandle`s in lepus are released, an event will be sent to JS context to de-ref the `execId`,\n * resulting a de-ref to the js function in JS context.\n */\nclass JsFunctionLifecycleManager {\n private execIdRefCount = new Map<number, number>();\n private execIdSetToFire = new Set<number>();\n private retainedObjects = new WeakSet<object>();\n private willFire = false;\n private registry: FinalizationRegistry<number>;\n\n constructor() {\n this.registry = new FinalizationRegistry<number>(this.removeRef.bind(this));\n }\n\n addRef(execId: number, objToRef: object): void {\n if (this.retainedObjects.has(objToRef)) {\n return;\n }\n this.retainedObjects.add(objToRef);\n this.execIdRefCount.set(\n execId,\n (this.execIdRefCount.get(execId) ?? 0) + 1,\n );\n this.registry.register(objToRef, execId);\n }\n\n removeRef(execId: number): void {\n const rc = this.execIdRefCount.get(execId)!;\n if (rc > 1) {\n this.execIdRefCount.set(execId, rc - 1);\n return;\n }\n this.execIdRefCount.delete(execId);\n this.execIdSetToFire.add(execId);\n if (!this.willFire) {\n this.willFire = true;\n void Promise.resolve().then(() => {\n this.fire();\n });\n }\n }\n\n fire(): void {\n profile('JsFunctionLifecycleManager.fire', () => {\n lynx.getJSContext().dispatchEvent({\n type: WorkletEvents.releaseBackgroundWorkletCtx,\n data: Array.from(this.execIdSetToFire),\n });\n this.execIdSetToFire.clear();\n this.willFire = false;\n });\n }\n}\n\nfunction isRunOnBackgroundEnabled(): boolean {\n return isSdkVersionGt(2, 15);\n}\n\nexport { JsFunctionLifecycleManager, isRunOnBackgroundEnabled };\n"]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I,EAAE,GAAG,CAAC,EAAE,CAAC;YACX,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC;YACxC,OAAO;QACT,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACjC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;YACrB,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;gBAC/B,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,IAAI;QACF,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,OAAO;QACzB,OAAO,CAAC,iCAAiC,EAAE,GAAG,EAAE;YAC9C,IAAI,CAAC,YAAY,EAAE,CAAC,aAAa,CAAC;gBAChC,IAAI,EAAE,aAAa,CAAC,2BAA2B;gBAC/C,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC;aACvC,CAAC,CAAC;YACH,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;YAC7B,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;QACxB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,SAAS,wBAAwB;IAC/B,OAAO,cAAc,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/B,CAAC;AAED,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { WorkletEvents } from './bindings/events.js';\nimport { profile } from './utils/profile.js';\nimport { isSdkVersionGt } from './utils/version.js';\n\n/**\n * `JsFunctionLifecycleManager` monitors references to JS function handles to be called by `runOnBackground()`.\n * In JS context, functions to be called by `runOnBackground()` is referenced by `JsFnHandle`s and finally by `execId`.\n * When all `JsFnHandle`s in lepus are released, an event will be sent to JS context to de-ref the `execId`,\n * resulting a de-ref to the js function in JS context.\n */\nclass JsFunctionLifecycleManager {\n private execIdRefCount = new Map<number, number>();\n private execIdSetToFire = new Set<number>();\n private retainedObjects = new WeakSet<object>();\n private willFire = false;\n private active = true;\n private registry: FinalizationRegistry<number>;\n\n constructor() {\n this.registry = new FinalizationRegistry<number>(this.removeRef.bind(this));\n }\n\n addRef(execId: number, objToRef: object): void {\n if (this.retainedObjects.has(objToRef)) {\n return;\n }\n // A failed engine registration must leave the target eligible for a retry.\n this.registry.register(objToRef, execId);\n this.retainedObjects.add(objToRef);\n this.execIdRefCount.set(\n execId,\n (this.execIdRefCount.get(execId) ?? 0) + 1,\n );\n }\n\n removeRef(execId: number): void {\n const rc = this.execIdRefCount.get(execId)!;\n if (rc > 1) {\n this.execIdRefCount.set(execId, rc - 1);\n return;\n }\n this.execIdRefCount.delete(execId);\n this.execIdSetToFire.add(execId);\n if (!this.willFire) {\n this.willFire = true;\n void Promise.resolve().then(() => {\n this.fire();\n });\n }\n }\n\n dispose(): void {\n this.active = false;\n }\n\n fire(): void {\n if (!this.active) return;\n profile('JsFunctionLifecycleManager.fire', () => {\n lynx.getJSContext().dispatchEvent({\n type: WorkletEvents.releaseBackgroundWorkletCtx,\n data: Array.from(this.execIdSetToFire),\n });\n this.execIdSetToFire.clear();\n this.willFire = false;\n });\n }\n}\n\nfunction isRunOnBackgroundEnabled(): boolean {\n return isSdkVersionGt(2, 15);\n}\n\nexport { JsFunctionLifecycleManager, isRunOnBackgroundEnabled };\n"]}
@@ -1,13 +1,13 @@
1
1
  // Copyright 2024 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
+ import { addReloadScopedEventListener } from '../core/reload-scoped-event.js';
4
5
  import { WorkletEvents } from './bindings/events.js';
5
6
  import { runRunOnMainThreadTask } from './runOnMainThread.js';
6
7
  import { removeValueFromWorkletRefMap } from './workletRef.js';
7
8
  function initEventListeners() {
8
9
  const jsContext = lynx.getJSContext();
9
- jsContext.addEventListener(WorkletEvents.runWorkletCtx, (event) => {
10
- const data = JSON.parse(event.data);
10
+ addReloadScopedEventListener(jsContext, WorkletEvents.runWorkletCtx, (data) => {
11
11
  runRunOnMainThreadTask(data.worklet, data.params, data.resolveId);
12
12
  });
13
13
  jsContext.addEventListener(WorkletEvents.releaseWorkletRef, (event) => {
@@ -1 +1 @@
1
- {"version":3,"file":"listeners.js","sourceRoot":"","sources":["../../src/worklet-runtime/listeners.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAE/D,SAAS,kBAAkB;IACzB,MAAM,SAAS,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;IACtC,SAAS,CAAC,gBAAgB,CACxB,aAAa,CAAC,aAAa,EAC3B,CAAC,KAAY,EAAE,EAAE;QACf,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAc,CAAsB,CAAC;QACnE,sBAAsB,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAA4B,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC1F,CAAC,CACF,CAAC;IACF,SAAS,CAAC,gBAAgB,CACxB,aAAa,CAAC,iBAAiB,EAC/B,CAAC,KAAY,EAAE,EAAE;QACf,4BAA4B,CAAE,KAAK,CAAC,IAA8B,CAAC,EAAE,CAAC,CAAC;IACzE,CAAC,CACF,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { WorkletEvents } from './bindings/events.js';\nimport type { ReleaseWorkletRefData, RunWorkletCtxData } from './bindings/events.js';\nimport type { ClosureValueType } from './bindings/types.js';\nimport { runRunOnMainThreadTask } from './runOnMainThread.js';\nimport type { Event } from './types/runtimeProxy.js';\nimport { removeValueFromWorkletRefMap } from './workletRef.js';\n\nfunction initEventListeners(): void {\n const jsContext = lynx.getJSContext();\n jsContext.addEventListener(\n WorkletEvents.runWorkletCtx,\n (event: Event) => {\n const data = JSON.parse(event.data as string) as RunWorkletCtxData;\n runRunOnMainThreadTask(data.worklet, data.params as ClosureValueType[], data.resolveId);\n },\n );\n jsContext.addEventListener(\n WorkletEvents.releaseWorkletRef,\n (event: Event) => {\n removeValueFromWorkletRefMap((event.data as ReleaseWorkletRefData).id);\n },\n );\n}\n\nexport { initEventListeners };\n"]}
1
+ {"version":3,"file":"listeners.js","sourceRoot":"","sources":["../../src/worklet-runtime/listeners.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAE/D,SAAS,kBAAkB;IACzB,MAAM,SAAS,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;IACtC,4BAA4B,CAAC,SAAS,EAAE,aAAa,CAAC,aAAa,EAAE,CAAC,IAAuB,EAAE,EAAE;QAC/F,sBAAsB,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAA4B,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC1F,CAAC,CAAC,CAAC;IACH,SAAS,CAAC,gBAAgB,CACxB,aAAa,CAAC,iBAAiB,EAC/B,CAAC,KAAY,EAAE,EAAE;QACf,4BAA4B,CAAE,KAAK,CAAC,IAA8B,CAAC,EAAE,CAAC,CAAC;IACzE,CAAC,CACF,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { addReloadScopedEventListener } from '../core/reload-scoped-event.js';\nimport { WorkletEvents } from './bindings/events.js';\nimport type { ReleaseWorkletRefData, RunWorkletCtxData } from './bindings/events.js';\nimport type { ClosureValueType } from './bindings/types.js';\nimport { runRunOnMainThreadTask } from './runOnMainThread.js';\nimport type { Event } from './types/runtimeProxy.js';\nimport { removeValueFromWorkletRefMap } from './workletRef.js';\n\nfunction initEventListeners(): void {\n const jsContext = lynx.getJSContext();\n addReloadScopedEventListener(jsContext, WorkletEvents.runWorkletCtx, (data: RunWorkletCtxData) => {\n runRunOnMainThreadTask(data.worklet, data.params as ClosureValueType[], data.resolveId);\n });\n jsContext.addEventListener(\n WorkletEvents.releaseWorkletRef,\n (event: Event) => {\n removeValueFromWorkletRefMap((event.data as ReleaseWorkletRefData).id);\n },\n );\n}\n\nexport { initEventListeners };\n"]}
@@ -12,8 +12,10 @@ function registerMainThreadObjectType(type, create) {
12
12
  !== getFactoryRegistrationIdentity(create)) {
13
13
  throw new Error(`Conflicting MainThreadObject registration for type "${type}". A type key must always use the same create function.`);
14
14
  }
15
- return;
15
+ if (registered.create === create)
16
+ return;
16
17
  }
18
+ // A re-evaluated module brings a factory bound to its own module state.
17
19
  mainThreadObjectDefinitions.set(type, { create });
18
20
  }
19
21
  function getFactoryRegistrationIdentity(factory) {
@@ -1 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AC,KAAK,qCAAqC,YAAY,0CAA0C,UAAU,IAAI,CACvL,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB;IAC5B,2BAA2B,CAAC,KAAK,EAAE,CAAC;IACpC,6BAA6B,GAAG,IAAI,OAAO,EAAE,CAAC;AAChD,CAAC;AAED,OAAO,EAEL,qBAAqB,EACrB,4BAA4B,EAC5B,sBAAsB,EACtB,gCAAgC,EAChC,0BAA0B,GAC3B,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport type { Worklet, WorkletRefImpl } from './bindings/types.js';\n\ntype MainThreadObjectFactory = (initialValue: unknown) => object;\ninterface MainThreadObjectDefinition {\n create: MainThreadObjectFactory | Worklet;\n resolvedCreate?: MainThreadObjectFactory;\n}\n\nconst mainThreadObjectDefinitions = new Map<string, MainThreadObjectDefinition>();\n// The brand belongs to the target, not an individual handle. Other handles or\n// captured contexts may still own the target after one ref-map entry is removed.\nlet realizedMainThreadObjectTypes = new WeakMap<object, string>();\n\nfunction registerMainThreadObjectType(\n type: string,\n create: MainThreadObjectFactory | Worklet,\n): void {\n if (type === 'main-thread') {\n throw new Error(\n 'MainThreadObject type \"main-thread\" is reserved for MainThreadRef.',\n );\n }\n const registered = mainThreadObjectDefinitions.get(type);\n if (registered) {\n if (\n getFactoryRegistrationIdentity(registered.create)\n !== getFactoryRegistrationIdentity(create)\n ) {\n throw new Error(\n `Conflicting MainThreadObject registration for type \"${type}\". A type key must always use the same create function.`,\n );\n }\n return;\n }\n mainThreadObjectDefinitions.set(type, { create });\n}\n\nfunction getFactoryRegistrationIdentity(\n factory: MainThreadObjectFactory | Worklet,\n): string {\n if (typeof factory === 'function') {\n return Function.prototype.toString.call(factory);\n }\n return `worklet:${factory._wkltId}`;\n}\n\nfunction resolveFactoryFunction(\n factory: MainThreadObjectFactory | Worklet,\n): MainThreadObjectFactory {\n if (typeof factory === 'function') {\n return factory;\n }\n if (!('_wkltId' in factory) || '_lepusWorkletHash' in factory) {\n throw new Error('Cannot resolve an invalid Main Thread Function.');\n }\n // Factories are capture-free, so they need neither context traversal nor binding.\n // Resolve on first use: the compiler registers worklets after module evaluation.\n return lynxWorkletImpl._workletMap[factory._wkltId] as MainThreadObjectFactory;\n}\n\nfunction getMainThreadObjectFactory(\n definition: MainThreadObjectDefinition,\n): MainThreadObjectFactory {\n return definition.resolvedCreate ??= resolveFactoryFunction(definition.create);\n}\n\nfunction createMainThreadObject(refImpl: WorkletRefImpl<unknown>): object {\n const type = refImpl._type!;\n const definition = mainThreadObjectDefinitions.get(type);\n if (!definition) {\n throw new Error(\n `MainThreadObject type is not registered: \"${type}\". Define the type in a module evaluated on the main thread before initializing its handle.`,\n );\n }\n\n const value = getMainThreadObjectFactory(definition)(refImpl._initValue);\n if (typeof value !== 'object' || value === null) {\n throw new Error(`MainThreadObject type \"${type}\" created a non-object value.`);\n }\n realizedMainThreadObjectTypes.set(value, type);\n return value;\n}\n\nfunction isRealizedMainThreadObject(value: object): boolean {\n return realizedMainThreadObjectTypes.has(value);\n}\n\nfunction assertCompatibleMainThreadObject(\n handle: WorkletRefImpl<unknown>,\n value: object,\n operation: 'hydration' | 'initialization patch',\n): void {\n const actualType = realizedMainThreadObjectTypes.get(value);\n const expectedType = handle._type!;\n if (actualType !== expectedType) {\n throw new Error(\n `MainThreadObject type mismatch during ${operation} for handle ${handle._wvid}: background handle expects type \"${expectedType}\", but the main-thread target is type \"${actualType}\".`,\n );\n }\n}\n\nfunction initMainThreadObjects(): void {\n mainThreadObjectDefinitions.clear();\n realizedMainThreadObjectTypes = new WeakMap();\n}\n\nexport {\n type MainThreadObjectFactory,\n initMainThreadObjects,\n registerMainThreadObjectType,\n createMainThreadObject,\n assertCompatibleMainThreadObject,\n isRealizedMainThreadObject,\n};\n"]}
1
+ {"version":3,"file":"mainThreadObject.js","sourceRoot":"","sources":["../../src/worklet-runtime/mainThreadObject.ts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YAAY,0CAA0C,UAAU,IAAI,CACvL,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB;IAC5B,2BAA2B,CAAC,KAAK,EAAE,CAAC;IACpC,6BAA6B,GAAG,IAAI,OAAO,EAAE,CAAC;AAChD,CAAC;AAED,OAAO,EAEL,qBAAqB,EACrB,4BAA4B,EAC5B,sBAAsB,EACtB,gCAAgC,EAChC,0BAA0B,GAC3B,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport type { Worklet, WorkletRefImpl } from './bindings/types.js';\n\ntype MainThreadObjectFactory = (initialValue: unknown) => object;\ninterface MainThreadObjectDefinition {\n create: MainThreadObjectFactory | Worklet;\n resolvedCreate?: MainThreadObjectFactory;\n}\n\nconst mainThreadObjectDefinitions = new Map<string, MainThreadObjectDefinition>();\n// The brand belongs to the target, not an individual handle. Other handles or\n// captured contexts may still own the target after one ref-map entry is removed.\nlet realizedMainThreadObjectTypes = new WeakMap<object, string>();\n\nfunction registerMainThreadObjectType(\n type: string,\n create: MainThreadObjectFactory | Worklet,\n): void {\n if (type === 'main-thread') {\n throw new Error(\n 'MainThreadObject type \"main-thread\" is reserved for MainThreadRef.',\n );\n }\n const registered = mainThreadObjectDefinitions.get(type);\n if (registered) {\n if (\n getFactoryRegistrationIdentity(registered.create)\n !== getFactoryRegistrationIdentity(create)\n ) {\n throw new Error(\n `Conflicting MainThreadObject registration for type \"${type}\". A type key must always use the same create function.`,\n );\n }\n if (registered.create === create) return;\n }\n // A re-evaluated module brings a factory bound to its own module state.\n mainThreadObjectDefinitions.set(type, { create });\n}\n\nfunction getFactoryRegistrationIdentity(\n factory: MainThreadObjectFactory | Worklet,\n): string {\n if (typeof factory === 'function') {\n return Function.prototype.toString.call(factory);\n }\n return `worklet:${factory._wkltId}`;\n}\n\nfunction resolveFactoryFunction(\n factory: MainThreadObjectFactory | Worklet,\n): MainThreadObjectFactory {\n if (typeof factory === 'function') {\n return factory;\n }\n if (!('_wkltId' in factory) || '_lepusWorkletHash' in factory) {\n throw new Error('Cannot resolve an invalid Main Thread Function.');\n }\n // Factories are capture-free, so they need neither context traversal nor binding.\n // Resolve on first use: the compiler registers worklets after module evaluation.\n return lynxWorkletImpl._workletMap[factory._wkltId] as MainThreadObjectFactory;\n}\n\nfunction getMainThreadObjectFactory(\n definition: MainThreadObjectDefinition,\n): MainThreadObjectFactory {\n return definition.resolvedCreate ??= resolveFactoryFunction(definition.create);\n}\n\nfunction createMainThreadObject(refImpl: WorkletRefImpl<unknown>): object {\n const type = refImpl._type!;\n const definition = mainThreadObjectDefinitions.get(type);\n if (!definition) {\n throw new Error(\n `MainThreadObject type is not registered: \"${type}\". Define the type in a module evaluated on the main thread before initializing its handle.`,\n );\n }\n\n const value = getMainThreadObjectFactory(definition)(refImpl._initValue);\n if (typeof value !== 'object' || value === null) {\n throw new Error(`MainThreadObject type \"${type}\" created a non-object value.`);\n }\n realizedMainThreadObjectTypes.set(value, type);\n return value;\n}\n\nfunction isRealizedMainThreadObject(value: object): boolean {\n return realizedMainThreadObjectTypes.has(value);\n}\n\nfunction assertCompatibleMainThreadObject(\n handle: WorkletRefImpl<unknown>,\n value: object,\n operation: 'hydration' | 'initialization patch',\n): void {\n const actualType = realizedMainThreadObjectTypes.get(value);\n const expectedType = handle._type!;\n if (actualType !== expectedType) {\n throw new Error(\n `MainThreadObject type mismatch during ${operation} for handle ${handle._wvid}: background handle expects type \"${expectedType}\", but the main-thread target is type \"${actualType}\".`,\n );\n }\n}\n\nfunction initMainThreadObjects(): void {\n mainThreadObjectDefinitions.clear();\n realizedMainThreadObjectTypes = new WeakMap();\n}\n\nexport {\n type MainThreadObjectFactory,\n initMainThreadObjects,\n registerMainThreadObjectType,\n createMainThreadObject,\n assertCompatibleMainThreadObject,\n isRealizedMainThreadObject,\n};\n"]}
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
+ import { dispatchReloadScopedEvent } from '../core/reload-scoped-event.js';
4
5
  import { WorkletEvents } from './bindings/index.js';
5
6
  export function runRunOnMainThreadTask(task, params, resolveId) {
6
7
  let returnValue;
@@ -9,12 +10,12 @@ export function runRunOnMainThreadTask(task, params, resolveId) {
9
10
  }
10
11
  finally {
11
12
  // TODO: Should be more proper to reject the promise if there is an error.
12
- lynx.getJSContext().dispatchEvent({
13
+ dispatchReloadScopedEvent(lynx.getJSContext(), {
13
14
  type: WorkletEvents.FunctionCallRet,
14
- data: JSON.stringify({
15
+ data: {
15
16
  resolveId,
16
17
  returnValue,
17
- }),
18
+ },
18
19
  });
19
20
  }
20
21
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runOnMainThread.js","sourceRoot":"","sources":["../../src/worklet-runtime/runOnMainThread.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,MAAM,UAAU,sBAAsB,CAAC,IAAa,EAAE,MAA0B,EAAE,SAAiB;IACjG,IAAI,WAAW,CAAC;IAChB,IAAI,CAAC;QACH,WAAW,GAAG,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;YAAS,CAAC;QACT,0EAA0E;QAC1E,IAAI,CAAC,YAAY,EAAE,CAAC,aAAa,CAAC;YAChC,IAAI,EAAE,aAAa,CAAC,eAAe;YACnC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;gBACnB,SAAS;gBACT,WAAW;aACY,CAAC;SAC3B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["// Copyright 2025 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { WorkletEvents } from './bindings/index.js';\nimport type { ClosureValueType, RunWorkletCtxRetData, Worklet } from './bindings/index.js';\n\nexport function runRunOnMainThreadTask(task: Worklet, params: ClosureValueType[], resolveId: number): void {\n let returnValue;\n try {\n returnValue = runWorklet(task, params);\n } finally {\n // TODO: Should be more proper to reject the promise if there is an error.\n lynx.getJSContext().dispatchEvent({\n type: WorkletEvents.FunctionCallRet,\n data: JSON.stringify({\n resolveId,\n returnValue,\n } as RunWorkletCtxRetData),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"runOnMainThread.js","sourceRoot":"","sources":["../../src/worklet-runtime/runOnMainThread.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,MAAM,UAAU,sBAAsB,CAAC,IAAa,EAAE,MAA0B,EAAE,SAAiB;IACjG,IAAI,WAAW,CAAC;IAChB,IAAI,CAAC;QACH,WAAW,GAAG,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;YAAS,CAAC;QACT,0EAA0E;QAC1E,yBAAyB,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE;YAC7C,IAAI,EAAE,aAAa,CAAC,eAAe;YACnC,IAAI,EAAE;gBACJ,SAAS;gBACT,WAAW;aACY;SAC1B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["// Copyright 2025 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { dispatchReloadScopedEvent } from '../core/reload-scoped-event.js';\nimport { WorkletEvents } from './bindings/index.js';\nimport type { ClosureValueType, RunWorkletCtxRetData, Worklet } from './bindings/index.js';\n\nexport function runRunOnMainThreadTask(task: Worklet, params: ClosureValueType[], resolveId: number): void {\n let returnValue;\n try {\n returnValue = runWorklet(task, params);\n } finally {\n // TODO: Should be more proper to reject the promise if there is an error.\n dispatchReloadScopedEvent(lynx.getJSContext(), {\n type: WorkletEvents.FunctionCallRet,\n data: {\n resolveId,\n returnValue,\n } as RunWorkletCtxRetData,\n });\n }\n}\n"]}
@@ -15,6 +15,8 @@ import { mainThreadFlushLoopMark } from './utils/mainThreadFlushLoopGuard.js';
15
15
  import { profile } from './utils/profile.js';
16
16
  import { getFromWorkletRefMap, initWorkletRef } from './workletRef.js';
17
17
  function initWorklet() {
18
+ const previousManager = globalThis.lynxWorkletImpl?._jsFunctionLifecycleManager;
19
+ previousManager?.dispose();
18
20
  globalThis.lynxWorkletImpl = {
19
21
  _workletMap: {},
20
22
  _refImpl: initWorkletRef(),
@@ -1 +1 @@
1
- {"version":3,"file":"workletRuntime.js","sourceRoot":"","sources":["../../src/worklet-runtime/workletRuntime.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OA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AI,CAAC,UAAU,CAAC,YAAY,EAAE,CAAC;YAC/C,wEAAwE;YACxE,MAAM,WAAW,GAAG,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;YAC1D,WAAW,CAAC,GAAG,CAAC,GAAG,kBAAkB,CAAC;YACtC,OAAO,mBAAmB,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;QAC/C,CAAC;QACD,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,kBAAkB,CAAC,CAAC;IACtD,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACnB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,mBAAmB,CAC1B,GAAqC,EACrC,cAAqC,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC;IAE1E,6EAA6E;IAC7E,+EAA+E;IAC/E,OAAO,MAAM,CAAC,gBAAgB,CAC5B,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAChB,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,GAAG,CAAkB,CAAqC,EAClG,WAAW,CACwB,CAAC;AACxC,CAAC;AAED,SAAS,4BAA4B,CACnC,KAAa;IAEb,MAAM,UAAU,GAAG,KAAyC,CAAC;IAC7D,OAAO,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ;WACtC,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ;WACpC,UAAU,CAAC,KAAK,KAAK,aAAa,CAAC;AAC1C,CAAC;AACD,OAAO,EAAE,WAAW,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { Element } from './api/element.js';\nimport type { ClosureValueType, RunWorkletOptions, Worklet, WorkletRefImpl } from './bindings/types.js';\nimport { RunWorkletSource } from './bindings/types.js';\nimport { initRunOnBackgroundDelay } from './delayRunOnBackground.js';\nimport { delayExecUntilJsReady, initEventDelay } from './delayWorkletEvent.js';\nimport { initEomImpl } from './eomImpl.js';\nimport { addEventMethodsIfNeeded } from './eventPropagation.js';\nimport { hydrateCtx } from './hydrate.js';\nimport { JsFunctionLifecycleManager, isRunOnBackgroundEnabled } from './jsFunctionLifecycle.js';\nimport { isRealizedMainThreadObject } from './mainThreadObject.js';\nimport { runRunOnMainThreadTask } from './runOnMainThread.js';\nimport { mainThreadFlushLoopMark } from './utils/mainThreadFlushLoopGuard.js';\nimport { profile } from './utils/profile.js';\nimport { getFromWorkletRefMap, initWorkletRef } from './workletRef.js';\n\nfunction initWorklet(): void {\n globalThis.lynxWorkletImpl = {\n _workletMap: {},\n _refImpl: initWorkletRef(),\n _runOnBackgroundDelayImpl: initRunOnBackgroundDelay(),\n _hydrateCtx: hydrateCtx,\n _eventDelayImpl: initEventDelay(),\n _eomImpl: initEomImpl(),\n _runRunOnMainThreadTask: runRunOnMainThreadTask,\n };\n\n if (isRunOnBackgroundEnabled()) {\n globalThis.lynxWorkletImpl._jsFunctionLifecycleManager = new JsFunctionLifecycleManager();\n }\n\n globalThis.registerWorklet = registerWorklet;\n globalThis.registerWorkletInternal = registerWorklet;\n globalThis.runWorklet = runWorklet;\n}\n\n/**\n * Register a worklet function, allowing it to be executed by `runWorklet()`.\n * This is called in lepus.js.\n * @param _type worklet type, 'main-thread' or 'ui'\n * @param id worklet hash\n * @param worklet worklet function\n */\nfunction registerWorklet(_type: string, id: string, worklet: (...args: unknown[]) => unknown): void {\n lynxWorkletImpl._workletMap[id] = worklet;\n}\n\n/**\n * Entrance of all worklet calls.\n * Native event touch handler will call this function.\n * @param ctx worklet object.\n * @param params worklet params.\n * @param options run worklet options.\n */\nfunction runWorklet(ctx: Worklet, params: ClosureValueType[], options?: RunWorkletOptions): unknown {\n if (!validateWorklet(ctx)) {\n return;\n }\n\n if (__DEV__) {\n if (options?.source === RunWorkletSource.EVENT && Array.isArray(params)) {\n const first = params[0];\n const t = (first as { type?: unknown }).type;\n if (typeof t === 'string') {\n mainThreadFlushLoopMark(`event:${t}`);\n }\n }\n\n mainThreadFlushLoopMark(`MainThreadFunction id=${String(ctx._wkltId)}`);\n }\n\n if ('_lepusWorkletHash' in ctx) {\n delayExecUntilJsReady(ctx._lepusWorkletHash, params);\n return;\n }\n return runWorkletImpl(ctx, params, options);\n}\n\nfunction runWorkletImpl(ctx: Worklet, params: ClosureValueType[], options?: RunWorkletOptions): unknown {\n const worklet: (...args: unknown[]) => unknown = profile(\n 'transformWorkletCtx ' + ctx._wkltId,\n () => transformWorklet(ctx, true),\n );\n const params_: ClosureValueType[] = profile(\n 'transformWorkletParams',\n () => transformWorklet(params || [], false),\n );\n\n const [hasEventMethods, eventCtx] = addEventMethodsIfNeeded(params_, options);\n\n const result = profile('runWorklet', () => worklet(...params_));\n\n if (hasEventMethods) {\n return {\n returnValue: result,\n eventReturnResult: eventCtx._eventReturnResult,\n };\n }\n\n return result;\n}\n\nfunction validateWorklet(ctx: unknown): ctx is Worklet {\n return typeof ctx === 'object' && ctx !== null && ('_wkltId' in ctx || '_lepusWorkletHash' in ctx);\n}\n\nconst workletCache = /*#__PURE__*/ new WeakMap<object, ClosureValueType | ((...args: unknown[]) => unknown)>();\n\nfunction transformWorklet(ctx: Worklet, isWorklet: true): (...args: unknown[]) => unknown;\nfunction transformWorklet(\n ctx: ClosureValueType[],\n isWorklet: false,\n): ClosureValueType[];\n\nfunction transformWorklet(\n ctx: ClosureValueType,\n isWorklet: boolean,\n): ClosureValueType | ((...args: unknown[]) => unknown) {\n /* v8 ignore next 3 */\n if (typeof ctx !== 'object' || ctx === null) {\n return ctx;\n }\n\n if (isWorklet) {\n const res = workletCache.get(ctx);\n if (res) {\n return res;\n }\n }\n\n const worklet = transformWorkletInner({ main: ctx }, 0, ctx) as { main: ClosureValueType };\n\n if (isWorklet) {\n workletCache.set(ctx, worklet.main);\n }\n\n return worklet.main;\n}\n\nconst transformWorkletInner = (\n value: ClosureValueType,\n depth: number,\n ctx: unknown,\n): ClosureValueType => {\n const limit = 1000;\n if (++depth >= limit) {\n throw new Error('Depth of value exceeds limit of ' + limit + '.');\n }\n /* v8 ignore next 3 */\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n let obj = value as Record<string, ClosureValueType>;\n\n for (const key in obj) {\n const subObj: ClosureValueType = obj[key];\n if (typeof subObj !== 'object' || subObj === null) {\n continue;\n }\n\n // A MainThreadObject initialization payload is user data. Resolve the\n // typed descriptor before walking it so payload properties that resemble\n // worklet metadata remain untouched. Legacy MainThreadRef descriptors retain\n // the existing recursive path.\n if (isRealizedMainThreadObject(subObj)) {\n continue;\n }\n if (isMainThreadObjectDescriptor(subObj)) {\n obj = replaceCapturedProperty(obj, value, key, getFromWorkletRefMap(subObj));\n continue;\n }\n\n if (/** isEventTarget */ 'elementRefptr' in subObj) {\n obj[key] = new Element(subObj.elementRefptr as ElementNode);\n continue;\n } else if (subObj instanceof Element) {\n continue;\n }\n\n const transformedSubObj = transformWorkletInner(subObj, depth, ctx) as Record<string, ClosureValueType>;\n\n const isWorkletRef = '_wvid' in (subObj as object);\n if (isWorkletRef) {\n obj[key] = getFromWorkletRefMap(\n subObj as unknown as WorkletRefImpl<unknown>,\n );\n continue;\n }\n const isWorklet = '_wkltId' in subObj;\n if (isWorklet) {\n const isRootWorklet = subObj === ctx;\n const boundCtx = { ...transformedSubObj };\n // Keep the original context collectible. PrimJS traces WeakMap values even\n // when their keys are otherwise unreachable, so the cached function must not point back to its key.\n const boundWorklet: ((...args: unknown[]) => unknown) & { boundCtx?: object } = lynxWorkletImpl\n ._workletMap[(subObj as Worklet)._wkltId]!\n .bind(boundCtx);\n if (transformedSubObj !== subObj && obj === value && obj !== ctx) obj = copyAccessorCapture(obj);\n obj = replaceCapturedProperty(obj, value, key, boundWorklet);\n if (!isRootWorklet) {\n // Hydration needs the same context that the function already owns through bind().\n // The original nested context can disappear after its parent replaces it with this function.\n boundWorklet.boundCtx = boundCtx;\n }\n continue;\n }\n if (transformedSubObj !== subObj) {\n // The root context is runtime-owned: hydration must see its captured copy.\n if (obj === value && obj !== ctx) obj = copyAccessorCapture(obj);\n obj = replaceCapturedProperty(obj, value, key, transformedSubObj);\n }\n const isJsFn = '_jsFnId' in subObj;\n if (isJsFn) {\n (subObj as Record<string, ClosureValueType>)['_execId'] = (ctx as Worklet)._execId;\n lynxWorkletImpl._jsFunctionLifecycleManager?.addRef(\n (ctx as Worklet)._execId!,\n subObj,\n );\n continue;\n }\n }\n return obj;\n};\n\nfunction replaceCapturedProperty(\n obj: Record<string, ClosureValueType>,\n source: object,\n key: string,\n value: ClosureValueType,\n): Record<string, ClosureValueType> {\n const descriptor = Object.getOwnPropertyDescriptor(obj, key);\n if (descriptor?.get) {\n // Getters can refresh handles or method receivers. Materialize the captured\n // value without consuming the source getter or invoking its setter.\n const capturedDescriptor = {\n value,\n writable: true,\n enumerable: descriptor.enumerable!,\n configurable: descriptor.configurable!,\n };\n if (obj === source || !descriptor.configurable) {\n // Replace before defining the copy, including non-configurable getters.\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n descriptors[key] = capturedDescriptor;\n return copyAccessorCapture(obj, descriptors);\n }\n Object.defineProperty(obj, key, capturedDescriptor);\n } else {\n obj[key] = value;\n }\n return obj;\n}\n\nfunction copyAccessorCapture(\n obj: Record<string, ClosureValueType>,\n descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(obj),\n): Record<string, ClosureValueType> {\n // Copy descriptors without evaluating getters a second time. Array ancestors\n // retain their array identity when a nested accessor requires a captured copy.\n return Object.defineProperties(\n Array.isArray(obj)\n ? []\n : Object.create(Object.getPrototypeOf(obj) as object | null) as Record<string, ClosureValueType>,\n descriptors,\n ) as Record<string, ClosureValueType>;\n}\n\nfunction isMainThreadObjectDescriptor(\n value: object,\n): value is WorkletRefImpl<unknown> {\n const descriptor = value as Partial<WorkletRefImpl<unknown>>;\n return typeof descriptor._wvid === 'number'\n && typeof descriptor._type === 'string'\n && descriptor._type !== 'main-thread';\n}\nexport { initWorklet };\n"]}
1
+ {"version":3,"file":"workletRuntime.js","sourceRoot":"","sources":["../../src/worklet-runtime/workletRuntime.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEvE,SAAS,WAAW;IAClB,MAAM,eAAe,GAAG,UAAU,CAAC,eAAe,EAAE,2BAA2B,CAAC;IAChF,eAAe,EAAE,OAAO,EAAE,CAAC;IAC3B,UAAU,CAAC,eAAe,GAAG;QAC3B,WAAW,EAAE,EAAE;QACf,QAAQ,EAAE,cAAc,EAAE;QAC1B,yBAAyB,EAAE,wBAAwB,EAAE;QACrD,WAAW,EAAE,UAAU;QACvB,eAAe,EAAE,cAAc,EAAE;QACjC,QAAQ,EAAE,WAAW,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AG,EAAE,GAAG,EAAE,kBAAkB,CAAC,CAAC;IACtD,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACnB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,mBAAmB,CAC1B,GAAqC,EACrC,cAAqC,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC;IAE1E,6EAA6E;IAC7E,+EAA+E;IAC/E,OAAO,MAAM,CAAC,gBAAgB,CAC5B,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAChB,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,GAAG,CAAkB,CAAqC,EAClG,WAAW,CACwB,CAAC;AACxC,CAAC;AAED,SAAS,4BAA4B,CACnC,KAAa;IAEb,MAAM,UAAU,GAAG,KAAyC,CAAC;IAC7D,OAAO,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ;WACtC,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ;WACpC,UAAU,CAAC,KAAK,KAAK,aAAa,CAAC;AAC1C,CAAC;AACD,OAAO,EAAE,WAAW,EAAE,CAAC","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\nimport { Element } from './api/element.js';\nimport type { ClosureValueType, RunWorkletOptions, Worklet, WorkletRefImpl } from './bindings/types.js';\nimport { RunWorkletSource } from './bindings/types.js';\nimport { initRunOnBackgroundDelay } from './delayRunOnBackground.js';\nimport { delayExecUntilJsReady, initEventDelay } from './delayWorkletEvent.js';\nimport { initEomImpl } from './eomImpl.js';\nimport { addEventMethodsIfNeeded } from './eventPropagation.js';\nimport { hydrateCtx } from './hydrate.js';\nimport { JsFunctionLifecycleManager, isRunOnBackgroundEnabled } from './jsFunctionLifecycle.js';\nimport { isRealizedMainThreadObject } from './mainThreadObject.js';\nimport { runRunOnMainThreadTask } from './runOnMainThread.js';\nimport { mainThreadFlushLoopMark } from './utils/mainThreadFlushLoopGuard.js';\nimport { profile } from './utils/profile.js';\nimport { getFromWorkletRefMap, initWorkletRef } from './workletRef.js';\n\nfunction initWorklet(): void {\n const previousManager = globalThis.lynxWorkletImpl?._jsFunctionLifecycleManager;\n previousManager?.dispose();\n globalThis.lynxWorkletImpl = {\n _workletMap: {},\n _refImpl: initWorkletRef(),\n _runOnBackgroundDelayImpl: initRunOnBackgroundDelay(),\n _hydrateCtx: hydrateCtx,\n _eventDelayImpl: initEventDelay(),\n _eomImpl: initEomImpl(),\n _runRunOnMainThreadTask: runRunOnMainThreadTask,\n };\n\n if (isRunOnBackgroundEnabled()) {\n globalThis.lynxWorkletImpl._jsFunctionLifecycleManager = new JsFunctionLifecycleManager();\n }\n\n globalThis.registerWorklet = registerWorklet;\n globalThis.registerWorkletInternal = registerWorklet;\n globalThis.runWorklet = runWorklet;\n}\n\n/**\n * Register a worklet function, allowing it to be executed by `runWorklet()`.\n * This is called in lepus.js.\n * @param _type worklet type, 'main-thread' or 'ui'\n * @param id worklet hash\n * @param worklet worklet function\n */\nfunction registerWorklet(_type: string, id: string, worklet: (...args: unknown[]) => unknown): void {\n lynxWorkletImpl._workletMap[id] = worklet;\n}\n\n/**\n * Entrance of all worklet calls.\n * Native event touch handler will call this function.\n * @param ctx worklet object.\n * @param params worklet params.\n * @param options run worklet options.\n */\nfunction runWorklet(ctx: Worklet, params: ClosureValueType[], options?: RunWorkletOptions): unknown {\n if (!validateWorklet(ctx)) {\n return;\n }\n\n if (__DEV__) {\n if (options?.source === RunWorkletSource.EVENT && Array.isArray(params)) {\n const first = params[0];\n const t = (first as { type?: unknown }).type;\n if (typeof t === 'string') {\n mainThreadFlushLoopMark(`event:${t}`);\n }\n }\n\n mainThreadFlushLoopMark(`MainThreadFunction id=${String(ctx._wkltId)}`);\n }\n\n if ('_lepusWorkletHash' in ctx) {\n delayExecUntilJsReady(ctx._lepusWorkletHash, params);\n return;\n }\n return runWorkletImpl(ctx, params, options);\n}\n\nfunction runWorkletImpl(ctx: Worklet, params: ClosureValueType[], options?: RunWorkletOptions): unknown {\n const worklet: (...args: unknown[]) => unknown = profile(\n 'transformWorkletCtx ' + ctx._wkltId,\n () => transformWorklet(ctx, true),\n );\n const params_: ClosureValueType[] = profile(\n 'transformWorkletParams',\n () => transformWorklet(params || [], false),\n );\n\n const [hasEventMethods, eventCtx] = addEventMethodsIfNeeded(params_, options);\n\n const result = profile('runWorklet', () => worklet(...params_));\n\n if (hasEventMethods) {\n return {\n returnValue: result,\n eventReturnResult: eventCtx._eventReturnResult,\n };\n }\n\n return result;\n}\n\nfunction validateWorklet(ctx: unknown): ctx is Worklet {\n return typeof ctx === 'object' && ctx !== null && ('_wkltId' in ctx || '_lepusWorkletHash' in ctx);\n}\n\nconst workletCache = /*#__PURE__*/ new WeakMap<object, ClosureValueType | ((...args: unknown[]) => unknown)>();\n\nfunction transformWorklet(ctx: Worklet, isWorklet: true): (...args: unknown[]) => unknown;\nfunction transformWorklet(\n ctx: ClosureValueType[],\n isWorklet: false,\n): ClosureValueType[];\n\nfunction transformWorklet(\n ctx: ClosureValueType,\n isWorklet: boolean,\n): ClosureValueType | ((...args: unknown[]) => unknown) {\n /* v8 ignore next 3 */\n if (typeof ctx !== 'object' || ctx === null) {\n return ctx;\n }\n\n if (isWorklet) {\n const res = workletCache.get(ctx);\n if (res) {\n return res;\n }\n }\n\n const worklet = transformWorkletInner({ main: ctx }, 0, ctx) as { main: ClosureValueType };\n\n if (isWorklet) {\n workletCache.set(ctx, worklet.main);\n }\n\n return worklet.main;\n}\n\nconst transformWorkletInner = (\n value: ClosureValueType,\n depth: number,\n ctx: unknown,\n): ClosureValueType => {\n const limit = 1000;\n if (++depth >= limit) {\n throw new Error('Depth of value exceeds limit of ' + limit + '.');\n }\n /* v8 ignore next 3 */\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n let obj = value as Record<string, ClosureValueType>;\n\n for (const key in obj) {\n const subObj: ClosureValueType = obj[key];\n if (typeof subObj !== 'object' || subObj === null) {\n continue;\n }\n\n // A MainThreadObject initialization payload is user data. Resolve the\n // typed descriptor before walking it so payload properties that resemble\n // worklet metadata remain untouched. Legacy MainThreadRef descriptors retain\n // the existing recursive path.\n if (isRealizedMainThreadObject(subObj)) {\n continue;\n }\n if (isMainThreadObjectDescriptor(subObj)) {\n obj = replaceCapturedProperty(obj, value, key, getFromWorkletRefMap(subObj));\n continue;\n }\n\n if (/** isEventTarget */ 'elementRefptr' in subObj) {\n obj[key] = new Element(subObj.elementRefptr as ElementNode);\n continue;\n } else if (subObj instanceof Element) {\n continue;\n }\n\n const transformedSubObj = transformWorkletInner(subObj, depth, ctx) as Record<string, ClosureValueType>;\n\n const isWorkletRef = '_wvid' in (subObj as object);\n if (isWorkletRef) {\n obj[key] = getFromWorkletRefMap(\n subObj as unknown as WorkletRefImpl<unknown>,\n );\n continue;\n }\n const isWorklet = '_wkltId' in subObj;\n if (isWorklet) {\n const isRootWorklet = subObj === ctx;\n const boundCtx = { ...transformedSubObj };\n // Keep the original context collectible. PrimJS traces WeakMap values even\n // when their keys are otherwise unreachable, so the cached function must not point back to its key.\n const boundWorklet: ((...args: unknown[]) => unknown) & { boundCtx?: object } = lynxWorkletImpl\n ._workletMap[(subObj as Worklet)._wkltId]!\n .bind(boundCtx);\n if (transformedSubObj !== subObj && obj === value && obj !== ctx) obj = copyAccessorCapture(obj);\n obj = replaceCapturedProperty(obj, value, key, boundWorklet);\n if (!isRootWorklet) {\n // Hydration needs the same context that the function already owns through bind().\n // The original nested context can disappear after its parent replaces it with this function.\n boundWorklet.boundCtx = boundCtx;\n }\n continue;\n }\n if (transformedSubObj !== subObj) {\n // The root context is runtime-owned: hydration must see its captured copy.\n if (obj === value && obj !== ctx) obj = copyAccessorCapture(obj);\n obj = replaceCapturedProperty(obj, value, key, transformedSubObj);\n }\n const isJsFn = '_jsFnId' in subObj;\n if (isJsFn) {\n (subObj as Record<string, ClosureValueType>)['_execId'] = (ctx as Worklet)._execId;\n lynxWorkletImpl._jsFunctionLifecycleManager?.addRef(\n (ctx as Worklet)._execId!,\n subObj,\n );\n continue;\n }\n }\n return obj;\n};\n\nfunction replaceCapturedProperty(\n obj: Record<string, ClosureValueType>,\n source: object,\n key: string,\n value: ClosureValueType,\n): Record<string, ClosureValueType> {\n const descriptor = Object.getOwnPropertyDescriptor(obj, key);\n if (descriptor?.get) {\n // Getters can refresh handles or method receivers. Materialize the captured\n // value without consuming the source getter or invoking its setter.\n const capturedDescriptor = {\n value,\n writable: true,\n enumerable: descriptor.enumerable!,\n configurable: descriptor.configurable!,\n };\n if (obj === source || !descriptor.configurable) {\n // Replace before defining the copy, including non-configurable getters.\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n descriptors[key] = capturedDescriptor;\n return copyAccessorCapture(obj, descriptors);\n }\n Object.defineProperty(obj, key, capturedDescriptor);\n } else {\n obj[key] = value;\n }\n return obj;\n}\n\nfunction copyAccessorCapture(\n obj: Record<string, ClosureValueType>,\n descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(obj),\n): Record<string, ClosureValueType> {\n // Copy descriptors without evaluating getters a second time. Array ancestors\n // retain their array identity when a nested accessor requires a captured copy.\n return Object.defineProperties(\n Array.isArray(obj)\n ? []\n : Object.create(Object.getPrototypeOf(obj) as object | null) as Record<string, ClosureValueType>,\n descriptors,\n ) as Record<string, ClosureValueType>;\n}\n\nfunction isMainThreadObjectDescriptor(\n value: object,\n): value is WorkletRefImpl<unknown> {\n const descriptor = value as Partial<WorkletRefImpl<unknown>>;\n return typeof descriptor._wvid === 'number'\n && typeof descriptor._type === 'string'\n && descriptor._type !== 'main-thread';\n}\nexport { initWorklet };\n"]}
@@ -18,7 +18,7 @@
18
18
  "build": "tsc6 --build",
19
19
  "test": "pnpm run test:snapshot && pnpm run test:et",
20
20
  "test:et": "vitest run -c __test__/element-template/vitest.config.ts --coverage",
21
- "test:snapshot": "vitest run --coverage __test__/snapshot __test__/core __test__/worklet-runtime __test__/guardrails"
21
+ "test:snapshot": "vitest run --coverage __test__/snapshot __test__/core __test__/shared __test__/worklet-runtime __test__/guardrails"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@lynx-js/react": "workspace:*",
@@ -31,6 +31,5 @@
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@types/react": "^18.0.0 || ^19.0.0"
34
- },
35
- "showcase": "__fake_entry__/showcase.js"
34
+ }
36
35
  }
@@ -4,12 +4,21 @@
4
4
 
5
5
  import { IndexMap } from '../../shared/index-map.js';
6
6
  import type { JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.js';
7
+ import { cardLifetime } from '../card-lifetime.js';
7
8
 
8
9
  /**
9
10
  * Keeps the background-thread worklet ctx alive while main thread still holds
10
11
  * a handle to one of its background functions.
11
12
  */
12
13
  export class BackgroundFunctionExecMap extends IndexMap<Worklet> {
14
+ constructor() {
15
+ super(cardLifetime('backgroundFunctionCtxId', () => ({ lastIndex: 0 })));
16
+ }
17
+
18
+ public clear(): void {
19
+ this.indexMap.clear();
20
+ }
21
+
13
22
  public override add(worklet: Worklet): number {
14
23
  const execId = super.add(worklet);
15
24
  worklet._execId = execId;
@@ -8,7 +8,8 @@ import { delayRunOnBackground } from '../../worklet-runtime/bindings/bindings.js
8
8
  import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
9
9
  import type { RunWorkletCtxRetData } from '../../worklet-runtime/bindings/events.js';
10
10
  import type { ClosureValueType, JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.js';
11
- import { registerDestroyTask } from '../runtime-destroy.js';
11
+ import { addReloadScopedEventListener, dispatchReloadScopedEvent } from '../reload-scoped-event.js';
12
+ import { isRuntimeDestroyed, registerDestroyTask } from '../runtime-destroy.js';
12
13
  import { onFunctionCall } from '../thread-function-call/return-value.js';
13
14
 
14
15
  /**
@@ -26,19 +27,19 @@ let unregisterBackgroundFunctionCleanup: (() => void) | undefined;
26
27
 
27
28
  function initBackgroundFunctionRuntime(): void {
28
29
  'background only';
29
- if (execIdMap) {
30
+ if (cleanupBackgroundFunctionRuntime) {
30
31
  return;
31
32
  }
32
33
 
33
- execIdMap = new BackgroundFunctionExecMap();
34
+ execIdMap ??= new BackgroundFunctionExecMap();
34
35
  const context = lynx.getCoreContext();
35
- context.addEventListener(WorkletEvents.runOnBackground, runBackgroundFunction);
36
+ const removeListener = addReloadScopedEventListener(context, WorkletEvents.runOnBackground, runBackgroundFunction);
36
37
  context.addEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);
37
38
 
38
39
  cleanupBackgroundFunctionRuntime = () => {
39
- context.removeEventListener(WorkletEvents.runOnBackground, runBackgroundFunction);
40
+ removeListener();
40
41
  context.removeEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);
41
- execIdMap = undefined;
42
+ execIdMap!.clear();
42
43
  cleanupBackgroundFunctionRuntime = undefined;
43
44
  };
44
45
  }
@@ -46,21 +47,17 @@ function initBackgroundFunctionRuntime(): void {
46
47
  /**
47
48
  * @internal
48
49
  */
49
- export function runBackgroundFunction(event: RuntimeProxy.Event): void {
50
+ export function runBackgroundFunction(data: RunOnBackgroundData): void {
50
51
  'background only';
51
- const data = JSON.parse(event.data as string) as RunOnBackgroundData;
52
52
  const obj = execIdMap!.findJsFnHandle(data.obj._execId!, data.obj._jsFnId!);
53
53
  const f = obj?._fn;
54
54
  if (!f) {
55
55
  throw new Error('runOnBackground: JS function not found: ' + JSON.stringify(data.obj));
56
56
  }
57
57
  const returnValue = f(...data.params);
58
- lynx.getCoreContext().dispatchEvent({
58
+ dispatchReloadScopedEvent(lynx.getCoreContext(), {
59
59
  type: WorkletEvents.FunctionCallRet,
60
- data: JSON.stringify({
61
- resolveId: data.resolveId,
62
- returnValue,
63
- } as RunWorkletCtxRetData),
60
+ data: { resolveId: data.resolveId, returnValue } satisfies RunWorkletCtxRetData,
64
61
  });
65
62
  }
66
63
 
@@ -133,6 +130,7 @@ export function runOnBackground<R, Fn extends (...args: any[]) => R>(
133
130
  }
134
131
  return async (...params: ClosureValueType[]): Promise<R> => {
135
132
  return new Promise((resolve) => {
133
+ if (isRuntimeDestroyed()) return;
136
134
  const resolveId = onFunctionCall(resolve);
137
135
 
138
136
  if (obj._isFirstScreen) {
@@ -153,15 +151,15 @@ function dispatchRunBackgroundFunctionEvent(
153
151
  execId: number,
154
152
  resolveId: number,
155
153
  ): void {
156
- lynx.getJSContext().dispatchEvent({
154
+ dispatchReloadScopedEvent(lynx.getJSContext(), {
157
155
  type: WorkletEvents.runOnBackground,
158
- data: JSON.stringify({
156
+ data: {
159
157
  obj: {
160
158
  _jsFnId: fnId,
161
159
  _execId: execId,
162
160
  },
163
161
  params,
164
162
  resolveId,
165
- } as RunOnBackgroundData),
163
+ } as RunOnBackgroundData,
166
164
  });
167
165
  }
@@ -8,7 +8,8 @@ import { isMainThreadObjectHandle } from './main-thread-object-handle-registry.j
8
8
  * Preserve opaque main-thread object handles when the worklet transform narrows a
9
9
  * captured member expression. Ordinary objects keep the transform's compact
10
10
  * fallback shape. The transform evaluates that shape lazily with
11
- * `captureMainThreadObject(source) ?? fallback`.
11
+ * `captureMainThreadObject(source) ?? fallback` (and guards optional-chain
12
+ * bases with `source == null ? source : ...`).
12
13
  *
13
14
  * @internal
14
15
  */
@@ -0,0 +1,18 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ const storeKey = Symbol.for('__REACT_LYNX_CARD_LIFETIME__');
6
+
7
+ /**
8
+ * Module-level state that survives an entry re-evaluation, for state tied to
9
+ * native objects that outlive the entry or IDs that late messages may carry.
10
+ */
11
+ export function cardLifetime<T extends object>(key: string, init: () => T): T {
12
+ if (typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ === 'undefined' || !__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__) {
13
+ return init();
14
+ }
15
+ const host = lynx as unknown as Record<symbol, Record<string, object> | undefined>;
16
+ const store = host[storeKey] ??= {};
17
+ return (store[key] ??= init()) as T;
18
+ }
@@ -17,7 +17,7 @@ export { ComponentFromReactRuntime as Component } from './lynxComponent.js';
17
17
  export { ComponentFromReactRuntime as PureComponent } from './lynxComponent.js';
18
18
  export { createContext } from 'preact';
19
19
  export { lazy } from 'preact/compat';
20
- export { useState, useReducer, useEffect, useMemo, useCallback /*, useInstance */ } from '../hooks/react.js';
20
+ export { useState, useReducer, useEffect, useMemo, useCallback } from '../hooks/react.js';
21
21
  export { __runInJS, createRef, useRef };
22
22
 
23
23
  /**
@@ -0,0 +1,63 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import { increaseReloadVersion } from './reload-version.js';
6
+ import { destroyRuntime } from './runtime-destroy.js';
7
+
8
+ const supportsReEvalKey = Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__');
9
+ const reloaderKey = Symbol.for('__LYNX_MAIN_THREAD_ENTRY_RELOADER__');
10
+ const completerKey = Symbol.for('__LYNX_MAIN_THREAD_RELOAD_COMPLETER__');
11
+ const externalGlobalKey = Symbol.for('__LYNX_EXTERNAL_GLOBAL__');
12
+
13
+ const host = () => lynx as unknown as Record<symbol, unknown>;
14
+
15
+ function isEntryReEvalEnabled(): boolean {
16
+ return typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ !== 'undefined'
17
+ && __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__
18
+ && host()[supportsReEvalKey] === true;
19
+ }
20
+
21
+ export function canReEvalMainThreadEntry(): boolean {
22
+ return isEntryReEvalEnabled() && typeof host()[reloaderKey] === 'function';
23
+ }
24
+
25
+ export function canReEvalBackgroundEntry(): boolean {
26
+ return isEntryReEvalEnabled() && typeof lynx.getApp().reloadCard === 'function';
27
+ }
28
+
29
+ /** Lets the entry being evaluated finish a reload started by the previous one. */
30
+ export function installMainThreadReloadCompleter<Handoff>(complete: (handoff: Handoff) => void): void {
31
+ if (
32
+ typeof __MAIN_THREAD__ !== 'undefined' && __MAIN_THREAD__
33
+ && typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ !== 'undefined' && __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__
34
+ ) {
35
+ host()[completerKey] = complete;
36
+ }
37
+ }
38
+
39
+ export function reEvalMainThreadEntry<Handoff>(handoff: Handoff): void {
40
+ // Evaluating the entry resets `__initData`.
41
+ const initData = lynx.__initData;
42
+ destroyRuntime();
43
+ Reflect.deleteProperty(lynx, externalGlobalKey);
44
+ (host()[reloaderKey] as () => void)();
45
+ lynx.__initData = initData;
46
+ (host()[completerKey] as (handoff: Handoff) => void)(handoff);
47
+ }
48
+
49
+ /** @param retire - stops this entry from sending work to the main thread */
50
+ export function reEvalBackgroundEntry(
51
+ updateData: Record<string, unknown>,
52
+ options: Record<string, unknown> | undefined,
53
+ retire: () => void,
54
+ ): void {
55
+ const data = Object.assign({}, lynx.__initData, updateData);
56
+ destroyRuntime();
57
+ increaseReloadVersion();
58
+ retire();
59
+ const app = lynx.getApp();
60
+ app.callDestroyLifetimeFun();
61
+ Reflect.deleteProperty(lynx, externalGlobalKey);
62
+ app.reloadCard!(data, options);
63
+ }