@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
@@ -5,45 +5,42 @@ import { BackgroundFunctionExecMap } from './exec-map.js';
5
5
  import { isSdkVersionGt } from '../../utils.js';
6
6
  import { delayRunOnBackground } from '../../worklet-runtime/bindings/bindings.js';
7
7
  import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
8
- import { registerDestroyTask } from '../runtime-destroy.js';
8
+ import { addReloadScopedEventListener, dispatchReloadScopedEvent } from '../reload-scoped-event.js';
9
+ import { isRuntimeDestroyed, registerDestroyTask } from '../runtime-destroy.js';
9
10
  import { onFunctionCall } from '../thread-function-call/return-value.js';
10
11
  let execIdMap;
11
12
  let cleanupBackgroundFunctionRuntime;
12
13
  let unregisterBackgroundFunctionCleanup;
13
14
  function initBackgroundFunctionRuntime() {
14
15
  'background only';
15
- if (execIdMap) {
16
+ if (cleanupBackgroundFunctionRuntime) {
16
17
  return;
17
18
  }
18
- execIdMap = new BackgroundFunctionExecMap();
19
+ execIdMap ??= new BackgroundFunctionExecMap();
19
20
  const context = lynx.getCoreContext();
20
- context.addEventListener(WorkletEvents.runOnBackground, runBackgroundFunction);
21
+ const removeListener = addReloadScopedEventListener(context, WorkletEvents.runOnBackground, runBackgroundFunction);
21
22
  context.addEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);
22
23
  cleanupBackgroundFunctionRuntime = () => {
23
- context.removeEventListener(WorkletEvents.runOnBackground, runBackgroundFunction);
24
+ removeListener();
24
25
  context.removeEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);
25
- execIdMap = undefined;
26
+ execIdMap.clear();
26
27
  cleanupBackgroundFunctionRuntime = undefined;
27
28
  };
28
29
  }
29
30
  /**
30
31
  * @internal
31
32
  */
