@lynx-js/react 0.128.0 → 0.129.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/components/tsconfig.tsbuildinfo +1 -1
  3. package/package.json +1 -1
  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/reload-scoped-dual-thread-communication.test.ts +129 -0
  7. package/runtime/__test__/core/thread-function-call.test.ts +1 -0
  8. package/runtime/__test__/element-template/fixtures/background/render/_shared.tsx +2 -0
  9. package/runtime/__test__/element-template/native/index.test.ts +8 -0
  10. package/runtime/__test__/element-template/native/main-thread-ref-init-value.test.ts +100 -0
  11. package/runtime/__test__/element-template/native/reload-dual-thread-communication.test.ts +101 -0
  12. package/runtime/__test__/element-template/native/reload.test.ts +50 -1
  13. package/runtime/__test__/element-template/runtime/background/commit-hook.test.ts +104 -47
  14. package/runtime/__test__/element-template/runtime/background/main-thread-function/compiled-fixtures.test.tsx +7 -1
  15. package/runtime/__test__/element-template/runtime/background/re-eval-reload.test.ts +69 -0
  16. package/runtime/__test__/element-template/runtime/hydration/hydration-listener.test.ts +31 -5
  17. package/runtime/__test__/element-template/runtime/patch/element-template-patch.test.tsx +17 -3
  18. package/runtime/__test__/element-template/runtime/render/render-transform.contract.test.ts +2 -0
  19. package/runtime/__test__/element-template/runtime/template/main-thread-function.test.ts +89 -2
  20. package/runtime/__test__/element-template/test-utils/debug/compiledFixtureModule.ts +5 -0
  21. package/runtime/__test__/snapshot/lifecycle/re-eval-reload.test.jsx +114 -0
  22. package/runtime/__test__/snapshot/lifecycle/reload-background-function.test.jsx +169 -0
  23. package/runtime/__test__/snapshot/lifecycle/reload-delayed-background.test.jsx +63 -0
  24. package/runtime/__test__/snapshot/lifecycle/reload-delayed-main-thread.test.jsx +103 -0
  25. package/runtime/__test__/snapshot/lifecycle.test.jsx +61 -1
  26. package/runtime/__test__/snapshot/lynx/lazy-effect-scheduling.test.jsx +105 -0
  27. package/runtime/__test__/snapshot/ssr.test.jsx +2 -2
  28. package/runtime/__test__/snapshot/worklet/runOnBackground.test.js +6 -11
  29. package/runtime/__test__/snapshot/worklet/runOnMainThread.test.jsx +1 -1
  30. package/runtime/__test__/snapshot/worklet/workletRef.test.jsx +24 -1
  31. package/runtime/__test__/worklet-runtime/jsFunctionLifecycle.test.js +15 -1
  32. package/runtime/__test__/worklet-runtime/mainThreadObject.test.js +46 -0
  33. package/runtime/__test__/worklet-runtime/runOnMainThread.test.js +3 -3
  34. package/runtime/lib/core/background-function/exec-map.d.ts +2 -0
  35. package/runtime/lib/core/background-function/exec-map.js +7 -0
  36. package/runtime/lib/core/background-function/exec-map.js.map +1 -1
  37. package/runtime/lib/core/background-function/run-on-background.js +15 -16
  38. package/runtime/lib/core/background-function/run-on-background.js.map +1 -1
  39. package/runtime/lib/core/card-lifetime.d.ts +5 -0
  40. package/runtime/lib/core/card-lifetime.js +17 -0
  41. package/runtime/lib/core/card-lifetime.js.map +1 -0
  42. package/runtime/lib/core/entry-reload.d.ts +7 -0
  43. package/runtime/lib/core/entry-reload.js +49 -0
  44. package/runtime/lib/core/entry-reload.js.map +1 -0
  45. package/runtime/lib/core/lynx/lazy-bundle.js +4 -1
  46. package/runtime/lib/core/lynx/lazy-bundle.js.map +1 -1
  47. package/runtime/lib/core/main-thread-ref-id.js +4 -4
  48. package/runtime/lib/core/main-thread-ref-id.js.map +1 -1
  49. package/runtime/lib/core/reload-scoped-event.d.ts +5 -0
  50. package/runtime/lib/core/reload-scoped-event.js +26 -0
  51. package/runtime/lib/core/reload-scoped-event.js.map +1 -0
  52. package/runtime/lib/core/reload-version.js +4 -3
  53. package/runtime/lib/core/reload-version.js.map +1 -1
  54. package/runtime/lib/core/runtime-destroy.d.ts +2 -0
  55. package/runtime/lib/core/runtime-destroy.js +9 -0
  56. package/runtime/lib/core/runtime-destroy.js.map +1 -1
  57. package/runtime/lib/core/thread-function-call/main-thread.js +5 -4
  58. package/runtime/lib/core/thread-function-call/main-thread.js.map +1 -1
  59. package/runtime/lib/core/thread-function-call/return-value.js +6 -5
  60. package/runtime/lib/core/thread-function-call/return-value.js.map +1 -1
  61. package/runtime/lib/element-template/background/commit-hook.js +19 -16
  62. package/runtime/lib/element-template/background/commit-hook.js.map +1 -1
  63. package/runtime/lib/element-template/background/hydration-listener.js +2 -6
  64. package/runtime/lib/element-template/background/hydration-listener.js.map +1 -1
  65. package/runtime/lib/element-template/main-thread-ref-init-value.d.ts +3 -0
  66. package/runtime/lib/element-template/main-thread-ref-init-value.js +38 -0
  67. package/runtime/lib/element-template/main-thread-ref-init-value.js.map +1 -0
  68. package/runtime/lib/element-template/native/index.js +2 -0
  69. package/runtime/lib/element-template/native/index.js.map +1 -1
  70. package/runtime/lib/element-template/native/mts-destroy.js +2 -0
  71. package/runtime/lib/element-template/native/mts-destroy.js.map +1 -1
  72. package/runtime/lib/element-template/native/patch-listener.js +1 -4
  73. package/runtime/lib/element-template/native/patch-listener.js.map +1 -1
  74. package/runtime/lib/element-template/native/reload-background.d.ts +1 -1
  75. package/runtime/lib/element-template/native/reload-background.js +12 -1
  76. package/runtime/lib/element-template/native/reload-background.js.map +1 -1
  77. package/runtime/lib/element-template/native/reload-main-thread.d.ts +6 -0
  78. package/runtime/lib/element-template/native/reload-main-thread.js +18 -2
  79. package/runtime/lib/element-template/native/reload-main-thread.js.map +1 -1
  80. package/runtime/lib/element-template/protocol/lifecycle-constant.d.ts +2 -1
  81. package/runtime/lib/element-template/protocol/lifecycle-constant.js +1 -0
  82. package/runtime/lib/element-template/protocol/lifecycle-constant.js.map +1 -1
  83. package/runtime/lib/element-template/protocol/types.d.ts +0 -2
  84. package/runtime/lib/element-template/protocol/types.js.map +1 -1
  85. package/runtime/lib/shared/index-map.d.ts +4 -1
  86. package/runtime/lib/shared/index-map.js +5 -2
  87. package/runtime/lib/shared/index-map.js.map +1 -1
  88. package/runtime/lib/snapshot/lifecycle/destroy.js +6 -0
  89. package/runtime/lib/snapshot/lifecycle/destroy.js.map +1 -1
  90. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.d.ts +6 -2
  91. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.js +21 -18
  92. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.js.map +1 -1
  93. package/runtime/lib/snapshot/lifecycle/reload.d.ts +9 -2
  94. package/runtime/lib/snapshot/lifecycle/reload.js +29 -8
  95. package/runtime/lib/snapshot/lifecycle/reload.js.map +1 -1
  96. package/runtime/lib/snapshot/list/list.js +3 -2
  97. package/runtime/lib/snapshot/list/list.js.map +1 -1
  98. package/runtime/lib/snapshot/lynx/calledByNative.js +3 -3
  99. package/runtime/lib/snapshot/lynx/calledByNative.js.map +1 -1
  100. package/runtime/lib/snapshot/snapshot/list.js +2 -1
  101. package/runtime/lib/snapshot/snapshot/list.js.map +1 -1
  102. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.d.ts +4 -2
  103. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.js +11 -11
  104. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.js.map +1 -1
  105. package/runtime/lib/snapshot/worklet/call/runOnMainThread.d.ts +1 -0
  106. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js +6 -1
  107. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js.map +1 -1
  108. package/runtime/lib/snapshot/worklet/ctx.d.ts +1 -1
  109. package/runtime/lib/snapshot/worklet/ctx.js +6 -1
  110. package/runtime/lib/snapshot/worklet/ctx.js.map +1 -1
  111. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js +6 -0
  112. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js.map +1 -1
  113. package/runtime/lib/tsconfig.tsbuildinfo +1 -1
  114. package/runtime/lib/worklet-runtime/delayRunOnBackground.js +3 -1
  115. package/runtime/lib/worklet-runtime/delayRunOnBackground.js.map +1 -1
  116. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js +2 -1
  117. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js.map +1 -1
  118. package/runtime/lib/worklet-runtime/listeners.js +2 -2
  119. package/runtime/lib/worklet-runtime/listeners.js.map +1 -1
  120. package/runtime/lib/worklet-runtime/mainThreadObject.js +3 -1
  121. package/runtime/lib/worklet-runtime/mainThreadObject.js.map +1 -1
  122. package/runtime/lib/worklet-runtime/runOnMainThread.js +4 -3
  123. package/runtime/lib/worklet-runtime/runOnMainThread.js.map +1 -1
  124. package/runtime/src/core/background-function/exec-map.ts +9 -0
  125. package/runtime/src/core/background-function/run-on-background.ts +14 -16
  126. package/runtime/src/core/card-lifetime.ts +18 -0
  127. package/runtime/src/core/entry-reload.ts +63 -0
  128. package/runtime/src/core/lynx/lazy-bundle.ts +4 -1
  129. package/runtime/src/core/main-thread-ref-id.ts +5 -4
  130. package/runtime/src/core/reload-scoped-event.ts +35 -0
  131. package/runtime/src/core/reload-version.ts +5 -3
  132. package/runtime/src/core/runtime-destroy.ts +11 -0
  133. package/runtime/src/core/thread-function-call/main-thread.ts +4 -4
  134. package/runtime/src/core/thread-function-call/return-value.ts +6 -5
  135. package/runtime/src/element-template/background/commit-hook.ts +20 -17
  136. package/runtime/src/element-template/background/hydration-listener.ts +2 -6
  137. package/runtime/src/element-template/main-thread-ref-init-value.ts +44 -0
  138. package/runtime/src/element-template/native/index.ts +2 -0
  139. package/runtime/src/element-template/native/mts-destroy.ts +3 -0
  140. package/runtime/src/element-template/native/patch-listener.ts +0 -5
  141. package/runtime/src/element-template/native/reload-background.ts +13 -1
  142. package/runtime/src/element-template/native/reload-main-thread.ts +30 -2
  143. package/runtime/src/element-template/protocol/lifecycle-constant.ts +1 -0
  144. package/runtime/src/element-template/protocol/types.ts +0 -2
  145. package/runtime/src/shared/index-map.ts +3 -2
  146. package/runtime/src/snapshot/lifecycle/destroy.ts +7 -0
  147. package/runtime/src/snapshot/lifecycle/event/firstScreenSync.ts +26 -19
  148. package/runtime/src/snapshot/lifecycle/reload.ts +47 -11
  149. package/runtime/src/snapshot/list/list.ts +9 -2
  150. package/runtime/src/snapshot/lynx/calledByNative.ts +3 -4
  151. package/runtime/src/snapshot/snapshot/list.ts +5 -1
  152. package/runtime/src/snapshot/snapshot/snapshotInstanceManager.ts +19 -12
  153. package/runtime/src/snapshot/worklet/call/runOnMainThread.ts +10 -1
  154. package/runtime/src/snapshot/worklet/ctx.ts +10 -1
  155. package/runtime/src/snapshot/worklet/ref/updateInitValue.ts +6 -0
  156. package/runtime/src/worklet-runtime/README.md +13 -0
  157. package/runtime/src/worklet-runtime/delayRunOnBackground.ts +3 -1
  158. package/runtime/src/worklet-runtime/jsFunctionLifecycle.ts +2 -1
  159. package/runtime/src/worklet-runtime/listeners.ts +4 -7
  160. package/runtime/src/worklet-runtime/mainThreadObject.ts +2 -1
  161. package/runtime/src/worklet-runtime/runOnMainThread.ts +4 -3
  162. package/runtime/types/types.d.ts +3 -1
  163. package/testing-library/.turbo/turbo-build.log +7 -7
  164. package/testing-library/src/__tests__/worklet.test.jsx +10 -5
  165. package/transform/.turbo/turbo-build$colon$wasm.log +339 -134
  166. package/transform/__test__/defines.spec.js +107 -0
  167. package/transform/crates/swc_plugin_worklet/definition_imports.rs +97 -0
  168. package/transform/crates/swc_plugin_worklet/lib.rs +7 -6
  169. package/transform/dist/wasm.cjs +1 -1
  170. package/transform/index.d.ts +3 -1
  171. package/transform/src/lib.rs +172 -11
  172. package/transform/swc-plugin-reactlynx/.turbo/turbo-build.log +57 -55
  173. package/transform/swc-plugin-reactlynx/swc_plugin_reactlynx.wasm +0 -0
  174. package/transform/swc-plugin-reactlynx-compat/.turbo/turbo-build.log +66 -274
@@ -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"]}
@@ -23,9 +23,10 @@ class JsFunctionLifecycleManager {
23
23
  if (this.retainedObjects.has(objToRef)) {
24
24
  return;
25
25
  }
26
+ // A failed engine registration must leave the target eligible for a retry.
27
+ this.registry.register(objToRef, execId);
26
28
  this.retainedObjects.add(objToRef);
27
29
  this.execIdRefCount.set(execId, (this.execIdRefCount.get(execId) ?? 0) + 1);
28
- this.registry.register(objToRef, execId);
29
30
  }
30
31
  removeRef(execId) {
31
32
  const rc = this.execIdRefCount.get(execId);
@@ -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,EA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EAAE;gBAC/B,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI;QACF,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 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"]}
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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C;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 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 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"]}
@@ -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 +1 @@
1
- {"version":3,"file":"mainThreadObject.js","sourceRoot":"","sources":["../../src/worklet-runtime/mainThreadObject.ts"],"names":[],"mappings":"AAWA,MAAM,2BAA2B,GAAG,IAAI,GAAG,EAAsC,CAAC;AAClF,8EAA8E;AAC9E,iFAAiF;AACjF,IAAI,6BAA6B,GAAG,IAAI,OAAO,EAAkB,CAAC;AAElE,SAAS,4BAA4B,CACnC,IAAY,EACZ,MAAyC;IAEzC,IAAI,IAAI,KAAK,aAAa,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;IACJ,CAAC;IACD,MAAM,UAAU,GAAG,2BAA2B,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACzD,IAAI,UAAU,EAAE,CAAC;QACf,IACE,8BAA8B,CAAC,UAAU,CAAC,MAAM,CAAC;gBAC3C,8BAA8B,CAAC,MAAM,CAAC,EAC5C,CAAC;YACD,MAAM,IAAI,KAAK,CACb,uDAAuD,IAAI,yDAAyD,CACrH,CAAC;QACJ,CAAC;QACD,OAAO;IACT,CAAC;IACD,2BAA2B,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,8BAA8B,CACrC,OAA0C;IAE1C,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,OAAO,QAAQ,CAAC,SAAS,CA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A0B,CAAC,KAAa;IAC/C,OAAO,6BAA6B,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,gCAAgC,CACvC,MAA+B,EAC/B,KAAa,EACb,SAA+C;IAE/C,MAAM,UAAU,GAAG,6BAA6B,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC5D,MAAM,YAAY,GAAG,MAAM,CAAC,KAAM,CAAC;IACnC,IAAI,UAAU,KAAK,YAAY,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,yCAAyC,SAAS,eAAe,MAAM,CAAC,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"],"names":[],"mappings":"AAWA,MAAM,2BAA2B,GAAG,IAAI,GAAG,EAAsC,CAAC;AAClF,8EAA8E;AAC9E,iFAAiF;AACjF,IAAI,6BAA6B,GAAG,IAAI,OAAO,EAAkB,CAAC;AAElE,SAAS,4BAA4B,CACnC,IAAY,EACZ,MAAyC;IAEzC,IAAI,IAAI,KAAK,aAAa,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;IACJ,CAAC;IACD,MAAM,UAAU,GAAG,2BAA2B,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACzD,IAAI,UAAU,EAAE,CAAC;QACf,IACE,8BAA8B,CAAC,UAAU,CAAC,MAAM,CAAC;gBAC3C,8BAA8B,CAAC,MAAM,CAAC,EAC5C,CAAC;YACD,MAAM,IAAI,KAAK,CACb,uDAAuD,IAAI,yDAAyD,CACrH,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,MAAM,KAAK,MAAM;YAAE,OAAO;IAC3C,CAAC;IACD,wEAAwE;IACxE,2BAA2B,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,8BAA8B,CACrC,OAA0C;IAE1C,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,OAAO,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,I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AC/C,OAAO,6BAA6B,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,gCAAgC,CACvC,MAA+B,EAC/B,KAAa,EACb,SAA+C;IAE/C,MAAM,UAAU,GAAG,6BAA6B,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC5D,MAAM,YAAY,GAAG,MAAM,CAAC,KAAM,CAAC;IACnC,IAAI,UAAU,KAAK,YAAY,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,yCAAyC,SAAS,eAAe,MAAM,CAAC,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 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"]}
@@ -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
  }