32
- export function runBackgroundFunction(event) {
33
+ export function runBackgroundFunction(data) {
33
34
  'background only';
34
- const data = JSON.parse(event.data);
35
35
  const obj = execIdMap.findJsFnHandle(data.obj._execId, data.obj._jsFnId);
36
36
  const f = obj?._fn;
37
37
  if (!f) {
38
38
  throw new Error('runOnBackground: JS function not found: ' + JSON.stringify(data.obj));
39
39
  }
40
40
  const returnValue = f(...data.params);
41
- lynx.getCoreContext().dispatchEvent({
41
+ dispatchReloadScopedEvent(lynx.getCoreContext(), {
42
42
  type: WorkletEvents.FunctionCallRet,
43
- data: JSON.stringify({
44
- resolveId: data.resolveId,
45
- returnValue,
46
- }),
43
+ data: { resolveId: data.resolveId, returnValue },
47
44
  });
48
45
  }
49
46
  function releaseBackgroundFunctionCtx(event) {
@@ -109,6 +106,8 @@ export function runOnBackground(f) {
109
106
  }
110
107
  return async (...params) => {
111
108
  return new Promise((resolve) => {
109
+ if (isRuntimeDestroyed())
110
+ return;
112
111
  const resolveId = onFunctionCall(resolve);
113
112
  if (obj._isFirstScreen) {
114
113
  delayRunOnBackground(obj, (fnId, execId) => {
@@ -121,16 +120,16 @@ export function runOnBackground(f) {
121
120
  };
122
121
  }
123
122
  function dispatchRunBackgroundFunctionEvent(fnId, params, execId, resolveId) {
124
- lynx.getJSContext().dispatchEvent({
123
+ dispatchReloadScopedEvent(lynx.getJSContext(), {
125
124
  type: WorkletEvents.runOnBackground,
126
- data: JSON.stringify({
125
+ data: {
127
126
  obj: {
128
127
  _jsFnId: fnId,
129
128
  _execId: execId,
130
129
  },
131
130
  params,
132
131
  resolveId,
133
- }),
132
+ },
134
133
  });
135
134
  }
136
135
  //# sourceMappingURL=run-on-background.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-on-background.js","sourceRoot":"","sources":["../../../src/core/background-function/run-on-background.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAGzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AAWzE,IAAI,SAAgD,CAAC;AACrD,IAAI,gCAA0D,CAAC;AAC/D,IAAI,mCAA6D,CAAC;AAElE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,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,KAAK,EAAE,GAAG,MAA0B,EAAc,EAAE;QACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,MAAM,SAAS,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;YAE1C,IAAI,GAAG,CAAC,cAAc,EAAE,CAAC;gBACvB,oBAAoB,CAAC,GAAG,EAAE,CAAC,IAAY,EAAE,MAAc,EAAE,EAAE;oBACzD,kCAAkC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;gBACtE,CAAC,CAAC,CAAC;gBACH,OAAO;YACT,CAAC;YAED,kCAAkC,CAAC,GAAG,CAAC,OAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,OAAQ,EAAE,SAAS,CAAC,CAAC;QACpF,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,kCAAkC,CACzC,IAAY,EACZ,MAA0B,EAC1B,MAAc,EACd,SAAiB;IAEjB,IAAI,CAAC,YAAY,EAAE,CAAC,aAAa,CAAC;QAChC,IAAI,EAAE,aAAa,CAAC,eAAe;QACnC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;YACnB,GAAG,EAAE;gBACH,OAAO,EAAE,IAAI;gBACb,OAAO,EAAE,MAAM;aAChB;YACD,MAAM;YACN,SAAS;SACa,CAAC;KAC1B,CAAC,CAAC;AACL,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 { BackgroundFunctionExecMap } from './exec-map.js';\nimport { isSdkVersionGt } from '../../utils.js';\nimport { delayRunOnBackground } from '../../worklet-runtime/bindings/bindings.js';\nimport { WorkletEvents } from '../../worklet-runtime/bindings/events.js';\nimport type { RunWorkletCtxRetData } from '../../worklet-runtime/bindings/events.js';\nimport type { ClosureValueType, JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.js';\nimport { registerDestroyTask } from '../runtime-destroy.js';\nimport { onFunctionCall } from '../thread-function-call/return-value.js';\n\n/**\n * @internal\n */\ninterface RunOnBackgroundData {\n obj: JsFnHandle;\n params: unknown[];\n resolveId: number;\n}\n\nlet execIdMap: BackgroundFunctionExecMap | undefined;\nlet cleanupBackgroundFunctionRuntime: (() => void) | undefined;\nlet unregisterBackgroundFunctionCleanup: (() => void) | undefined;\n\nfunction initBackgroundFunctionRuntime(): void {\n 'background only';\n if (execIdMap) {\n return;\n }\n\n execIdMap = new BackgroundFunctionExecMap();\n const context = lynx.getCoreContext();\n context.addEventListener(WorkletEvents.runOnBackground, runBackgroundFunction);\n context.addEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);\n\n cleanupBackgroundFunctionRuntime = () => {\n context.removeEventListener(WorkletEvents.runOnBackground, runBackgroundFunction);\n context.removeEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);\n execIdMap = undefined;\n cleanupBackgroundFunctionRuntime = undefined;\n };\n}\n\n/**\n * @internal\n */\nexport function runBackgroundFunction(event: RuntimeProxy.Event): void {\n 'background only';\n const data = JSON.parse(event.data as string) as RunOnBackgroundData;\n const obj = execIdMap!.findJsFnHandle(data.obj._execId!, data.obj._jsFnId!);\n const f = obj?._fn;\n if (!f) {\n throw new Error('runOnBackground: JS function not found: ' + JSON.stringify(data.obj));\n }\n const returnValue = f(...data.params);\n lynx.getCoreContext().dispatchEvent({\n type: WorkletEvents.FunctionCallRet,\n data: JSON.stringify({\n resolveId: data.resolveId,\n returnValue,\n } as RunWorkletCtxRetData),\n });\n}\n\nfunction releaseBackgroundFunctionCtx(event: RuntimeProxy.Event): void {\n 'background only';\n for (const id of event.data) {\n execIdMap!.remove(id as number);\n }\n}\n\n/**\n * @internal\n */\nexport function registerBackgroundFunctionCtx(ctx: Worklet): void {\n 'background only';\n initBackgroundFunctionRuntime();\n ensureBackgroundFunctionCleanup();\n execIdMap!.add(ctx);\n}\n\nfunction ensureBackgroundFunctionCleanup(): void {\n if (unregisterBackgroundFunctionCleanup) {\n return;\n }\n unregisterBackgroundFunctionCleanup = registerDestroyTask(() => {\n resetBackgroundFunctionRuntime();\n });\n}\n\nexport function resetBackgroundFunctionRuntime(): void {\n cleanupBackgroundFunctionRuntime?.();\n unregisterBackgroundFunctionCleanup?.();\n unregisterBackgroundFunctionCleanup = undefined;\n}\n\n/**\n * `runOnBackground` allows triggering js functions on the background thread asynchronously.\n * @param f - The js function to be called.\n * @returns A function. Calling which with the arguments to be passed to the js function to trigger it on the background thread. This function returns a promise that resolves to the return value of the js function.\n * @public\n *\n * @example\n *\n * ```ts\n * import { runOnBackground } from '@lynx-js/react';\n *\n * async function someMainthreadFunction() {\n * 'main thread';\n * const fn = runOnBackground(() => {\n * return 'hello';\n * });\n * const result = await fn();\n * }\n * ```\n *\n * @group Functions\n */\nexport function runOnBackground<R, Fn extends (...args: any[]) => R>(\n f: Fn,\n): (...args: Parameters<Fn>) => Promise<R> {\n if (!isSdkVersionGt(2, 15)) {\n throw new Error('runOnBackground requires Lynx sdk version 2.16.');\n }\n if (__JS__) {\n throw new Error('runOnBackground can only be used on the main thread.');\n }\n const obj = f as any as JsFnHandle;\n if (obj._error) {\n throw new Error(obj._error);\n }\n return async (...params: ClosureValueType[]): Promise<R> => {\n return new Promise((resolve) => {\n const resolveId = onFunctionCall(resolve);\n\n if (obj._isFirstScreen) {\n delayRunOnBackground(obj, (fnId: number, execId: number) => {\n dispatchRunBackgroundFunctionEvent(fnId, params, execId, resolveId);\n });\n return;\n }\n\n dispatchRunBackgroundFunctionEvent(obj._jsFnId!, params, obj._execId!, resolveId);\n });\n };\n}\n\nfunction dispatchRunBackgroundFunctionEvent(\n fnId: number,\n params: ClosureValueType[],\n execId: number,\n resolveId: number,\n): void {\n lynx.getJSContext().dispatchEvent({\n type: WorkletEvents.runOnBackground,\n data: JSON.stringify({\n obj: {\n _jsFnId: fnId,\n _execId: execId,\n },\n params,\n resolveId,\n } as RunOnBackgroundData),\n });\n}\n"]}
1
+ {"version":3,"file":"run-on-background.js","sourceRoot":"","sources":["../../../src/core/background-function/run-on-background.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAGzE,OAAO,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACpG,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AAWzE,IAAI,SAAgD,CAAC;AACrD,IAAI,gCAA0D,CAAC;AAC/D,IAAI,mCAA6D,CAAC;AAElE,SAAS,6BAA6B;IACpC,iBAAiB,CAAC;IAClB,IAAI,gCAAgC,EAAE,CAAC;QACrC,OAAO;IACT,CAAC;IAED,SAAS,KAAK,IAAI,yBAAyB,EAAE,CAAC;IAC9C,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;IACtC,MAAM,cAAc,GAAG,4BAA4B,CAAC,OAAO,EAAE,aAAa,CAAC,eAAe,EAAE,qBAAqB,CAAC,CAAC;IACnH,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC,2BAA2B,EAAE,4BAA4B,CAAC,CAAC;IAElG,gCAAgC,GAAG,GAAG,EAAE;QACtC,cAAc,EAAE,CAAC;QACjB,OAAO,CAAC,mBAAmB,CAAC,aAAa,CAAC,2BAA2B,EAAE,4BAA4B,CAAC,CAAC;QACrG,SAAU,CAAC,KAAK,EAAE,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CAAkC,CACzC,IAAY,EACZ,MAA0B,EAC1B,MAAc,EACd,SAAiB;IAEjB,yBAAyB,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE;QAC7C,IAAI,EAAE,aAAa,CAAC,eAAe;QACnC,IAAI,EAAE;YACJ,GAAG,EAAE;gBACH,OAAO,EAAE,IAAI;gBACb,OAAO,EAAE,MAAM;aAChB;YACD,MAAM;YACN,SAAS;SACa;KACzB,CAAC,CAAC;AACL,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 { BackgroundFunctionExecMap } from './exec-map.js';\nimport { isSdkVersionGt } from '../../utils.js';\nimport { delayRunOnBackground } from '../../worklet-runtime/bindings/bindings.js';\nimport { WorkletEvents } from '../../worklet-runtime/bindings/events.js';\nimport type { RunWorkletCtxRetData } from '../../worklet-runtime/bindings/events.js';\nimport type { ClosureValueType, JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.js';\nimport { addReloadScopedEventListener, dispatchReloadScopedEvent } from '../reload-scoped-event.js';\nimport { isRuntimeDestroyed, registerDestroyTask } from '../runtime-destroy.js';\nimport { onFunctionCall } from '../thread-function-call/return-value.js';\n\n/**\n * @internal\n */\ninterface RunOnBackgroundData {\n obj: JsFnHandle;\n params: unknown[];\n resolveId: number;\n}\n\nlet execIdMap: BackgroundFunctionExecMap | undefined;\nlet cleanupBackgroundFunctionRuntime: (() => void) | undefined;\nlet unregisterBackgroundFunctionCleanup: (() => void) | undefined;\n\nfunction initBackgroundFunctionRuntime(): void {\n 'background only';\n if (cleanupBackgroundFunctionRuntime) {\n return;\n }\n\n execIdMap ??= new BackgroundFunctionExecMap();\n const context = lynx.getCoreContext();\n const removeListener = addReloadScopedEventListener(context, WorkletEvents.runOnBackground, runBackgroundFunction);\n context.addEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);\n\n cleanupBackgroundFunctionRuntime = () => {\n removeListener();\n context.removeEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundFunctionCtx);\n execIdMap!.clear();\n cleanupBackgroundFunctionRuntime = undefined;\n };\n}\n\n/**\n * @internal\n */\nexport function runBackgroundFunction(data: RunOnBackgroundData): void {\n 'background only';\n const obj = execIdMap!.findJsFnHandle(data.obj._execId!, data.obj._jsFnId!);\n const f = obj?._fn;\n if (!f) {\n throw new Error('runOnBackground: JS function not found: ' + JSON.stringify(data.obj));\n }\n const returnValue = f(...data.params);\n dispatchReloadScopedEvent(lynx.getCoreContext(), {\n type: WorkletEvents.FunctionCallRet,\n data: { resolveId: data.resolveId, returnValue } satisfies RunWorkletCtxRetData,\n });\n}\n\nfunction releaseBackgroundFunctionCtx(event: RuntimeProxy.Event): void {\n 'background only';\n for (const id of event.data) {\n execIdMap!.remove(id as number);\n }\n}\n\n/**\n * @internal\n */\nexport function registerBackgroundFunctionCtx(ctx: Worklet): void {\n 'background only';\n initBackgroundFunctionRuntime();\n ensureBackgroundFunctionCleanup();\n execIdMap!.add(ctx);\n}\n\nfunction ensureBackgroundFunctionCleanup(): void {\n if (unregisterBackgroundFunctionCleanup) {\n return;\n }\n unregisterBackgroundFunctionCleanup = registerDestroyTask(() => {\n resetBackgroundFunctionRuntime();\n });\n}\n\nexport function resetBackgroundFunctionRuntime(): void {\n cleanupBackgroundFunctionRuntime?.();\n unregisterBackgroundFunctionCleanup?.();\n unregisterBackgroundFunctionCleanup = undefined;\n}\n\n/**\n * `runOnBackground` allows triggering js functions on the background thread asynchronously.\n * @param f - The js function to be called.\n * @returns A function. Calling which with the arguments to be passed to the js function to trigger it on the background thread. This function returns a promise that resolves to the return value of the js function.\n * @public\n *\n * @example\n *\n * ```ts\n * import { runOnBackground } from '@lynx-js/react';\n *\n * async function someMainthreadFunction() {\n * 'main thread';\n * const fn = runOnBackground(() => {\n * return 'hello';\n * });\n * const result = await fn();\n * }\n * ```\n *\n * @group Functions\n */\nexport function runOnBackground<R, Fn extends (...args: any[]) => R>(\n f: Fn,\n): (...args: Parameters<Fn>) => Promise<R> {\n if (!isSdkVersionGt(2, 15)) {\n throw new Error('runOnBackground requires Lynx sdk version 2.16.');\n }\n if (__JS__) {\n throw new Error('runOnBackground can only be used on the main thread.');\n }\n const obj = f as any as JsFnHandle;\n if (obj._error) {\n throw new Error(obj._error);\n }\n return async (...params: ClosureValueType[]): Promise<R> => {\n return new Promise((resolve) => {\n if (isRuntimeDestroyed()) return;\n const resolveId = onFunctionCall(resolve);\n\n if (obj._isFirstScreen) {\n delayRunOnBackground(obj, (fnId: number, execId: number) => {\n dispatchRunBackgroundFunctionEvent(fnId, params, execId, resolveId);\n });\n return;\n }\n\n dispatchRunBackgroundFunctionEvent(obj._jsFnId!, params, obj._execId!, resolveId);\n });\n };\n}\n\nfunction dispatchRunBackgroundFunctionEvent(\n fnId: number,\n params: ClosureValueType[],\n execId: number,\n resolveId: number,\n): void {\n dispatchReloadScopedEvent(lynx.getJSContext(), {\n type: WorkletEvents.runOnBackground,\n data: {\n obj: {\n _jsFnId: fnId,\n _execId: execId,\n },\n params,\n resolveId,\n } as RunOnBackgroundData,\n });\n}\n"]}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Module-level state that survives an entry re-evaluation, for state tied to
3
+ * native objects that outlive the entry or IDs that late messages may carry.
4
+ */
5
+ export declare function cardLifetime<T extends object>(key: string, init: () => T): T;
@@ -0,0 +1,17 @@
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
+ const storeKey = Symbol.for('__REACT_LYNX_CARD_LIFETIME__');
5
+ /**
6
+ * Module-level state that survives an entry re-evaluation, for state tied to
7
+ * native objects that outlive the entry or IDs that late messages may carry.
8
+ */
9
+ export function cardLifetime(key, init) {
10
+ if (typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ === 'undefined' || !__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__) {
11
+ return init();
12
+ }
13
+ const host = lynx;
14
+ const store = host[storeKey] ??= {};
15
+ return (store[key] ??= init());
16
+ }
17
+ //# sourceMappingURL=card-lifetime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"card-lifetime.js","sourceRoot":"","sources":["../../src/core/card-lifetime.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;AAE5D;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAmB,GAAW,EAAE,IAAa;IACvE,IAAI,OAAO,qCAAqC,KAAK,WAAW,IAAI,CAAC,qCAAqC,EAAE,CAAC;QAC3G,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IACD,MAAM,IAAI,GAAG,IAAqE,CAAC;IACnF,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACpC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAM,CAAC;AACtC,CAAC","sourcesContent":["// Copyright 2026 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\nconst storeKey = Symbol.for('__REACT_LYNX_CARD_LIFETIME__');\n\n/**\n * Module-level state that survives an entry re-evaluation, for state tied to\n * native objects that outlive the entry or IDs that late messages may carry.\n */\nexport function cardLifetime<T extends object>(key: string, init: () => T): T {\n if (typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ === 'undefined' || !__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__) {\n return init();\n }\n const host = lynx as unknown as Record<symbol, Record<string, object> | undefined>;\n const store = host[storeKey] ??= {};\n return (store[key] ??= init()) as T;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export declare function canReEvalMainThreadEntry(): boolean;
2
+ export declare function canReEvalBackgroundEntry(): boolean;
3
+ /** Lets the entry being evaluated finish a reload started by the previous one. */
4
+ export declare function installMainThreadReloadCompleter<Handoff>(complete: (handoff: Handoff) => void): void;
5
+ export declare function reEvalMainThreadEntry<Handoff>(handoff: Handoff): void;
6
+ /** @param retire - stops this entry from sending work to the main thread */
7
+ export declare function reEvalBackgroundEntry(updateData: Record<string, unknown>, options: Record<string, unknown> | undefined, retire: () => void): void;
@@ -0,0 +1,49 @@
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
+ import { increaseReloadVersion } from './reload-version.js';
5
+ import { destroyRuntime } from './runtime-destroy.js';
6
+ const supportsReEvalKey = Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__');
7
+ const reloaderKey = Symbol.for('__LYNX_MAIN_THREAD_ENTRY_RELOADER__');
8
+ const completerKey = Symbol.for('__LYNX_MAIN_THREAD_RELOAD_COMPLETER__');
9
+ const externalGlobalKey = Symbol.for('__LYNX_EXTERNAL_GLOBAL__');
10
+ const host = () => lynx;
11
+ function isEntryReEvalEnabled() {
12
+ return typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ !== 'undefined'
13
+ && __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__
14
+ && host()[supportsReEvalKey] === true;
15
+ }
16
+ export function canReEvalMainThreadEntry() {
17
+ return isEntryReEvalEnabled() && typeof host()[reloaderKey] === 'function';
18
+ }
19
+ export function canReEvalBackgroundEntry() {
20
+ return isEntryReEvalEnabled() && typeof lynx.getApp().reloadCard === 'function';
21
+ }
22
+ /** Lets the entry being evaluated finish a reload started by the previous one. */
23
+ export function installMainThreadReloadCompleter(complete) {
24
+ if (typeof __MAIN_THREAD__ !== 'undefined' && __MAIN_THREAD__
25
+ && typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ !== 'undefined' && __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__) {
26
+ host()[completerKey] = complete;
27
+ }
28
+ }
29
+ export function reEvalMainThreadEntry(handoff) {
30
+ // Evaluating the entry resets `__initData`.
31
+ const initData = lynx.__initData;
32
+ destroyRuntime();
33
+ Reflect.deleteProperty(lynx, externalGlobalKey);
34
+ host()[reloaderKey]();
35
+ lynx.__initData = initData;
36
+ host()[completerKey](handoff);
37
+ }
38
+ /** @param retire - stops this entry from sending work to the main thread */
39
+ export function reEvalBackgroundEntry(updateData, options, retire) {
40
+ const data = Object.assign({}, lynx.__initData, updateData);
41
+ destroyRuntime();
42
+ increaseReloadVersion();
43
+ retire();
44
+ const app = lynx.getApp();
45
+ app.callDestroyLifetimeFun();
46
+ Reflect.deleteProperty(lynx, externalGlobalKey);
47
+ app.reloadCard(data, options);
48
+ }
49
+ //# sourceMappingURL=entry-reload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-reload.js","sourceRoot":"","sources":["../../src/core/entry-reload.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;AACxE,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;AACtE,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AACzE,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AAEjE,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,IAA0C,CAAC;AAE9D,SAAS,oBAAoB;IAC3B,OAAO,OAAO,qCAAqC,KAAK,WAAW;WAC9D,qCAAqC;WACrC,IAAI,EAAE,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAAC;AAC1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cAAc,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;IAChD,GAAG,CAAC,UAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjC,CAAC","sourcesContent":["// Copyright 2026 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 { increaseReloadVersion } from './reload-version.js';\nimport { destroyRuntime } from './runtime-destroy.js';\n\nconst supportsReEvalKey = Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__');\nconst reloaderKey = Symbol.for('__LYNX_MAIN_THREAD_ENTRY_RELOADER__');\nconst completerKey = Symbol.for('__LYNX_MAIN_THREAD_RELOAD_COMPLETER__');\nconst externalGlobalKey = Symbol.for('__LYNX_EXTERNAL_GLOBAL__');\n\nconst host = () => lynx as unknown as Record<symbol, unknown>;\n\nfunction isEntryReEvalEnabled(): boolean {\n return typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ !== 'undefined'\n && __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__\n && host()[supportsReEvalKey] === true;\n}\n\nexport function canReEvalMainThreadEntry(): boolean {\n return isEntryReEvalEnabled() && typeof host()[reloaderKey] === 'function';\n}\n\nexport function canReEvalBackgroundEntry(): boolean {\n return isEntryReEvalEnabled() && typeof lynx.getApp().reloadCard === 'function';\n}\n\n/** Lets the entry being evaluated finish a reload started by the previous one. */\nexport function installMainThreadReloadCompleter<Handoff>(complete: (handoff: Handoff) => void): void {\n if (\n typeof __MAIN_THREAD__ !== 'undefined' && __MAIN_THREAD__\n && typeof __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__ !== 'undefined' && __EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__\n ) {\n host()[completerKey] = complete;\n }\n}\n\nexport function reEvalMainThreadEntry<Handoff>(handoff: Handoff): void {\n // Evaluating the entry resets `__initData`.\n const initData = lynx.__initData;\n destroyRuntime();\n Reflect.deleteProperty(lynx, externalGlobalKey);\n (host()[reloaderKey] as () => void)();\n lynx.__initData = initData;\n (host()[completerKey] as (handoff: Handoff) => void)(handoff);\n}\n\n/** @param retire - stops this entry from sending work to the main thread */\nexport function reEvalBackgroundEntry(\n updateData: Record<string, unknown>,\n options: Record<string, unknown> | undefined,\n retire: () => void,\n): void {\n const data = Object.assign({}, lynx.__initData, updateData);\n destroyRuntime();\n increaseReloadVersion();\n retire();\n const app = lynx.getApp();\n app.callDestroyLifetimeFun();\n Reflect.deleteProperty(lynx, externalGlobalKey);\n app.reloadCard!(data, options);\n}\n"]}
@@ -53,7 +53,10 @@ export const makeSyncThen = function (result) {
53
53
  // { level: "warning" }
54
54
  // );
55
55
  }
56
- const p = Promise.resolve(ret);
56
+ // The Lynx Promise polyfill shares resolved promises for primitive values.
57
+ // Own this promise before replacing `then`, or an undefined callback
58
+ // result would make unrelated Promise.resolve().then(...) calls synchronous.
59
+ const p = new Promise(resolve => resolve(ret));
57
60
  const then = makeSyncThen(ret);
58
61
  p.then = then;
59
62
  return p;
@@ -1 +1 @@
1
- {"version":3,"file":"lazy-bundle.js","sourceRoot":"","sources":["../../../src/core/lynx/lazy-bundle.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,6EAA6E;AAC7E,oDAAoD;AACpD,6EAA6E;AAC7E,+CAA+C;AAC/C,4EAA4E;AAC5E,2DAA2D;AAC3D,MAAM,mBAAmB,GAAG,aAAa,CAAC;AAC1C,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,WAAW,GAAG,KAAK,CAAC;AAC1B,MAAM,8BAA8B,GAAG,CAAC,CAAC;AACzC,MAAM,uBAAuB,GAAG,2BAA2B,CAAC;AAE5D,yEAAyE;AACzE,0EAA0E;AAC1E,+EAA+E;AAC/E,gFAAgF;AAChF,mDAAmD;AACnD,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAmB,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,CAAC,M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AE,IAAI;KACZ,CAAC;IAEF,OAAO,QAAQ,CAAC;AAClB,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\n// Inlined rather than imported from `snapshot/` so this `core/` module stays\n// free of runtime-backend dependencies (enforced by\n// `guardrails/snapshot-containment`). `PREPARE_LAZY_BUNDLE_MTS` must stay in\n// sync with `snapshot/lifecycle/constant.ts`'s\n// `LifecycleConstant.prepareLazyBundleMTS`, the lifecycle name the snapshot\n// backend registers the main-thread prepare handler under.\nconst SECTION_MAIN_THREAD = 'main-thread';\nconst SECTION_BACKGROUND = 'background';\nconst SECTION_CSS = 'CSS';\nconst LYNX_LAZY_SYNC_TIMEOUT_SECONDS = 5;\nconst PREPARE_LAZY_BUNDLE_MTS = 'rLynxPrepareLazyBundleMTS';\n\n// Background-thread dedup cache: a `source` whose FetchBundle load fully\n// succeeded maps to its exports, so a repeat load returns the same result\n// without re-fetching or re-triggering the main-thread prepare. Only populated\n// on success — a failed load stays out of the cache and can be retried, exactly\n// like `prepareLazyBundleMTS`'s main-thread cache.\nconst fetchBundleBgCache = new Map<string, unknown>();\n\n/**\n * To make code below works\n * const App1 = lazy(() => import(\"./x\").then(({App1}) => ({default: App1})))\n * const App2 = lazy(() => import(\"./x\").then(({App2}) => ({default: App2})))\n * @internal\n */\nexport const makeSyncThen = function<T>(result: T): Promise<T>['then'] {\n return function<TR1 = T, TR2 = never>(\n this: Promise<T>,\n onF?: ((value: T) => TR1 | PromiseLike<TR1>) | null,\n _onR?: ((reason: any) => TR2 | PromiseLike<TR2>) | null,\n ): Promise<TR1 | TR2> {\n if (onF) {\n let ret: TR1 | PromiseLike<TR1>;\n try {\n ret = onF(result);\n } catch (e) {\n // if (onR) {\n // return Promise.resolve(onR(e));\n // }\n return Promise.reject(e as Error);\n }\n\n if (ret && typeof (ret as PromiseLike<TR1>).then === 'function' /* `thenable` object */) {\n // lazy(() =>\n // import(\"./x\").then(() => new Promise(...))\n // )\n // Calling `then` and passing a callback is standard behavior\n // but in Lepus runtime the callback will never be called\n // So can be simplified to code below\n return ret as Promise<TR1>;\n\n // TODO(hongzhiyuan.hzy): Avoid warning that cannot be turned-off, so the warning is commented\n // lynx.reportError(\n // new Error(\n // 'You returned a Promise in promise-chain of lazy-bundle import (eg. `import(\"./x\").then(() => new Promise(...))`), which will cause related Component unavailable at first-screen, '\n // ),\n // { level: \"warning\" }\n // );\n }\n\n const p = Promise.resolve(ret);\n\n const then = makeSyncThen(ret as TR1);\n p.then = then as Promise<Awaited<TR1>>['then'];\n\n return p as Promise<TR1 | TR2>;\n }\n\n return this as Promise<TR1 | TR2>;\n };\n};\n\nexport type LazyBundleMode = 'sync' | 'async';\n\n// loadScript a background section with `globalThis.globDynamicComponentEntry`\n// set to `entry` (restored after). The bundle's wrapper reads it once as\n// `g.globDynamicComponentEntry || '__Card__'`, so without this its modules — and\n// any nested `import()` it triggers — would resolve against the caller's host.\nfunction loadBackgroundBundle<T>(bundleName: string, entry: string): T {\n const g = globalThis as { globDynamicComponentEntry?: string | undefined };\n const previous = g.globDynamicComponentEntry;\n g.globDynamicComponentEntry = entry;\n try {\n return lynx.loadScript<T>(SECTION_BACKGROUND, { bundleName });\n } finally {\n g.globDynamicComponentEntry = previous;\n }\n}\n\n/**\n * Load dynamic component from source. Designed to be used with `lazy`.\n *\n * The `mode` is threaded in by the chunk-loading runtime from the\n * `import(..., { with: { mode } })` import attribute (see `lynx_acm`), so each\n * lazy import carries its own mode instead of relying on shared mutable state.\n * @param source - where dynamic component template.js locates\n * @param mode - `'sync'` (first-screen blocking) or `'async'` (default)\n * @returns\n * @public\n */\nexport const loadLazyBundle: <\n T extends { default: React.ComponentType<any> },\n>(source: string, mode?: LazyBundleMode, host?: string) => Promise<T> = /*#__PURE__*/ (() => {\n // Default to QueryComponent when `__LAZY_BUNDLE_FETCHER__` is missing —\n // older react-webpack-plugin builds don't stamp it and they predate\n // FetchBundle support, so falling through to QueryComponent is the only\n // safe behavior.\n const useFetchBundle = typeof __LAZY_BUNDLE_FETCHER__ !== 'undefined'\n && __LAZY_BUNDLE_FETCHER__ === 'FetchBundle';\n\n const impl = useFetchBundle\n ? loadLazyBundleWithFetchBundle\n : loadLazyBundleWithQueryComponent;\n\n lynx.loadLazyBundle = impl;\n\n function loadLazyBundleWithQueryComponent<\n T extends { default: React.ComponentType<any> },\n >(source: string, mode?: LazyBundleMode): Promise<T> {\n if (__LEPUS__) {\n const query = __QueryComponent(source);\n let result: T;\n try {\n result = query.evalResult as T;\n } catch (e) {\n // Here we cannot return a rejected promise\n // (which will eventually be an unhandled rejection and cause unnecessary redbox)\n // But we still need a object in shape of Promise\n // So we return a Promise which will never resolve or reject,\n // which fit our principle \"lepus run only once at first-screen\" better\n return new Promise(() => {});\n }\n const r: Promise<T> = Promise.resolve(result);\n // Why we should modify the implementation of `then`?\n // We should make it `sync` so lepus first-screen render can use result above instantly\n // We also should keep promise shape\n r.then = makeSyncThen(result);\n return r;\n } else if (__JS__) {\n if (__DEV__ && mode !== undefined) {\n throw new Error(\n `Lazy bundle import \\`mode: '${mode}'\\` requires FetchBundle, but the current build uses QueryComponent. `\n + `Set \\`engineVersion: '3.9'\\` (or higher) in \\`pluginReactLynx\\` to enable FetchBundle.`,\n );\n }\n const resolver = withSyncResolvers<T>();\n\n const callback: (result: { code: number; detail: { schema: string } }) => void = result => {\n const { code, detail } = result;\n if (code === 0) {\n const { schema } = detail;\n const exports = lynx.getApp().getDynamicComponentExports(schema);\n // `code === 0` means that the lazy bundle has been successfully parsed. However,\n // its javascript files may still fail to run, which would prevent the retrieval of the exports object.\n if (exports) {\n resolver.resolve(exports as T);\n return;\n }\n }\n const e = new Error('Lazy bundle load failed, schema: ' + result.detail.schema);\n // ES5 does not support new Error('message', { cause: 'detail' })\n // So we set cause using `.cause` assignment\n e.cause = JSON.stringify(result);\n resolver.reject(e);\n };\n if (typeof lynx.QueryComponent === 'function') {\n lynx.QueryComponent(source, callback);\n } else {\n lynx.getNativeLynx().QueryComponent!(source, callback);\n }\n\n if (resolver.result !== null) {\n const p = Promise.resolve(resolver.result);\n p.then = makeSyncThen(resolver.result) as Promise<Awaited<T>>['then'];\n return p;\n } else if (resolver.error === null) {\n return new Promise((_resolve, _reject) => {\n resolver.resolve = _resolve;\n resolver.reject = _reject;\n });\n } else {\n return Promise.reject(resolver.error);\n }\n }\n\n throw new Error('unreachable');\n }\n\n function loadLazyBundleWithFetchBundle<\n T extends { default: React.ComponentType<any> },\n >(source: string, mode?: LazyBundleMode, host?: string): Promise<T> {\n if (__MAIN_THREAD__) {\n if (mode !== 'sync') {\n // Fire the fetch and ignore the result so the request goes out early\n // and warms the native bundle cache; the background `async` path then\n // waits less. The main thread renders nothing here.\n try {\n lynx.fetchBundle(source, {});\n } catch {}\n return new Promise(() => {});\n }\n let response;\n try {\n response = lynx.fetchBundle(source, {}).wait(\n LYNX_LAZY_SYNC_TIMEOUT_SECONDS,\n );\n } catch {\n return new Promise(() => {});\n }\n if (!response || response.code !== 0) {\n return new Promise(() => {});\n }\n let result: T;\n try {\n result = lynx.loadScript<(entry: string) => T>(SECTION_MAIN_THREAD, {\n bundleName: response.url,\n })(source);\n const styleSheet = __LoadStyleSheet(SECTION_CSS, response.url);\n if (styleSheet !== null) {\n __AdoptStyleSheet(styleSheet);\n }\n } catch {\n return new Promise(() => {});\n }\n const r: Promise<T> = Promise.resolve(result);\n r.then = makeSyncThen(result);\n return r;\n } else if (__JS__) {\n const cached = fetchBundleBgCache.get(source);\n if (cached !== undefined) {\n const r: Promise<T> = Promise.resolve(cached as T);\n r.then = makeSyncThen(cached as T);\n return r;\n }\n if (mode === 'sync') {\n let response;\n try {\n response = lynx.fetchBundle(source, {}).wait(\n LYNX_LAZY_SYNC_TIMEOUT_SECONDS,\n );\n } catch (e) {\n return Promise.reject(e instanceof Error ? e : new Error(String(e)));\n }\n if (!response || response.code !== 0) {\n console.error('Lazy bundle load failed', response);\n const e = new Error('Lazy bundle load failed, schema: ' + source);\n e.cause = JSON.stringify(response);\n return Promise.reject(e);\n }\n let result: T;\n try {\n result = loadBackgroundBundle<T>(response.url, source);\n } catch (e) {\n return Promise.reject(e instanceof Error ? e : new Error(String(e)));\n }\n // A sync bundle that wasn't part of the first-screen main-thread render\n // still needs its main-thread section prepared on the MT (the\n // createSnapshot side effect), or a later patch referencing it hits\n // \"snapshot not found\". Runs synchronously — the bundle is already in\n // the native cache — just like the async path below.\n try {\n lynx.getNativeApp().callLepusMethod(\n PREPARE_LAZY_BUNDLE_MTS,\n { url: source, host },\n () => {},\n );\n } catch (e) {\n return Promise.reject(e instanceof Error ? e : new Error(String(e)));\n }\n // Fully loaded and prepared — cache so repeat loads skip the work above.\n fetchBundleBgCache.set(source, result);\n const r: Promise<T> = Promise.resolve(result);\n r.then = makeSyncThen(result);\n return r;\n }\n\n // async (default)\n return new Promise<T>((resolve, reject) => {\n let handler;\n try {\n handler = lynx.fetchBundle(source, {});\n } catch (e) {\n reject(e instanceof Error ? e : new Error(String(e)));\n return;\n }\n handler.then((response) => {\n if (!response || response.code !== 0) {\n console.error('Lazy bundle load failed', response);\n const e = new Error('Lazy bundle load failed, schema: ' + source);\n e.cause = JSON.stringify(response);\n reject(e);\n return;\n }\n let btsResult: T;\n try {\n btsResult = loadBackgroundBundle<T>(response.url, source);\n } catch (e) {\n reject(e instanceof Error ? e : new Error(String(e)));\n return;\n }\n // Bundle is now in native cache, so MT's `.then` fires sync and\n // the whole prepare runs synchronously inside `Call`, meaning the\n // cb fires only after MT snapshots are registered.\n try {\n lynx.getNativeApp().callLepusMethod(\n PREPARE_LAZY_BUNDLE_MTS,\n { url: source, host },\n () => {\n // Fully loaded and MT-prepared — cache so repeat loads skip\n // the fetch / background eval / MT prepare above.\n fetchBundleBgCache.set(source, btsResult);\n resolve(btsResult);\n },\n );\n } catch (e) {\n reject(e instanceof Error ? e : new Error(String(e)));\n }\n });\n });\n }\n\n throw new Error('unreachable');\n }\n\n return impl;\n})();\n\nfunction withSyncResolvers<T>() {\n 'background-only';\n\n const resolver: {\n result: T | null;\n error: Error | null;\n resolve(result: T): void;\n reject(error: Error): void;\n } = {\n resolve: (result: T): void => {\n resolver.result = result;\n },\n reject: (error: Error): void => {\n resolver.error = error;\n },\n result: null,\n error: null,\n };\n\n return resolver;\n}\n"]}
1
+ {"version":3,"file":"lazy-bundle.js","sourceRoot":"","sources":["../../../src/core/lynx/lazy-bundle.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,6EAA6E;AAC7E,oDAAoD;AACpD,6EAA6E;AAC7E,+CAA+C;AAC/C,4EAA4E;AAC5E,2DAA2D;AAC3D,MAAM,mBAAmB,GAAG,aAAa,CAAC;AAC1C,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,WAAW,GAAG,KAAK,CAAC;AAC1B,MAAM,8BAA8B,GAAG,CAAC,CAAC;AACzC,MAAM,uBAAuB,GAAG,2BAA2B,CAAC;AAE5D,yEAAyE;AACzE,0EAA0E;AAC1E,+EAA+E;AAC/E,gFAAgF;AAChF,mDAAmD;AACnD,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAmB,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,UAAY,MAAS;IAC/C,OAAO,UAEL,GAAmD,EACnD,IAAuD;QAEvD,IAAI,GAAG,EAAE,CAAC;YACR,IAAI,GAA2B,CAAC;YAChC,IAAI,CAAC;gBACH,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC;YACpB,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,aAAa;gBACb,oCAAoC;gBACpC,IAAI;gBACJ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAU,CAAC,CAAC;YACpC,CAAC;YAED,IAAI,GAAG,IAAI,OAAQ,GAAwB,CAAC,IAAI,KAAK,UAAU,CAAC,uBAAuB,EAAE,CAAC;gBACxF,aAAa;g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EAAE,MAAM,EAAE,IAAI,EAAE,EACrB,GAAG,EAAE;4BACH,4DAA4D;4BAC5D,kDAAkD;4BAClD,kBAAkB,CAAC,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;4BAC1C,OAAO,CAAC,SAAS,CAAC,CAAC;wBACrB,CAAC,CACF,CAAC;oBACJ,CAAC;oBAAC,OAAO,CAAC,EAAE,CAAC;wBACX,MAAM,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBACxD,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;QAED,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,EAAE,CAAC;AAEL,SAAS,iBAAiB;IACxB,iBAAiB,CAAC;IAElB,MAAM,QAAQ,GAKV;QACF,OAAO,EAAE,CAAC,MAAS,EAAQ,EAAE;YAC3B,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC;QAC3B,CAAC;QACD,MAAM,EAAE,CAAC,KAAY,EAAQ,EAAE;YAC7B,QAAQ,CAAC,KAAK,GAAG,KAAK,CAAC;QACzB,CAAC;QACD,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,IAAI;KACZ,CAAC;IAEF,OAAO,QAAQ,CAAC;AAClB,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\n// Inlined rather than imported from `snapshot/` so this `core/` module stays\n// free of runtime-backend dependencies (enforced by\n// `guardrails/snapshot-containment`). `PREPARE_LAZY_BUNDLE_MTS` must stay in\n// sync with `snapshot/lifecycle/constant.ts`'s\n// `LifecycleConstant.prepareLazyBundleMTS`, the lifecycle name the snapshot\n// backend registers the main-thread prepare handler under.\nconst SECTION_MAIN_THREAD = 'main-thread';\nconst SECTION_BACKGROUND = 'background';\nconst SECTION_CSS = 'CSS';\nconst LYNX_LAZY_SYNC_TIMEOUT_SECONDS = 5;\nconst PREPARE_LAZY_BUNDLE_MTS = 'rLynxPrepareLazyBundleMTS';\n\n// Background-thread dedup cache: a `source` whose FetchBundle load fully\n// succeeded maps to its exports, so a repeat load returns the same result\n// without re-fetching or re-triggering the main-thread prepare. Only populated\n// on success — a failed load stays out of the cache and can be retried, exactly\n// like `prepareLazyBundleMTS`'s main-thread cache.\nconst fetchBundleBgCache = new Map<string, unknown>();\n\n/**\n * To make code below works\n * const App1 = lazy(() => import(\"./x\").then(({App1}) => ({default: App1})))\n * const App2 = lazy(() => import(\"./x\").then(({App2}) => ({default: App2})))\n * @internal\n */\nexport const makeSyncThen = function<T>(result: T): Promise<T>['then'] {\n return function<TR1 = T, TR2 = never>(\n this: Promise<T>,\n onF?: ((value: T) => TR1 | PromiseLike<TR1>) | null,\n _onR?: ((reason: any) => TR2 | PromiseLike<TR2>) | null,\n ): Promise<TR1 | TR2> {\n if (onF) {\n let ret: TR1 | PromiseLike<TR1>;\n try {\n ret = onF(result);\n } catch (e) {\n // if (onR) {\n // return Promise.resolve(onR(e));\n // }\n return Promise.reject(e as Error);\n }\n\n if (ret && typeof (ret as PromiseLike<TR1>).then === 'function' /* `thenable` object */) {\n // lazy(() =>\n // import(\"./x\").then(() => new Promise(...))\n // )\n // Calling `then` and passing a callback is standard behavior\n // but in Lepus runtime the callback will never be called\n // So can be simplified to code below\n return ret as Promise<TR1>;\n\n // TODO(hongzhiyuan.hzy): Avoid warning that cannot be turned-off, so the warning is commented\n // lynx.reportError(\n // new Error(\n // 'You returned a Promise in promise-chain of lazy-bundle import (eg. `import(\"./x\").then(() => new Promise(...))`), which will cause related Component unavailable at first-screen, '\n // ),\n // { level: \"warning\" }\n // );\n }\n\n // The Lynx Promise polyfill shares resolved promises for primitive values.\n // Own this promise before replacing `then`, or an undefined callback\n // result would make unrelated Promise.resolve().then(...) calls synchronous.\n const p = new Promise<TR1>(resolve => resolve(ret));\n\n const then = makeSyncThen(ret as TR1);\n p.then = then as Promise<Awaited<TR1>>['then'];\n\n return p as Promise<TR1 | TR2>;\n }\n\n return this as Promise<TR1 | TR2>;\n };\n};\n\nexport type LazyBundleMode = 'sync' | 'async';\n\n// loadScript a background section with `globalThis.globDynamicComponentEntry`\n// set to `entry` (restored after). The bundle's wrapper reads it once as\n// `g.globDynamicComponentEntry || '__Card__'`, so without this its modules — and\n// any nested `import()` it triggers — would resolve against the caller's host.\nfunction loadBackgroundBundle<T>(bundleName: string, entry: string): T {\n const g = globalThis as { globDynamicComponentEntry?: string | undefined };\n const previous = g.globDynamicComponentEntry;\n g.globDynamicComponentEntry = entry;\n try {\n return lynx.loadScript<T>(SECTION_BACKGROUND, { bundleName });\n } finally {\n g.globDynamicComponentEntry = previous;\n }\n}\n\n/**\n * Load dynamic component from source. Designed to be used with `lazy`.\n *\n * The `mode` is threaded in by the chunk-loading runtime from the\n * `import(..., { with: { mode } })` import attribute (see `lynx_acm`), so each\n * lazy import carries its own mode instead of relying on shared mutable state.\n * @param source - where dynamic component template.js locates\n * @param mode - `'sync'` (first-screen blocking) or `'async'` (default)\n * @returns\n * @public\n */\nexport const loadLazyBundle: <\n T extends { default: React.ComponentType<any> },\n>(source: string, mode?: LazyBundleMode, host?: string) => Promise<T> = /*#__PURE__*/ (() => {\n // Default to QueryComponent when `__LAZY_BUNDLE_FETCHER__` is missing —\n // older react-webpack-plugin builds don't stamp it and they predate\n // FetchBundle support, so falling through to QueryComponent is the only\n // safe behavior.\n const useFetchBundle = typeof __LAZY_BUNDLE_FETCHER__ !== 'undefined'\n && __LAZY_BUNDLE_FETCHER__ === 'FetchBundle';\n\n const impl = useFetchBundle\n ? loadLazyBundleWithFetchBundle\n : loadLazyBundleWithQueryComponent;\n\n lynx.loadLazyBundle = impl;\n\n function loadLazyBundleWithQueryComponent<\n T extends { default: React.ComponentType<any> },\n >(source: string, mode?: LazyBundleMode): Promise<T> {\n if (__LEPUS__) {\n const query = __QueryComponent(source);\n let result: T;\n try {\n result = query.evalResult as T;\n } catch (e) {\n // Here we cannot return a rejected promise\n // (which will eventually be an unhandled rejection and cause unnecessary redbox)\n // But we still need a object in shape of Promise\n // So we return a Promise which will never resolve or reject,\n // which fit our principle \"lepus run only once at first-screen\" better\n return new Promise(() => {});\n }\n const r: Promise<T> = Promise.resolve(result);\n // Why we should modify the implementation of `then`?\n // We should make it `sync` so lepus first-screen render can use result above instantly\n // We also should keep promise shape\n r.then = makeSyncThen(result);\n return r;\n } else if (__JS__) {\n if (__DEV__ && mode !== undefined) {\n throw new Error(\n `Lazy bundle import \\`mode: '${mode}'\\` requires FetchBundle, but the current build uses QueryComponent. `\n + `Set \\`engineVersion: '3.9'\\` (or higher) in \\`pluginReactLynx\\` to enable FetchBundle.`,\n );\n }\n const resolver = withSyncResolvers<T>();\n\n const callback: (result: { code: number; detail: { schema: string } }) => void = result => {\n const { code, detail } = result;\n if (code === 0) {\n const { schema } = detail;\n const exports = lynx.getApp().getDynamicComponentExports(schema);\n // `code === 0` means that the lazy bundle has been successfully parsed. However,\n // its javascript files may still fail to run, which would prevent the retrieval of the exports object.\n if (exports) {\n resolver.resolve(exports as T);\n return;\n }\n }\n const e = new Error('Lazy bundle load failed, schema: ' + result.detail.schema);\n // ES5 does not support new Error('message', { cause: 'detail' })\n // So we set cause using `.cause` assignment\n e.cause = JSON.stringify(result);\n resolver.reject(e);\n };\n if (typeof lynx.QueryComponent === 'function') {\n lynx.QueryComponent(source, callback);\n } else {\n lynx.getNativeLynx().QueryComponent!(source, callback);\n }\n\n if (resolver.result !== null) {\n const p = Promise.resolve(resolver.result);\n p.then = makeSyncThen(resolver.result) as Promise<Awaited<T>>['then'];\n return p;\n } else if (resolver.error === null) {\n return new Promise((_resolve, _reject) => {\n resolver.resolve = _resolve;\n resolver.reject = _reject;\n });\n } else {\n return Promise.reject(resolver.error);\n }\n }\n\n throw new Error('unreachable');\n }\n\n function loadLazyBundleWithFetchBundle<\n T extends { default: React.ComponentType<any> },\n >(source: string, mode?: LazyBundleMode, host?: string): Promise<T> {\n if (__MAIN_THREAD__) {\n if (mode !== 'sync') {\n // Fire the fetch and ignore the result so the request goes out early\n // and warms the native bundle cache; the background `async` path then\n // waits less. The main thread renders nothing here.\n try {\n lynx.fetchBundle(source, {});\n } catch {}\n return new Promise(() => {});\n }\n let response;\n try {\n response = lynx.fetchBundle(source, {}).wait(\n LYNX_LAZY_SYNC_TIMEOUT_SECONDS,\n );\n } catch {\n return new Promise(() => {});\n }\n if (!response || response.code !== 0) {\n return new Promise(() => {});\n }\n let result: T;\n try {\n result = lynx.loadScript<(entry: string) => T>(SECTION_MAIN_THREAD, {\n bundleName: response.url,\n })(source);\n const styleSheet = __LoadStyleSheet(SECTION_CSS, response.url);\n if (styleSheet !== null) {\n __AdoptStyleSheet(styleSheet);\n }\n } catch {\n return new Promise(() => {});\n }\n const r: Promise<T> = Promise.resolve(result);\n r.then = makeSyncThen(result);\n return r;\n } else if (__JS__) {\n const cached = fetchBundleBgCache.get(source);\n if (cached !== undefined) {\n const r: Promise<T> = Promise.resolve(cached as T);\n r.then = makeSyncThen(cached as T);\n return r;\n }\n if (mode === 'sync') {\n let response;\n try {\n response = lynx.fetchBundle(source, {}).wait(\n LYNX_LAZY_SYNC_TIMEOUT_SECONDS,\n );\n } catch (e) {\n return Promise.reject(e instanceof Error ? e : new Error(String(e)));\n }\n if (!response || response.code !== 0) {\n console.error('Lazy bundle load failed', response);\n const e = new Error('Lazy bundle load failed, schema: ' + source);\n e.cause = JSON.stringify(response);\n return Promise.reject(e);\n }\n let result: T;\n try {\n result = loadBackgroundBundle<T>(response.url, source);\n } catch (e) {\n return Promise.reject(e instanceof Error ? e : new Error(String(e)));\n }\n // A sync bundle that wasn't part of the first-screen main-thread render\n // still needs its main-thread section prepared on the MT (the\n // createSnapshot side effect), or a later patch referencing it hits\n // \"snapshot not found\". Runs synchronously — the bundle is already in\n // the native cache — just like the async path below.\n try {\n lynx.getNativeApp().callLepusMethod(\n PREPARE_LAZY_BUNDLE_MTS,\n { url: source, host },\n () => {},\n );\n } catch (e) {\n return Promise.reject(e instanceof Error ? e : new Error(String(e)));\n }\n // Fully loaded and prepared — cache so repeat loads skip the work above.\n fetchBundleBgCache.set(source, result);\n const r: Promise<T> = Promise.resolve(result);\n r.then = makeSyncThen(result);\n return r;\n }\n\n // async (default)\n return new Promise<T>((resolve, reject) => {\n let handler;\n try {\n handler = lynx.fetchBundle(source, {});\n } catch (e) {\n reject(e instanceof Error ? e : new Error(String(e)));\n return;\n }\n handler.then((response) => {\n if (!response || response.code !== 0) {\n console.error('Lazy bundle load failed', response);\n const e = new Error('Lazy bundle load failed, schema: ' + source);\n e.cause = JSON.stringify(response);\n reject(e);\n return;\n }\n let btsResult: T;\n try {\n btsResult = loadBackgroundBundle<T>(response.url, source);\n } catch (e) {\n reject(e instanceof Error ? e : new Error(String(e)));\n return;\n }\n // Bundle is now in native cache, so MT's `.then` fires sync and\n // the whole prepare runs synchronously inside `Call`, meaning the\n // cb fires only after MT snapshots are registered.\n try {\n lynx.getNativeApp().callLepusMethod(\n PREPARE_LAZY_BUNDLE_MTS,\n { url: source, host },\n () => {\n // Fully loaded and MT-prepared — cache so repeat loads skip\n // the fetch / background eval / MT prepare above.\n fetchBundleBgCache.set(source, btsResult);\n resolve(btsResult);\n },\n );\n } catch (e) {\n reject(e instanceof Error ? e : new Error(String(e)));\n }\n });\n });\n }\n\n throw new Error('unreachable');\n }\n\n return impl;\n})();\n\nfunction withSyncResolvers<T>() {\n 'background-only';\n\n const resolver: {\n result: T | null;\n error: Error | null;\n resolve(result: T): void;\n reject(error: Error): void;\n } = {\n resolve: (result: T): void => {\n resolver.result = result;\n },\n reject: (error: Error): void => {\n resolver.error = error;\n },\n result: null,\n error: null,\n };\n\n return resolver;\n}\n"]}
@@ -1,14 +1,14 @@
1
1
  // Copyright 2026 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
- let lastIdBG = 0;
5
- let lastIdMT = 0;
4
+ import { cardLifetime } from './card-lifetime.js';
5
+ const lastId = /*#__PURE__*/ cardLifetime('mainThreadRefId', () => ({ bg: 0, mt: 0 }));
6
6
  /** @internal */
7
7
  export function allocateMainThreadRefId() {
8
- return __JS__ ? ++lastIdBG : --lastIdMT;
8
+ return __JS__ ? ++lastId.bg : --lastId.mt;
9
9
  }
10
10
  /** @internal */
11
11
  export function clearMainThreadRefIdsForTesting() {
12
- lastIdBG = lastIdMT = 0;
12
+ lastId.bg = lastId.mt = 0;
13
13
  }
14
14
  //# sourceMappingURL=main-thread-ref-id.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"main-thread-ref-id.js","sourceRoot":"","sources":["../../src/core/main-thread-ref-id.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,IAAI,QAAQ,GAAG,CAAC,CAAC;AACjB,IAAI,QAAQ,GAAG,CAAC,CAAC;AAEjB,gBAAgB;AAChB,MAAM,UAAU,uBAAuB;IACrC,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;AAC1C,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,+BAA+B;IAC7C,QAAQ,GAAG,QAAQ,GAAG,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["// Copyright 2026 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\nlet lastIdBG = 0;\nlet lastIdMT = 0;\n\n/** @internal */\nexport function allocateMainThreadRefId(): number {\n return __JS__ ? ++lastIdBG : --lastIdMT;\n}\n\n/** @internal */\nexport function clearMainThreadRefIdsForTesting(): void {\n lastIdBG = lastIdMT = 0;\n}\n"]}
1
+ {"version":3,"file":"main-thread-ref-id.js","sourceRoot":"","sources":["../../src/core/main-thread-ref-id.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,MAAM,MAAM,GAAG,aAAa,CAAC,YAAY,CAAC,iBAAiB,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AAEvF,gBAAgB;AAChB,MAAM,UAAU,uBAAuB;IACrC,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC;AAC5C,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,+BAA+B;IAC7C,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["// Copyright 2026 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 { cardLifetime } from './card-lifetime.js';\n\nconst lastId = /*#__PURE__*/ cardLifetime('mainThreadRefId', () => ({ bg: 0, mt: 0 }));\n\n/** @internal */\nexport function allocateMainThreadRefId(): number {\n return __JS__ ? ++lastId.bg : --lastId.mt;\n}\n\n/** @internal */\nexport function clearMainThreadRefIdsForTesting(): void {\n lastId.bg = lastId.mt = 0;\n}\n"]}
@@ -0,0 +1,5 @@
1
+ export declare function dispatchReloadScopedEvent(context: RuntimeProxy, event: {
2
+ type: string;
3
+ data: object;
4
+ }): void;
5
+ export declare function addReloadScopedEventListener<T>(context: RuntimeProxy, type: string, listener: (data: T) => void): () => void;
@@ -0,0 +1,26 @@
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
+ import { getReloadVersion } from './reload-version.js';
5
+ export function dispatchReloadScopedEvent(context, event) {
6
+ context.dispatchEvent({
7
+ type: event.type,
8
+ data: JSON.stringify({ ...event.data, reloadVersion: getReloadVersion() }),
9
+ });
10
+ }
11
+ // Deliver parsed payloads only while their page is current. Return cleanup for
12
+ // the actual registered wrapper, so callers need no listener identity registry.
13
+ export function addReloadScopedEventListener(context, type, listener) {
14
+ const handle = (event) => {
15
+ const data = JSON.parse(event.data);
16
+ // Unversioned events belong to the initial page only.
17
+ if ((data.reloadVersion ?? 0) !== getReloadVersion())
18
+ return;
19
+ listener(data);
20
+ };
21
+ context.addEventListener(type, handle);
22
+ return () => {
23
+ context.removeEventListener(type, handle);
24
+ };
25
+ }
26
+ //# sourceMappingURL=reload-scoped-event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reload-scoped-event.js","sourceRoot":"","sources":["../../src/core/reload-scoped-event.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAMvD,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EAAE,KAAqC;IACpG,OAAO,CAAC,aAAa,CAAC;QACpB,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,KAAK,CAAC,IAAI,EAAE,aAAa,EAAE,gBAAgB,EAAE,EAAE,CAAC;KAC3E,CAAC,CAAC;AACL,CAAC;AAED,+EAA+E;AAC/E,gFAAgF;AAChF,MAAM,UAAU,4BAA4B,CAC1C,OAAqB,EACrB,IAAY,EACZ,QAA2B;IAE3B,MAAM,MAAM,GAAG,CAAC,KAAyB,EAAQ,EAAE;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAc,CAAoB,CAAC;QACjE,sDAAsD;QACtD,IAAI,CAAC,IAAI,CAAC,aAAa,IAAI,CAAC,CAAC,KAAK,gBAAgB,EAAE;YAAE,OAAO;QAC7D,QAAQ,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC,CAAC;IACF,OAAO,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACvC,OAAO,GAAG,EAAE;QACV,OAAO,CAAC,mBAAmB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2026 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 { getReloadVersion } from './reload-version.js';\n\ninterface ReloadScope {\n reloadVersion?: number | undefined;\n}\n\nexport function dispatchReloadScopedEvent(context: RuntimeProxy, event: { type: string; data: object }): void {\n context.dispatchEvent({\n type: event.type,\n data: JSON.stringify({ ...event.data, reloadVersion: getReloadVersion() }),\n });\n}\n\n// Deliver parsed payloads only while their page is current. Return cleanup for\n// the actual registered wrapper, so callers need no listener identity registry.\nexport function addReloadScopedEventListener<T>(\n context: RuntimeProxy,\n type: string,\n listener: (data: T) => void,\n): () => void {\n const handle = (event: RuntimeProxy.Event): void => {\n const data = JSON.parse(event.data as string) as T & ReloadScope;\n // Unversioned events belong to the initial page only.\n if ((data.reloadVersion ?? 0) !== getReloadVersion()) return;\n listener(data);\n };\n context.addEventListener(type, handle);\n return () => {\n context.removeEventListener(type, handle);\n };\n}\n"]}
@@ -1,11 +1,12 @@
1
1
  // Copyright 2026 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
- let reloadVersion = 0;
4
+ import { cardLifetime } from './card-lifetime.js';
5
+ const state = /*#__PURE__*/ cardLifetime('reloadVersion', () => ({ value: 0 }));
5
6
  export function getReloadVersion() {
6
- return reloadVersion;
7
+ return state.value;
7
8
  }
8
9
  export function increaseReloadVersion() {
9
- return ++reloadVersion;
10
+ return ++state.value;
10
11
  }
11
12
  //# sourceMappingURL=reload-version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reload-version.js","sourceRoot":"","sources":["../../src/core/reload-version.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,IAAI,aAAa,GAAG,CAAC,CAAC;AAEtB,MAAM,UAAU,gBAAgB;IAC9B,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,MAAM,UAAU,qBAAqB;IACnC,OAAO,EAAE,aAAa,CAAC;AACzB,CAAC","sourcesContent":["// Copyright 2026 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\nlet reloadVersion = 0;\n\nexport function getReloadVersion(): number {\n return reloadVersion;\n}\n\nexport function increaseReloadVersion(): number {\n return ++reloadVersion;\n}\n"]}
1
+ {"version":3,"file":"reload-version.js","sourceRoot":"","sources":["../../src/core/reload-version.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,MAAM,KAAK,GAAG,aAAa,CAAC,YAAY,CAAC,eAAe,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AAEhF,MAAM,UAAU,gBAAgB;IAC9B,OAAO,KAAK,CAAC,KAAK,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,qBAAqB;IACnC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC;AACvB,CAAC","sourcesContent":["// Copyright 2026 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 { cardLifetime } from './card-lifetime.js';\n\nconst state = /*#__PURE__*/ cardLifetime('reloadVersion', () => ({ value: 0 }));\n\nexport function getReloadVersion(): number {\n return state.value;\n}\n\nexport function increaseReloadVersion(): number {\n return ++state.value;\n}\n"]}
@@ -1,4 +1,6 @@
1
1
  type DestroyTask = () => void;
2
+ export declare function isRuntimeDestroyed(): boolean;
3
+ export declare function destroyRuntime(): void;
2
4
  export declare function registerDestroyTask(task: DestroyTask): () => void;
3
5
  export declare function runDestroyTasks(): void;
4
6
  export {};
@@ -2,6 +2,15 @@
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
  const destroyTasks = new Set();
5
+ let destroyed = false;
6
+ // Calls from a retired entry stay pending: settling them would run its continuations.
7
+ export function isRuntimeDestroyed() {
8
+ return destroyed;
9
+ }
10
+ export function destroyRuntime() {
11
+ destroyed = true;
12
+ runDestroyTasks();
13
+ }
5
14
  export function registerDestroyTask(task) {
6
15
  destroyTasks.add(task);
7
16
  return () => {
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-destroy.js","sourceRoot":"","sources":["../../src/core/runtime-destroy.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAI1D,MAAM,YAAY,GAAG,IAAI,GAAG,EAAe,CAAC;AAE5C,MAAM,UAAU,mBAAmB,CAAC,IAAiB;IACnD,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,GAAG,EAAE;QACV,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,EAAE,CAAC;IACT,CAAC;IACD,YAAY,CAAC,KAAK,EAAE,CAAC;AACvB,CAAC","sourcesContent":["// Copyright 2026 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\ntype DestroyTask = () => void;\n\nconst destroyTasks = new Set<DestroyTask>();\n\nexport function registerDestroyTask(task: DestroyTask): () => void {\n destroyTasks.add(task);\n return () => {\n destroyTasks.delete(task);\n };\n}\n\nexport function runDestroyTasks(): void {\n const tasks = Array.from(destroyTasks);\n for (const task of tasks) {\n task();\n }\n destroyTasks.clear();\n}\n"]}
1
+ {"version":3,"file":"runtime-destroy.js","sourceRoot":"","sources":["../../src/core/runtime-destroy.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAI1D,MAAM,YAAY,GAAG,IAAI,GAAG,EAAe,CAAC;AAC5C,IAAI,SAAS,GAAG,KAAK,CAAC;AAEtB,sFAAsF;AACtF,MAAM,UAAU,kBAAkB;IAChC,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,cAAc;IAC5B,SAAS,GAAG,IAAI,CAAC;IACjB,eAAe,EAAE,CAAC;AACpB,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAiB;IACnD,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,GAAG,EAAE;QACV,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,EAAE,CAAC;IACT,CAAC;IACD,YAAY,CAAC,KAAK,EAAE,CAAC;AACvB,CAAC","sourcesContent":["// Copyright 2026 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\ntype DestroyTask = () => void;\n\nconst destroyTasks = new Set<DestroyTask>();\nlet destroyed = false;\n\n// Calls from a retired entry stay pending: settling them would run its continuations.\nexport function isRuntimeDestroyed(): boolean {\n return destroyed;\n}\n\nexport function destroyRuntime(): void {\n destroyed = true;\n runDestroyTasks();\n}\n\nexport function registerDestroyTask(task: DestroyTask): () => void {\n destroyTasks.add(task);\n return () => {\n destroyTasks.delete(task);\n };\n}\n\nexport function runDestroyTasks(): void {\n const tasks = Array.from(destroyTasks);\n for (const task of tasks) {\n task();\n }\n destroyTasks.clear();\n}\n"]}
@@ -7,6 +7,8 @@ import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
7
7
  import { registerBackgroundFunctionCtx } from '../background-function/run-on-background.js';
8
8
  import { isMainThreadFunction } from '../main-thread-function.js';
9
9
  import { isMtsEnabled } from '../mts-capability.js';
10
+ import { dispatchReloadScopedEvent } from '../reload-scoped-event.js';
11
+ import { isRuntimeDestroyed } from '../runtime-destroy.js';
10
12
  export let delayedRunOnMainThreadData = [];
11
13
  export function enqueueDelayedRunOnMainThreadData(data) {
12
14
  delayedRunOnMainThreadData.push(data);
@@ -29,6 +31,8 @@ export function createRunOnMainThread(options) {
29
31
  }
30
32
  return async (...params) => {
31
33
  return new Promise((resolve) => {
34
+ if (isRuntimeDestroyed())
35
+ return;
32
36
  const worklet = fn;
33
37
  prepareMainThreadFunctionCtx(worklet);
34
38
  const data = {
@@ -54,9 +58,6 @@ function prepareMainThreadFunctionCtx(worklet) {
54
58
  }
55
59
  }
56
60
  function dispatchRunOnMainThreadEvent(data) {
57
- lynx.getCoreContext().dispatchEvent({
58
- type: WorkletEvents.runWorkletCtx,
59
- data: JSON.stringify(data),
60
- });
61
+ dispatchReloadScopedEvent(lynx.getCoreContext(), { type: WorkletEvents.runWorkletCtx, data });
61
62
  }
62
63
  //# sourceMappingURL=main-thread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"main-thread.js","sourceRoot":"","sources":["../../../src/core/thread-function-call/main-thread.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,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C,CAAC;YAC1C,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,0BAA0B;IACjC,OAAO,cAAc,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,4BAA4B,CAAC,OAAgB;IACpD,IAAI,oBAAoB,CAAC,OAAO,CAAC,IAAI,0BAA0B,EAAE,EAAE,CAAC;QAClE,6BAA6B,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,4BAA4B,CAAC,IAAuB;IAC3D,IAAI,CAAC,cAAc,EAAE,CAAC,aAAa,CAAC;QAClC,IAAI,EAAE,aAAa,CAAC,aAAa;QACjC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2026 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 { onFunctionCall } from './return-value.js';\nimport { isSdkVersionGt } from '../../utils.js';\nimport { WorkletEvents } from '../../worklet-runtime/bindings/events.js';\nimport type { RunWorkletCtxData } from '../../worklet-runtime/bindings/events.js';\nimport type { Worklet } from '../../worklet-runtime/bindings/types.js';\nimport { registerBackgroundFunctionCtx } from '../background-function/run-on-background.js';\nimport { isMainThreadFunction } from '../main-thread-function.js';\nimport { isMtsEnabled } from '../mts-capability.js';\n\ninterface RunOnMainThreadOptions {\n shouldDispatchRunOnMainThreadDirectly: () => boolean;\n}\n\nexport type RunOnMainThread = <R, Fn extends (...args: any[]) => R>(fn: Fn) => (...args: Parameters<Fn>) => Promise<R>;\n\nexport let delayedRunOnMainThreadData: RunWorkletCtxData[] = [];\n\nexport function enqueueDelayedRunOnMainThreadData(data: RunWorkletCtxData): void {\n delayedRunOnMainThreadData.push(data);\n}\n\nexport function takeDelayedRunOnMainThreadData(): typeof delayedRunOnMainThreadData {\n const data = delayedRunOnMainThreadData;\n delayedRunOnMainThreadData = [];\n return data;\n}\n\n/**\n * @internal\n */\nexport function createRunOnMainThread(\n options: RunOnMainThreadOptions,\n): RunOnMainThread {\n return <R, Fn extends (...args: any[]) => R>(fn: Fn): (...args: Parameters<Fn>) => Promise<R> => {\n if (__LEPUS__) {\n throw new Error('runOnMainThread can only be used on the background thread.');\n }\n if (!isMtsEnabled()) {\n throw new Error('runOnMainThread requires Lynx sdk version 2.14.');\n }\n return async (...params: Parameters<Fn>): Promise<R> => {\n return new Promise((resolve) => {\n const worklet = fn as unknown as Worklet;\n prepareMainThreadFunctionCtx(worklet);\n const data = {\n worklet,\n params,\n resolveId: onFunctionCall(resolve),\n } as RunWorkletCtxData;\n\n if (options.shouldDispatchRunOnMainThreadDirectly()) {\n dispatchRunOnMainThreadEvent(data);\n return;\n }\n\n enqueueDelayedRunOnMainThreadData(data);\n });\n };\n };\n}\n\nfunction isRunOnBackgroundSupported(): boolean {\n return isSdkVersionGt(2, 15);\n}\n\nfunction prepareMainThreadFunctionCtx(worklet: unknown): void {\n if (isMainThreadFunction(worklet) && isRunOnBackgroundSupported()) {\n registerBackgroundFunctionCtx(worklet);\n }\n}\n\nfunction dispatchRunOnMainThreadEvent(data: RunWorkletCtxData): void {\n lynx.getCoreContext().dispatchEvent({\n type: WorkletEvents.runWorkletCtx,\n data: JSON.stringify(data),\n });\n}\n"]}
1
+ {"version":3,"file":"main-thread.js","sourceRoot":"","sources":["../../../src/core/thread-function-call/main-thread.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAGzE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6CAA6C,CAAC;AAC5F,OAAO,EAAE,oBAAoB,EAAE,M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C;YAC1C,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,0BAA0B;IACjC,OAAO,cAAc,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,4BAA4B,CAAC,OAAgB;IACpD,IAAI,oBAAoB,CAAC,OAAO,CAAC,IAAI,0BAA0B,EAAE,EAAE,CAAC;QAClE,6BAA6B,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,4BAA4B,CAAC,IAAuB;IAC3D,yBAAyB,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,EAAE,IAAI,EAAE,aAAa,CAAC,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;AAChG,CAAC","sourcesContent":["// Copyright 2026 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 { onFunctionCall } from './return-value.js';\nimport { isSdkVersionGt } from '../../utils.js';\nimport { WorkletEvents } from '../../worklet-runtime/bindings/events.js';\nimport type { RunWorkletCtxData } from '../../worklet-runtime/bindings/events.js';\nimport type { Worklet } from '../../worklet-runtime/bindings/types.js';\nimport { registerBackgroundFunctionCtx } from '../background-function/run-on-background.js';\nimport { isMainThreadFunction } from '../main-thread-function.js';\nimport { isMtsEnabled } from '../mts-capability.js';\nimport { dispatchReloadScopedEvent } from '../reload-scoped-event.js';\nimport { isRuntimeDestroyed } from '../runtime-destroy.js';\n\ninterface RunOnMainThreadOptions {\n shouldDispatchRunOnMainThreadDirectly: () => boolean;\n}\n\nexport type RunOnMainThread = <R, Fn extends (...args: any[]) => R>(fn: Fn) => (...args: Parameters<Fn>) => Promise<R>;\n\nexport let delayedRunOnMainThreadData: RunWorkletCtxData[] = [];\n\nexport function enqueueDelayedRunOnMainThreadData(data: RunWorkletCtxData): void {\n delayedRunOnMainThreadData.push(data);\n}\n\nexport function takeDelayedRunOnMainThreadData(): typeof delayedRunOnMainThreadData {\n const data = delayedRunOnMainThreadData;\n delayedRunOnMainThreadData = [];\n return data;\n}\n\n/**\n * @internal\n */\nexport function createRunOnMainThread(\n options: RunOnMainThreadOptions,\n): RunOnMainThread {\n return <R, Fn extends (...args: any[]) => R>(fn: Fn): (...args: Parameters<Fn>) => Promise<R> => {\n if (__LEPUS__) {\n throw new Error('runOnMainThread can only be used on the background thread.');\n }\n if (!isMtsEnabled()) {\n throw new Error('runOnMainThread requires Lynx sdk version 2.14.');\n }\n return async (...params: Parameters<Fn>): Promise<R> => {\n return new Promise((resolve) => {\n if (isRuntimeDestroyed()) return;\n const worklet = fn as unknown as Worklet;\n prepareMainThreadFunctionCtx(worklet);\n const data = {\n worklet,\n params,\n resolveId: onFunctionCall(resolve),\n } as RunWorkletCtxData;\n\n if (options.shouldDispatchRunOnMainThreadDirectly()) {\n dispatchRunOnMainThreadEvent(data);\n return;\n }\n\n enqueueDelayedRunOnMainThreadData(data);\n });\n };\n };\n}\n\nfunction isRunOnBackgroundSupported(): boolean {\n return isSdkVersionGt(2, 15);\n}\n\nfunction prepareMainThreadFunctionCtx(worklet: unknown): void {\n if (isMainThreadFunction(worklet) && isRunOnBackgroundSupported()) {\n registerBackgroundFunctionCtx(worklet);\n }\n}\n\nfunction dispatchRunOnMainThreadEvent(data: RunWorkletCtxData): void {\n dispatchReloadScopedEvent(lynx.getCoreContext(), { type: WorkletEvents.runWorkletCtx, data });\n}\n"]}
@@ -3,16 +3,18 @@
3
3
  // LICENSE file in the root directory of this source tree.
4
4
  import { IndexMap } from '../../shared/index-map.js';
5
5
  import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
6
+ import { cardLifetime } from '../card-lifetime.js';
7
+ import { addReloadScopedEventListener } from '../reload-scoped-event.js';
6
8
  import { registerDestroyTask } from '../runtime-destroy.js';
7
9
  let resolveMap;
8
10
  let cleanupReturnValueListener;
9
11
  let unregisterReturnValueCleanup;
10
12
  function initReturnValueListener() {
11
13
  const context = __JS__ ? lynx.getCoreContext() : lynx.getJSContext();
12
- resolveMap = new IndexMap();
13
- context.addEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
14
+ resolveMap = new IndexMap(cardLifetime('functionCallId', () => ({ lastIndex: 0 })));
15
+ const removeListener = addReloadScopedEventListener(context, WorkletEvents.FunctionCallRet, onFunctionCallRet);
14
16
  cleanupReturnValueListener = () => {
15
- context.removeEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
17
+ removeListener();
16
18
  resolveMap = undefined;
17
19
  cleanupReturnValueListener = undefined;
18
20
  };
@@ -51,8 +53,7 @@ export function dropFunctionCallReturnIds(resolveIds) {
51
53
  resetFunctionCallReturnListener();
52
54
  }
53
55
  }
54
- function onFunctionCallRet(event) {
55
- const data = JSON.parse(event.data);
56
+ function onFunctionCallRet(data) {
56
57
  const map = resolveMap;
57
58
  if (!map) {
58
59
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"return-value.js","sourceRoot":"","sources":["../../../src/core/thread-function-call/return-value.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAEzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,IAAI,UAAsD,CAAC;AAC3D,IAAI,0BAAoD,CAAC;AACzD,IAAI,4BAAsD,CAAC;AAE3D,SAAS,uBAAuB;IAC9B,MAAM,OAAO,GAAiB,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;IAEnF,UAAU,GAAG,IAAI,QAAQ,EAAE,CAAC;IAC5B,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC,eAAe,EAAE,iBAAiB,CAAC,CAAC;IAE3E,0BAA0B,GAAG,GAAG,EAA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AM,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACxC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO;IACT,CAAC;IACD,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC3B,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC5B,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.\n\nimport { IndexMap } from '../../shared/index-map.js';\nimport { WorkletEvents } from '../../worklet-runtime/bindings/events.js';\nimport type { RunWorkletCtxRetData } from '../../worklet-runtime/bindings/events.js';\nimport { registerDestroyTask } from '../runtime-destroy.js';\n\nlet resolveMap: IndexMap<(value: any) => void> | undefined;\nlet cleanupReturnValueListener: (() => void) | undefined;\nlet unregisterReturnValueCleanup: (() => void) | undefined;\n\nfunction initReturnValueListener(): void {\n const context: RuntimeProxy = __JS__ ? lynx.getCoreContext() : lynx.getJSContext();\n\n resolveMap = new IndexMap();\n context.addEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);\n\n cleanupReturnValueListener = () => {\n context.removeEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);\n resolveMap = undefined;\n cleanupReturnValueListener = undefined;\n };\n}\n\n/**\n * @internal\n */\nexport function onFunctionCall(resolve: (value: any) => void): number {\n ensureFunctionCallReturnCleanup();\n if (!resolveMap) {\n initReturnValueListener();\n }\n return resolveMap!.add(resolve);\n}\n\nfunction ensureFunctionCallReturnCleanup(): void {\n if (unregisterReturnValueCleanup) {\n return;\n }\n unregisterReturnValueCleanup = registerDestroyTask(() => {\n resetFunctionCallReturnListener();\n });\n}\n\nexport function resetFunctionCallReturnListener(): void {\n cleanupReturnValueListener?.();\n unregisterReturnValueCleanup?.();\n unregisterReturnValueCleanup = undefined;\n}\n\nexport function dropFunctionCallReturnIds(resolveIds: readonly number[]): void {\n if (!resolveMap) {\n return;\n }\n for (const resolveId of resolveIds) {\n resolveMap.remove(resolveId);\n }\n if (resolveMap.size === 0) {\n resetFunctionCallReturnListener();\n }\n}\n\nfunction onFunctionCallRet(event: RuntimeProxy.Event): void {\n const data = JSON.parse(event.data as string) as RunWorkletCtxRetData;\n const map = resolveMap;\n if (!map) {\n return;\n }\n const resolve = map.get(data.resolveId);\n if (!resolve) {\n return;\n }\n map.remove(data.resolveId);\n resolve(data.returnValue);\n}\n"]}
1
+ {"version":3,"file":"return-value.js","sourceRoot":"","sources":["../../../src/core/thread-function-call/return-value.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAEzE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,IAAI,UAAsD,CAAC;AAC3D,IAAI,0BAAoD,CAAC;AACzD,IAAI,4BAAsD,CAAC;AAE3D,SAAS,uBAAuB;IAC9B,MAAM,OAAO,GAAiB,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;IAEnF,UAAU,GAAG,IAAI,QAAQ,CAAC,YAAY,CAAC,gBAAgB,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACpF,MAAM,cAAc,GAAG,4BAA4B,CAAC,OAAO,EAAE,aAAa,CAAC,eAAe,EAAE,iBAAiB,CAAC,CAAC;IAE/G,0BAA0B,GAAG,GAAG,EAAE;QAChC,cAAc,EAAE,CAAC;QACjB,UAAU,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S,CAAC,CAAC;IAC3B,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC5B,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.\n\nimport { IndexMap } from '../../shared/index-map.js';\nimport { WorkletEvents } from '../../worklet-runtime/bindings/events.js';\nimport type { RunWorkletCtxRetData } from '../../worklet-runtime/bindings/events.js';\nimport { cardLifetime } from '../card-lifetime.js';\nimport { addReloadScopedEventListener } from '../reload-scoped-event.js';\nimport { registerDestroyTask } from '../runtime-destroy.js';\n\nlet resolveMap: IndexMap<(value: any) => void> | undefined;\nlet cleanupReturnValueListener: (() => void) | undefined;\nlet unregisterReturnValueCleanup: (() => void) | undefined;\n\nfunction initReturnValueListener(): void {\n const context: RuntimeProxy = __JS__ ? lynx.getCoreContext() : lynx.getJSContext();\n\n resolveMap = new IndexMap(cardLifetime('functionCallId', () => ({ lastIndex: 0 })));\n const removeListener = addReloadScopedEventListener(context, WorkletEvents.FunctionCallRet, onFunctionCallRet);\n\n cleanupReturnValueListener = () => {\n removeListener();\n resolveMap = undefined;\n cleanupReturnValueListener = undefined;\n };\n}\n\n/**\n * @internal\n */\nexport function onFunctionCall(resolve: (value: any) => void): number {\n ensureFunctionCallReturnCleanup();\n if (!resolveMap) {\n initReturnValueListener();\n }\n return resolveMap!.add(resolve);\n}\n\nfunction ensureFunctionCallReturnCleanup(): void {\n if (unregisterReturnValueCleanup) {\n return;\n }\n unregisterReturnValueCleanup = registerDestroyTask(() => {\n resetFunctionCallReturnListener();\n });\n}\n\nexport function resetFunctionCallReturnListener(): void {\n cleanupReturnValueListener?.();\n unregisterReturnValueCleanup?.();\n unregisterReturnValueCleanup = undefined;\n}\n\nexport function dropFunctionCallReturnIds(resolveIds: readonly number[]): void {\n if (!resolveMap) {\n return;\n }\n for (const resolveId of resolveIds) {\n resolveMap.remove(resolveId);\n }\n if (resolveMap.size === 0) {\n resetFunctionCallReturnListener();\n }\n}\n\nfunction onFunctionCallRet(data: RunWorkletCtxRetData): void {\n const map = resolveMap;\n if (!map) {\n return;\n }\n const resolve = map.get(data.resolveId);\n if (!resolve) {\n return;\n }\n map.remove(data.resolveId);\n resolve(data.returnValue);\n}\n"]}