@@ -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
+ }
@@ -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
+ }
@@ -62,7 +62,10 @@ export const makeSyncThen = function<T>(result: T): Promise<T>['then'] {
62
62
  // );
63
63
  }
64
64
 
65
- const p = Promise.resolve(ret);
65
+ // The Lynx Promise polyfill shares resolved promises for primitive values.
66
+ // Own this promise before replacing `then`, or an undefined callback
67
+ // result would make unrelated Promise.resolve().then(...) calls synchronous.
68
+ const p = new Promise<TR1>(resolve => resolve(ret));
66
69
 
67
70
  const then = makeSyncThen(ret as TR1);
68
71
  p.then = then as Promise<Awaited<TR1>>['then'];
@@ -2,15 +2,16 @@
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
4
 
5
- let lastIdBG = 0;
6
- let lastIdMT = 0;
5
+ import { cardLifetime } from './card-lifetime.js';
6
+
7
+ const lastId = /*#__PURE__*/ cardLifetime('mainThreadRefId', () => ({ bg: 0, mt: 0 }));
7
8
 
8
9
  /** @internal */
9
10
  export function allocateMainThreadRefId(): number {
10
- return __JS__ ? ++lastIdBG : --lastIdMT;
11
+ return __JS__ ? ++lastId.bg : --lastId.mt;
11
12
  }
12
13
 
13
14
  /** @internal */
14
15
  export function clearMainThreadRefIdsForTesting(): void {
15
- lastIdBG = lastIdMT = 0;
16
+ lastId.bg = lastId.mt = 0;
16
17
  }
@@ -0,0 +1,35 @@
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 { getReloadVersion } from './reload-version.js';
6
+
7
+ interface ReloadScope {
8
+ reloadVersion?: number | undefined;
9
+ }
10
+
11
+ export function dispatchReloadScopedEvent(context: RuntimeProxy, event: { type: string; data: object }): void {
12
+ context.dispatchEvent({
13
+ type: event.type,
14
+ data: JSON.stringify({ ...event.data, reloadVersion: getReloadVersion() }),
15
+ });
16
+ }
17
+
18
+ // Deliver parsed payloads only while their page is current. Return cleanup for
19
+ // the actual registered wrapper, so callers need no listener identity registry.
20
+ export function addReloadScopedEventListener<T>(
21
+ context: RuntimeProxy,
22
+ type: string,
23
+ listener: (data: T) => void,
24
+ ): () => void {
25
+ const handle = (event: RuntimeProxy.Event): void => {
26
+ const data = JSON.parse(event.data as string) as T & ReloadScope;
27
+ // Unversioned events belong to the initial page only.
28
+ if ((data.reloadVersion ?? 0) !== getReloadVersion()) return;
29
+ listener(data);
30
+ };
31
+ context.addEventListener(type, handle);
32
+ return () => {
33
+ context.removeEventListener(type, handle);
34
+ };
35
+ }
@@ -2,12 +2,14 @@
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
4
 
5
- let reloadVersion = 0;
5
+ import { cardLifetime } from './card-lifetime.js';
6
+
7
+ const state = /*#__PURE__*/ cardLifetime('reloadVersion', () => ({ value: 0 }));
6
8
 
7
9
  export function getReloadVersion(): number {
8
- return reloadVersion;
10
+ return state.value;
9
11
  }
10
12
 
11
13
  export function increaseReloadVersion(): number {
12
- return ++reloadVersion;
14
+ return ++state.value;
13
15
  }
@@ -5,6 +5,17 @@
5
5
  type DestroyTask = () => void;
6
6
 
7
7
  const destroyTasks = new Set<DestroyTask>();
8
+ let destroyed = false;
9
+
10
+ // Calls from a retired entry stay pending: settling them would run its continuations.
11
+ export function isRuntimeDestroyed(): boolean {
12
+ return destroyed;
13
+ }
14
+
15
+ export function destroyRuntime(): void {
16
+ destroyed = true;
17
+ runDestroyTasks();
18
+ }
8
19
 
9
20
  export function registerDestroyTask(task: DestroyTask): () => void {
10
21
  destroyTasks.add(task);
@@ -10,6 +10,8 @@ import type { Worklet } from '../../worklet-runtime/bindings/types.js';
10
10
  import { registerBackgroundFunctionCtx } from '../background-function/run-on-background.js';
11
11
  import { isMainThreadFunction } from '../main-thread-function.js';
12
12
  import { isMtsEnabled } from '../mts-capability.js';
13
+ import { dispatchReloadScopedEvent } from '../reload-scoped-event.js';
14
+ import { isRuntimeDestroyed } from '../runtime-destroy.js';
13
15
 
14
16
  interface RunOnMainThreadOptions {
15
17
  shouldDispatchRunOnMainThreadDirectly: () => boolean;
@@ -44,6 +46,7 @@ export function createRunOnMainThread(
44
46
  }
45
47
  return async (...params: Parameters<Fn>): Promise<R> => {
46
48
  return new Promise((resolve) => {
49
+ if (isRuntimeDestroyed()) return;
47
50
  const worklet = fn as unknown as Worklet;
48
51
  prepareMainThreadFunctionCtx(worklet);
49
52
  const data = {
@@ -74,8 +77,5 @@ function prepareMainThreadFunctionCtx(worklet: unknown): void {
74
77
  }
75
78
 
76
79
  function dispatchRunOnMainThreadEvent(data: RunWorkletCtxData): void {
77
- lynx.getCoreContext().dispatchEvent({
78
- type: WorkletEvents.runWorkletCtx,
79
- data: JSON.stringify(data),
80
- });
80
+ dispatchReloadScopedEvent(lynx.getCoreContext(), { type: WorkletEvents.runWorkletCtx, data });
81
81
  }
@@ -5,6 +5,8 @@
5
5
  import { IndexMap } from '../../shared/index-map.js';
6
6
  import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
7
7
  import type { RunWorkletCtxRetData } from '../../worklet-runtime/bindings/events.js';
8
+ import { cardLifetime } from '../card-lifetime.js';
9
+ import { addReloadScopedEventListener } from '../reload-scoped-event.js';
8
10
  import { registerDestroyTask } from '../runtime-destroy.js';
9
11
 
10
12
  let resolveMap: IndexMap<(value: any) => void> | undefined;
@@ -14,11 +16,11 @@ let unregisterReturnValueCleanup: (() => void) | undefined;
14
16
  function initReturnValueListener(): void {
15
17
  const context: RuntimeProxy = __JS__ ? lynx.getCoreContext() : lynx.getJSContext();
16
18
 
17
- resolveMap = new IndexMap();
18
- context.addEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
19
+ resolveMap = new IndexMap(cardLifetime('functionCallId', () => ({ lastIndex: 0 })));
20
+ const removeListener = addReloadScopedEventListener(context, WorkletEvents.FunctionCallRet, onFunctionCallRet);
19
21
 
20
22
  cleanupReturnValueListener = () => {
21
- context.removeEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
23
+ removeListener();
22
24
  resolveMap = undefined;
23
25
  cleanupReturnValueListener = undefined;
24
26
  };
@@ -62,8 +64,7 @@ export function dropFunctionCallReturnIds(resolveIds: readonly number[]): void {
62
64
  }
63
65
  }
64
66
 
65
- function onFunctionCallRet(event: RuntimeProxy.Event): void {
66
- const data = JSON.parse(event.data as string) as RunWorkletCtxRetData;
67
+ function onFunctionCallRet(data: RunWorkletCtxRetData): void {
67
68
  const map = resolveMap;
68
69
  if (!map) {
69
70
  return;
@@ -11,7 +11,6 @@ import {
11
11
  } from './commit-context.js';
12
12
  import type { BackgroundElementTemplateInstance } from './instance.js';
13
13
  import { clearElementTemplateRenderScope, resetElementTemplateRenderScope } from './render-scope.js';
14
- import { takeMainThreadRefInitValuePatch } from '../../core/main-thread-ref-init-value.js';
15
14
  import { globalPipelineOptions, markTiming, markTimingLegacy, setPipeline } from '../../core/performance.js';
16
15
  import { getReloadVersion } from '../../core/reload-version.js';
17
16
  import {
@@ -21,9 +20,9 @@ import {
21
20
  import { dropFunctionCallReturnIds } from '../../core/thread-function-call/return-value.js';
22
21
  import { COMMIT } from '../../shared/render-constants.js';
23
22
  import { hook, isEmptyObject } from '../../utils.js';
24
- import type { MainThreadRefInitValuePatch } from '../../worklet-runtime/bindings/types.js';
25
23
  import { formatElementTemplateUpdateCommands } from '../debug/alog.js';
26
24
  import { profileEnd, profileStart } from '../debug/profile.js';
25
+ import { sendMTRefInitValueToMainThread } from '../main-thread-ref-init-value.js';
27
26
  import { clearPendingRefs, flushPendingRefs, hasPendingRefs } from '../prop-adapters/ref.js';
28
27
  import { createElementTemplateUpdateEvent } from '../protocol/update-event.js';
29
28
 
@@ -68,14 +67,12 @@ export function cancelElementTemplateRemovedSubtreeCleanup(): void {
68
67
  scheduledRemovedSubtreeCleanupTimers.clear();
69
68
  }
70
69
 
71
- function flushElementTemplateCommitChanges(mainThreadRefInitValuePatch: MainThreadRefInitValuePatch): void {
70
+ function flushElementTemplateCommitChanges(): void {
72
71
  const hasNativeOps = globalCommitContext.ops.length > 0;
73
72
  const hasDelayedRunOnMainThread = delayedRunOnMainThreadData.length > 0;
74
- const hasMainThreadRefInitValuePatch = mainThreadRefInitValuePatch.length > 0;
75
73
  const hasUpdatePayload = hasNativeOps
76
74
  || !isEmptyObject(globalCommitContext.flushOptions)
77
- || hasDelayedRunOnMainThread
78
- || hasMainThreadRefInitValuePatch;
75
+ || hasDelayedRunOnMainThread;
79
76
  const removedSubtreesAwaitingTeardown = hasNativeOps ? takeRemovedSubtreesForPostDispatchTeardown() : [];
80
77
  if (hasUpdatePayload) {
81
78
  markTimingLegacy('updateDiffVdomEnd');
@@ -115,7 +112,6 @@ function flushElementTemplateCommitChanges(mainThreadRefInitValuePatch: MainThre
115
112
  flushOptions: globalCommitContext.flushOptions,
116
113
  flowIds: globalCommitContext.flowIds,
117
114
  delayedRunOnMainThreadDataCount: delayedRunOnMainThreadPayload?.length,
118
- mainThreadRefInitValuePatchCount: mainThreadRefInitValuePatch.length,
119
115
  },
120
116
  null,
121
117
  2,
@@ -129,9 +125,6 @@ function flushElementTemplateCommitChanges(mainThreadRefInitValuePatch: MainThre
129
125
  reloadVersion: getReloadVersion(),
130
126
  flowIds: globalCommitContext.flowIds,
131
127
  delayedRunOnMainThreadData: delayedRunOnMainThreadPayload,
132
- mainThreadRefInitValuePatch: hasMainThreadRefInitValuePatch
133
- ? mainThreadRefInitValuePatch
134
- : undefined,
135
128
  });
136
129
  } catch (error) {
137
130
  if (delayedRunOnMainThreadPayload) {
@@ -166,23 +159,33 @@ export function installElementTemplateCommitHook(): void {
166
159
  hook(options, COMMIT, (originalCommit, vnode, commitQueue) => {
167
160
  if (__BACKGROUND__) {
168
161
  clearElementTemplateRenderScope();
162
+ try {
163
+ sendMTRefInitValueToMainThread();
164
+ } catch (error) {
165
+ const removedSubtreesAwaitingTeardown = takeRemovedSubtreesForPostDispatchTeardown();
166
+ dropFunctionCallReturnIds(takeDelayedRunOnMainThreadData().map(data => data.resolveId));
167
+ clearPendingRefs();
168
+ resetGlobalCommitContext();
169
+ setPipeline(undefined);
170
+ scheduleElementTemplateRemovedSubtreeCleanup(removedSubtreesAwaitingTeardown);
171
+ throw error;
172
+ }
169
173
  }
170
174
 
171
175
  if (__BACKGROUND__ && !hasHydrated && hasPendingRefs()) {
172
176
  // User effects can run before ET hydrate arrives, so ordinary refs must be
173
177
  // attached on the background commit even though native UI ops are delayed.
174
178
  flushPendingRefs();
175
- } else if (__BACKGROUND__ && hasHydrated) {
176
- const mainThreadRefInitValuePatch = takeMainThreadRefInitValuePatch();
177
- if (
179
+ } else if (
180
+ __BACKGROUND__ && hasHydrated
181
+ && (
178
182
  globalCommitContext.ops.length > 0
179
183
  || !isEmptyObject(globalCommitContext.flushOptions)
180
184
  || hasPendingRefs()
181
185
  || delayedRunOnMainThreadData.length > 0
182
- || mainThreadRefInitValuePatch.length > 0
183
- ) {
184
- flushElementTemplateCommitChanges(mainThreadRefInitValuePatch);
185
- }
186
+ )
187
+ ) {
188
+ flushElementTemplateCommitChanges();
186
189
  }
187
190
 
188
191
  originalCommit?.(vnode, commitQueue);