'use strict'; import { isBundleModeEnabled } from '../debug/bundleMode'; import { registerWorkletStackDetails } from '../debug/errors'; import { jsVersion } from '../debug/jsVersion'; import { logger } from '../debug/logger'; import { getRuntimeKind, RuntimeKind } from '../runtimeKind'; import type { WorkletFunction, WorkletImport } from '../types'; import { isWorkletFunction } from '../workletFunction'; import { WorkletsModule } from '../WorkletsModule/NativeWorklets'; import { isSynchronizable } from './isSynchronizable'; import { RemoteFunctionBearingEntry, remoteFunctionBearingFlag, } from './remoteFunctionBearingEntry'; import { serializableMappingCache, serializableMappingEntries, serializableMappingFlag, } from './serializableMappingCache'; import type { FlatSerializableRef, RegistrationData, RemoteFunction, SerializableRef, SerializationData, Synchronizable, } from './types'; const MAGIC_KEY = 'REANIMATED_MAGIC_KEY'; function isHostObject(value: NonNullable) { 'worklet'; // We could use JSI to determine whether an object is a host object, however // the below workaround works well and is way faster than an additional JSI call. // We use the fact that host objects have broken implementation of `hasOwnProperty` // and hence return true for all `in` checks regardless of the key we ask for. return MAGIC_KEY in value; } export function isSerializableRef( value: unknown ): value is SerializableRef { 'worklet'; return ( typeof value === 'object' && value !== null && '__serializableRef' in value && value.__serializableRef === true ); } function isPlainJSObject(object: object): object is Record { 'worklet'; return Object.getPrototypeOf(object) === Object.prototype; } /** * RN has introduced a new representation of TurboModules as a JS object whose * prototype is the host object. More details: * https://github.com/facebook/react-native/blob/main/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.cpp#L182 */ function isTurboModuleLike(object: object): object is Record { const proto = Object.getPrototypeOf(object); return proto !== null && isHostObject(proto); } /** * How many times `createSerializable` has returned a clone that holds a JS * function: a remote function, new or cached, or a cache hit whose entry is * tagged as one (`remoteFunctionBearingFlag` or a * `RemoteFunctionBearingEntry`). A container holds a JS function exactly when * this changed while its children were cloned, so a subtree without one costs a * read before and a comparison after, and nothing per child. It only grows, * apart from the resets around the user's `determine` and `pack`, so a throw * caught in the middle of a traversal cannot hide a function seen before it. */ let functionsSeen = 0; function markRemoteFunctionBearing(clone: object): void { serializableMappingEntries.set(clone, remoteFunctionBearingFlag); } function markIfRemoteFunctionBearing( clone: TClone, holdsFunction: boolean ): TClone { if (holdsFunction) { markRemoteFunctionBearing(clone); } return clone; } /** * Caches `value -> clone`. A clone that holds a JS function and is not * persisted is cached through a non-owning marker, so the cache never keeps it * alive on its own. While something else owns the clone, a cache hit returns * the same native serializable (and so the same copy on the other runtime), * through the clone itself while it is alive. Once it was released, `value` is * serialized again. */ function cacheClone( value: object, clone: SerializableRef, holdsFunction: boolean, shouldPersistRemote: boolean ) { if (holdsFunction) { serializableMappingEntries.set( value, RemoteFunctionBearingEntry.forClone(clone, shouldPersistRemote) ); markRemoteFunctionBearing(clone); return; } serializableMappingEntries.set(value, clone); serializableMappingEntries.set(clone, serializableMappingFlag); } /** * Returns the clone cached for `value`, or `undefined` when there is none or it * was released. Counts a hit on a clone that holds a JS function in * `functionsSeen` unless `countHit` is false. A hit on any other clone costs no * lookup beyond the entry. */ function getFromCache(value: object, countHit = true) { const cached = serializableMappingEntries.get(value); if (cached === undefined) { return undefined; } if (cached === serializableMappingFlag) { // This means that `value` was already a clone and we should return it as is. return value; } const tag = (cached as { __serializableRef?: unknown }).__serializableRef; if (tag === true) { // A serializable stored as is holds no JS function, because one that does // is stored in a `RemoteFunctionBearingEntry`. return cached; } if (tag === false) { const clone = (cached as RemoteFunctionBearingEntry).deref( markRemoteFunctionBearing ); if (clone !== undefined && countHit) { functionsSeen++; } return clone; } if (cached === remoteFunctionBearingFlag) { if (countHit) { functionsSeen++; } return value; } return cached; } /** * The serializable cached for `value`, or `undefined` when there is none or it * was released. Unlike a raw cache read, it never returns the non-owning marker * or `WeakRef` that stands in for a clone holding a JS function. */ export function getCachedSerializable( value: object ): SerializableRef | undefined { return getFromCache(value, false) as SerializableRef | undefined; } const VALID_ARRAY_VIEWS_NAMES = [ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array', 'DataView', ]; const DETECT_CYCLIC_OBJECT_DEPTH_THRESHOLD = 30; // Below variable stores object that we process in createSerializable at the specified depth. // We use it to check if later on the function reenters with the same object let processedObjectAtThresholdDepth: unknown; const serializationPathStack: string[] = []; function withPathSegment(segment: string, serialize: () => TValue) { serializationPathStack.push(segment); try { return serialize(); } finally { serializationPathStack.pop(); } } function formatSerializationPath(): string { return serializationPathStack.join(''); } export function createSerializable( value: TValue, shouldPersistRemote = false, depth = 0 ): SerializableRef { detectCyclicObject(value, depth); const isFunction = typeof value === 'function'; if (typeof value === 'string') { return cloneString(value) as SerializableRef; } if (typeof value === 'number') { return cloneNumber(value) as SerializableRef; } if (typeof value === 'boolean') { return cloneBoolean(value) as SerializableRef; } if (typeof value === 'bigint') { return cloneBigInt(value) as SerializableRef; } if (typeof value === 'symbol') { return cloneString(String(value)) as SerializableRef; } if (value === undefined) { return cloneUndefined() as SerializableRef; } if (value === null) { return cloneNull() as SerializableRef; } const cached = getFromCache(value); if (cached !== undefined) { return cached as SerializableRef; } if (Array.isArray(value)) { return cloneArray(value, shouldPersistRemote, depth); } if (isFunction) { if (globalThis._WORKLETS_BUNDLE_MODE_ENABLED) { if ((value as unknown as WorkletImport).__bundleData) { return cloneImport( value as unknown as WorkletImport ) as SerializableRef; } } if ((value as unknown as RemoteFunction).__remoteFunction) { // Remote functions are already serialized. functionsSeen++; return value as unknown as SerializableRef; } if (!isWorkletFunction(value)) { return cloneNonWorkletFunction( value as () => unknown ) as SerializableRef; } } if (isTurboModuleLike(value)) { return cloneTurboModuleLike(value, shouldPersistRemote, depth); } if (isHostObject(value)) { return cloneHostObject(value); } if ((isPlainJSObject(value) || isFunction) && isWorkletFunction(value)) { return cloneWorklet(value, shouldPersistRemote, depth); } if (isSynchronizable(value)) { return cloneSynchronizable(value) as SerializableRef; } if (isPlainJSObject(value) || isFunction) { return clonePlainJSObject(value, shouldPersistRemote, depth); } if (value instanceof Set) { return cloneSet(value) as SerializableRef; } if (value instanceof Map) { return cloneMap(value) as SerializableRef; } if (value instanceof RegExp) { return cloneRegExp(value) as SerializableRef; } if (value instanceof Error) { return cloneError(value) as SerializableRef; } if (value instanceof ArrayBuffer) { return cloneArrayBuffer(value) as SerializableRef; } if (ArrayBuffer.isView(value)) { // typed array (e.g. Int32Array, Uint8ClampedArray) or DataView return cloneArrayBufferView(value); } const seen = functionsSeen; for (let i = 0; i < customSerializationRegistry.length; i++) { const { determine, pack } = customSerializationRegistry[i]; const matches = determine(value); // `determine` is user code. Whatever it serializes is not part of `value`. functionsSeen = seen; if (matches) { return cloneCustom(value, pack, i) as SerializableRef; } } if (__DEV__) { const constructorName = (value as { constructor?: { name?: string } })?.constructor?.name || 'unknown'; const path = formatSerializationPath(); const location = path ? ` It was located at \`${path}\`.` : ''; console.warn( `[Worklets] Cannot copy value of type \`${constructorName}\`.${location}` ); } return cloneUndefined() as SerializableRef; } if (isBundleModeEnabled()) { // TODO: Do it programmatically. createSerializable.__bundleData = { imported: 'createSerializable', source: require.resolveWeak('react-native-worklets'), }; } export function createSerializableArray( value: TValue ): SerializableRef { if (__DEV__ && !Array.isArray(value)) { throw new Error('[Worklets] `createSerializableArray` expects an array.'); } return ( (getFromCache(value) as SerializableRef | undefined) ?? cloneArray(value, false, 0) ); } export function createSerializableObject( value: TValue ): SerializableRef { if ( __DEV__ && (typeof value !== 'object' || value === null || !isPlainJSObject(value) || isSynchronizable(value) || isWorkletFunction(value)) ) { throw new Error( '[Worklets] `createSerializableObject` expects a plain object.' ); } return ( (getFromCache(value) as SerializableRef | undefined) ?? clonePlainJSObject(value, false, 0) ); } export function createSerializableMap( value: Map ): SerializableRef> { if (__DEV__ && !(value instanceof Map)) { throw new Error('[Worklets] `createSerializableMap` expects a Map.'); } return ((getFromCache(value) as SerializableRef>) ?? cloneMap(value)) as SerializableRef>; } export function createSerializableSet( value: Set ): SerializableRef> { if (__DEV__ && !(value instanceof Set)) { throw new Error('[Worklets] `createSerializableSet` expects a Set.'); } return ((getFromCache(value) as SerializableRef>) ?? cloneSet(value)) as SerializableRef>; } export function createSerializableError( value: TValue ): SerializableRef { if (__DEV__ && !(value instanceof Error)) { throw new Error('[Worklets] `createSerializableError` expects an Error.'); } return ((getFromCache(value) as SerializableRef) ?? cloneError(value)) as SerializableRef; } export function createSerializableRegExp( value: RegExp ): SerializableRef { if (__DEV__ && !(value instanceof RegExp)) { throw new Error('[Worklets] `createSerializableRegExp` expects a RegExp.'); } return ( (getFromCache(value) as SerializableRef | undefined) ?? cloneRegExp(value) ); } export function createSerializableArrayBuffer( value: ArrayBuffer ): SerializableRef { if (__DEV__ && !(value instanceof ArrayBuffer)) { throw new Error( '[Worklets] `createSerializableArrayBuffer` expects an ArrayBuffer.' ); } return ( (getFromCache(value) as SerializableRef | undefined) ?? cloneArrayBuffer(value) ); } export function createSerializableArrayBufferView< TValue extends ArrayBufferView, >(value: TValue): SerializableRef { if (__DEV__ && !ArrayBuffer.isView(value)) { throw new Error( '[Worklets] `createSerializableArrayBufferView` expects a typed array or a DataView.' ); } return ( (getFromCache(value) as SerializableRef | undefined) ?? cloneArrayBufferView(value) ); } export function createSerializableHostObject( value: TValue ): SerializableRef { if ( __DEV__ && (typeof value !== 'object' || value === null || !isHostObject(value)) ) { throw new Error( '[Worklets] `createSerializableHostObject` expects a host object.' ); } return ( (getFromCache(value) as SerializableRef | undefined) ?? cloneHostObject(value) ); } export function createSerializableString( value: string ): SerializableRef { if (__DEV__ && typeof value !== 'string') { throw new Error('[Worklets] `createSerializableString` expects a string.'); } const clone = cloneString(value); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } export function createSerializableNumber( value: number ): SerializableRef { if (__DEV__ && typeof value !== 'number') { throw new Error('[Worklets] `createSerializableNumber` expects a number.'); } const clone = cloneNumber(value); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } export function createSerializableBoolean( value: boolean ): SerializableRef { if (__DEV__ && typeof value !== 'boolean') { throw new Error( '[Worklets] `createSerializableBoolean` expects a boolean.' ); } const clone = cloneBoolean(value); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } export function createSerializableBigInt( value: bigint ): SerializableRef { if (__DEV__ && typeof value !== 'bigint') { throw new Error('[Worklets] `createSerializableBigInt` expects a bigint.'); } const clone = cloneBigInt(value); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } export function createSerializableNull(value: null): SerializableRef { if (__DEV__ && value !== null) { throw new Error('[Worklets] `createSerializableNull` expects null.'); } const clone = cloneNull(); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } export function createSerializableUndefined( value: undefined ): SerializableRef { if (__DEV__ && value !== undefined) { throw new Error( '[Worklets] `createSerializableUndefined` expects undefined.' ); } const clone = cloneUndefined(); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } export function createSerializableWorklet< TValue extends (...args: never[]) => unknown, >(value: TValue): SerializableRef { if (__DEV__ && !isWorkletFunction(value)) { throw new Error( '[Worklets] `createSerializableWorklet` expects a worklet.' ); } return ( (getFromCache(value) as SerializableRef | undefined) ?? (cloneWorklet( value as unknown as WorkletFunction, false, 0 ) as unknown as SerializableRef) ); } export function createSerializableRemoteFunction< TValue extends (...args: never[]) => unknown, >(value: TValue): SerializableRef { if (__DEV__ && (typeof value !== 'function' || isWorkletFunction(value))) { throw new Error( '[Worklets] `createSerializableRemoteFunction` expects a function that is not a worklet.' ); } return ( (getFromCache(value) as SerializableRef | undefined) ?? (cloneNonWorkletFunction( value as unknown as () => unknown ) as unknown as SerializableRef) ); } if (!globalThis.__customSerializationRegistry) { globalThis.__customSerializationRegistry = [] as typeof globalThis.__customSerializationRegistry; } const customSerializationRegistry = globalThis.__customSerializationRegistry; /** * `registerCustomSerializable` lets you register your own pre-serialization and * post-deserialization logic. This is necessary for objects with prototypes * different than just `Object.prototype` or some other built-in prototypes like * `Map` etc. Worklets can't handle such objects by default to convert into * [Serializables](https://docs.swmansion.com/react-native-worklets/docs/memory/serializable) * hence you need to register them as **Custom Serializables**. This way you can * tell Worklets how to transfer your custom data structures between different * Runtimes without manually serializing and deserializing them every time. * * @param registrationData - The registration data for the custom serializable - * {@link RegistrationData} * @see https://docs.swmansion.com/react-native-worklets/docs/memory/registerCustomSerializable/ */ export function registerCustomSerializable< TValue extends object, TPacked extends object, >(registrationData: RegistrationData) { if (__DEV__ && getRuntimeKind() !== RuntimeKind.ReactNative) { throw new Error( '[Worklets] registerCustomSerializable can be used only on React Native runtime.' ); } const { name, determine, pack, unpack } = registrationData; if (__DEV__) { verifyRegistrationData(determine, pack, unpack); } if (customSerializationRegistry.some((data) => data.name === name)) { if (__DEV__) { console.warn( `Custom serializable with name "${name}" is already registered. Duplicate registration is ignored.` ); } return; } customSerializationRegistry.push( registrationData as unknown as SerializationData ); WorkletsModule.registerCustomSerializable( createSerializable(determine), createSerializable(pack), createSerializable(unpack), customSerializationRegistry.length - 1 ); } function verifyRegistrationData( determine: unknown, pack: unknown, unpack: unknown ) { if (!isWorkletFunction(determine)) { throw new Error( '[Worklets] The "determine" function provided to registerCustomSerializable must be a worklet.' ); } if (!isWorkletFunction(pack)) { throw new Error( '[Worklets] The "pack" function provided to registerCustomSerializable must be a worklet.' ); } if (!isWorkletFunction(unpack)) { throw new Error( '[Worklets] The "unpack" function provided to registerCustomSerializable must be a worklet.' ); } } function detectCyclicObject(value: unknown, depth: number) { if (depth >= DETECT_CYCLIC_OBJECT_DEPTH_THRESHOLD) { // if we reach certain recursion depth we suspect that we are dealing with a cyclic object. // this type of objects are not supported and cannot be transferred as serializable, so we // implement a simple detection mechanism that remembers the value at a given depth and // tests whether we try reenter this method later on with the same value. If that happens // we throw an appropriate error. if (depth === DETECT_CYCLIC_OBJECT_DEPTH_THRESHOLD) { processedObjectAtThresholdDepth = value; } else if (value === processedObjectAtThresholdDepth) { throw new Error( '[Worklets] Trying to convert a cyclic object to a serializable. This is not supported.' ); } } else { processedObjectAtThresholdDepth = undefined; } } function cloneString(value: string): SerializableRef { return WorkletsModule.createSerializableString(value); } function cloneNumber(value: number): SerializableRef { return WorkletsModule.createSerializableNumber(value); } function cloneBoolean(value: boolean): SerializableRef { return WorkletsModule.createSerializableBoolean(value); } function cloneBigInt(value: bigint): SerializableRef { return WorkletsModule.createSerializableBigInt(value); } function cloneUndefined(): SerializableRef { return WorkletsModule.createSerializableUndefined(); } function cloneNull(): SerializableRef { return WorkletsModule.createSerializableNull(); } function cloneObjectProperties( value: T, shouldPersistRemote: boolean, depth: number ): Record { const clonedProps: Record = Object.create(null); for (const [key, element] of Object.entries(value)) { // We don't need to clone __initData field as it contains long strings // representing the worklet code, source map, and location, and we will // serialize/deserialize it once. if (key === '__initData' && clonedProps.__initData !== undefined) { continue; } if (__DEV__) { clonedProps[key] = withPathSegment(`[${JSON.stringify(key)}]`, () => createSerializable(element, shouldPersistRemote, depth + 1) ); } else { clonedProps[key] = createSerializable( element, shouldPersistRemote, depth + 1 ); } } return clonedProps; } function cloneArray( value: T, shouldPersistRemote: boolean, depth: number ): SerializableRef { const seen = functionsSeen; const clonedElements = value.map((element, index) => __DEV__ ? withPathSegment(`[${index}]`, () => createSerializable(element, shouldPersistRemote, depth + 1) ) : createSerializable(element, shouldPersistRemote, depth + 1) ); const clone = WorkletsModule.createSerializableArray( clonedElements, shouldPersistRemote ) as SerializableRef; cacheClone(value, clone, functionsSeen !== seen, shouldPersistRemote); freezeObjectInDev(value); return clone; } function cloneNonWorkletFunction( fun: (...args: TArgs) => TReturn ): SerializableRef<(...args: TArgs) => TReturn> { const clone = WorkletsModule.createSerializableNonWorkletFunction( fun, __DEV__ ? fun.name : undefined ) as SerializableRef<(...args: TArgs) => TReturn>; functionsSeen++; if (globalThis.WeakRef) { // WeakRef is installed on runtimes only with Hermes microtaskQueue enabled. serializableMappingEntries.set( fun, RemoteFunctionBearingEntry.forRemoteFunction(clone) ); } markRemoteFunctionBearing(clone); freezeObjectInDev(fun); return clone; } function cloneHostObject(value: T): SerializableRef { // for host objects we pass the reference to the object as serializable and // then recreate new host object wrapping the same instance on the UI thread. // there is no point of iterating over keys as we do for regular objects. const clone = WorkletsModule.createSerializableHostObject(value); serializableMappingEntries.set(value, clone); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } function cloneWorklet( value: TValue, shouldPersistRemote: boolean, depth: number ): SerializableRef { if (__DEV__) { const babelVersion = (value as WorkletFunction).__pluginVersion; if (babelVersion !== undefined && babelVersion !== jsVersion) { throw new Error( `[Worklets] Mismatch between JavaScript code version and Worklets Babel plugin version (${jsVersion} vs. ${babelVersion}). See \`https://docs.swmansion.com/react-native-worklets/docs/guides/troubleshooting#mismatch-between-javascript-code-version-and-worklets-babel-plugin-version\` for more details. Offending code was: \`${getWorkletCode(value)}\`` ); } // `__stackDetails` is deleted below, so a worklet cloned again after its // cached clone was released has none. Keep what the first clone registered. const stackDetails = (value as WorkletFunction).__stackDetails; if (stackDetails) { registerWorkletStackDetails(value.__workletHash, stackDetails); } } if ((value as WorkletFunction).__stackDetails) { // `Error` type of value cannot be copied to the UI thread, so we // remove it after we handled it in dev mode or delete it to ignore it in production mode. // Not removing this would cause an infinite loop in production mode and it just // seems more elegant to handle it this way. delete (value as WorkletFunction).__stackDetails; } const buildClone = (): SerializableRef => { const seen = functionsSeen; const clonedProps: Record = cloneObjectProperties( value, shouldPersistRemote, depth ); // to save on transferring static __initData field of worklet structure // we request serializable value to persist its UI counterpart. This means // that the __initData field that contains long strings representing the // worklet code, source map, and location, will always be // serialized/deserialized once. clonedProps.__initData = __DEV__ ? withPathSegment('["__initData"]', () => createSerializable(value.__initData, true, depth + 1) ) : createSerializable(value.__initData, true, depth + 1); const clone = WorkletsModule.createSerializableWorklet( clonedProps, // TODO: Check after refactor if we can remove shouldPersistRemote parameter (imho it's redundant here since worklets are always persistent) // retain all worklets true ) as SerializableRef; cacheClone(value, clone, functionsSeen !== seen, shouldPersistRemote); freezeObjectInDev(value); return clone; }; return __DEV__ ? withPathSegment(``, buildClone) : buildClone(); } /** * TurboModuleLike objects are JS objects that have a TurboModule as their * prototype. */ function cloneTurboModuleLike( value: TValue, shouldPersistRemote: boolean, depth: number ): SerializableRef { const proto = Object.getPrototypeOf(value); const seen = functionsSeen; const clonedProps = cloneObjectProperties(value, shouldPersistRemote, depth); const clone = WorkletsModule.createSerializableTurboModuleLike( clonedProps, proto ) as SerializableRef; return markIfRemoteFunctionBearing(clone, functionsSeen !== seen); } function clonePlainJSObject( value: TValue, shouldPersistRemote: boolean, depth: number ): SerializableRef { const seen = functionsSeen; const clonedProps: Record = cloneObjectProperties( value, shouldPersistRemote, depth ); const clone = WorkletsModule.createSerializableObject( clonedProps, shouldPersistRemote, value ) as SerializableRef; cacheClone(value, clone, functionsSeen !== seen, shouldPersistRemote); freezeObjectInDev(value); return clone; } function cloneMap( value: Map ): SerializableRef> { const clonedKeys: unknown[] = []; const clonedValues: unknown[] = []; const seen = functionsSeen; let index = 0; for (const [key, element] of value.entries()) { if (__DEV__) { clonedKeys.push( withPathSegment(`.keys()[${index}]`, () => createSerializable(key)) ); clonedValues.push( withPathSegment(`.values()[${index}]`, () => createSerializable(element) ) ); index++; } else { clonedKeys.push(createSerializable(key)); clonedValues.push(createSerializable(element)); } } const clone = WorkletsModule.createSerializableMap(clonedKeys, clonedValues); cacheClone(value, clone, functionsSeen !== seen, false); freezeObjectInDev(value); return clone; } function cloneSet(value: Set): SerializableRef> { const clonedElements: unknown[] = []; const seen = functionsSeen; let index = 0; for (const element of value) { if (__DEV__) { clonedElements.push( withPathSegment(`.values()[${index}]`, () => createSerializable(element) ) ); index++; } else { clonedElements.push(createSerializable(element)); } } const clone = WorkletsModule.createSerializableSet(clonedElements); cacheClone(value, clone, functionsSeen !== seen, false); freezeObjectInDev(value); return clone; } function cloneRegExp(value: RegExp): SerializableRef { const clone = WorkletsModule.createSerializableRegExp( value.source, value.flags ); serializableMappingEntries.set(value, clone); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } function cloneError(value: Error): SerializableRef { const { name, message, stack } = value; const clone = WorkletsModule.createSerializableError(name, message, stack); serializableMappingEntries.set(value, clone); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } function cloneArrayBuffer( arrayBuffer: ArrayBuffer ): SerializableRef { const clone = WorkletsModule.createSerializableArrayBuffer(arrayBuffer); serializableMappingEntries.set(arrayBuffer, clone); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } function cloneArrayBufferView( value: TValue ): SerializableRef { const typeName = value.constructor.name; if (!VALID_ARRAY_VIEWS_NAMES.includes(typeName)) { throw new Error(`[Worklets] Invalid array view name \`${typeName}\`.`); } const length = typeName === 'DataView' ? value.byteLength : (value as unknown as { length: number }).length; const clone = WorkletsModule.createSerializableArrayBufferView( typeName, value.buffer as ArrayBuffer, value.byteOffset, length ); serializableMappingEntries.set(value, clone); serializableMappingEntries.set(clone, serializableMappingFlag); return clone; } function cloneSynchronizable( value: Synchronizable ): SerializableRef { serializableMappingEntries.set(value, serializableMappingFlag); return value; } function cloneImport( value: TValue ): SerializableRef { const { source, imported } = value.__bundleData; const clone = WorkletsModule.createSerializableImport(source, imported); serializableMappingEntries.set(value, clone); serializableMappingEntries.set(clone, serializableMappingFlag); return clone as SerializableRef; } function cloneCustom( data: TValue, pack: (data: TValue) => TPacked, typeId: number ): SerializableRef { const seen = functionsSeen; const packedData = pack(data); // `pack` is user code. Whatever it serializes is not part of `data`. functionsSeen = seen; const serialized = __DEV__ ? withPathSegment('.pack()', () => createSerializable(packedData)) : createSerializable(packedData); return markIfRemoteFunctionBearing( WorkletsModule.createCustomSerializable( serialized, typeId ) as SerializableRef, functionsSeen !== seen ); } const WORKLET_CODE_THRESHOLD = 255; function getWorkletCode(value: WorkletFunction) { const code = value?.__initData?.code; if (!code) { return 'unknown'; } if (code.length > WORKLET_CODE_THRESHOLD) { return `${code.substring(0, WORKLET_CODE_THRESHOLD)}...`; } return code; } /** * We freeze * * - Arrays, * - Remote functions, * - Plain JS objects, * * That are transformed to a serializable with a meaningful warning. This should * help detect issues when someone modifies data after it's been converted. * Meaning that they may be doing a faulty assumption in their code expecting * that the updates are going to automatically propagate to the object sent to * the UI thread. If the user really wants some objects to be mutable they * should use shared values instead. */ function freezeObjectInDev(value: TValue) { if (!__DEV__ || globalThis.__RUNTIME_KIND !== RuntimeKind.ReactNative) { return; } Object.entries(value).forEach(([key, element]) => { const descriptor = Object.getOwnPropertyDescriptor(value, key)!; if (!descriptor.configurable) { return; } Object.defineProperty(value, key, { get() { return element; }, set() { logger.warn( `Tried to modify key \`${key}\` of an object which has been already passed to a worklet. See https://docs.swmansion.com/react-native-reanimated/docs/guides/troubleshooting#tried-to-modify-key-of-an-object-which-has-been-converted-to-a-serializable for more details.` ); }, }); }); Object.preventExtensions(value); } function makeShareableCloneOnUIRecursiveLEGACY( value: TValue ): FlatSerializableRef { 'worklet'; // eslint-disable-next-line @typescript-eslint/no-shadow function cloneRecursive(value: TValue): FlatSerializableRef { if ( (typeof value === 'object' && value !== null) || typeof value === 'function' ) { if (isHostObject(value)) { // We call `_createSerializableClone` to wrap the provided HostObject // inside SerializableJSRef. return globalThis._createSerializableHostObject( value ) as FlatSerializableRef; } if ((value as Record).__remoteFunction) { // RemoteFunctions are created by us therefore they are // a Serializable out of the box and there is no need to // call `_createSerializableClone`. return value as FlatSerializableRef; } if (Array.isArray(value)) { return globalThis._createSerializableArray( value.map(cloneRecursive) ) as FlatSerializableRef; } if ((value as Record).__synchronizableRef) { return globalThis._createSerializableSynchronizable( value ) as FlatSerializableRef; } if ((value as Record).__serializableRef) { return value as FlatSerializableRef; } if (value instanceof Set) { const values: unknown[] = []; value.forEach((element) => { values.push(cloneRecursive(element)); }); return globalThis.__workletsModuleProxy.createSerializableSet( values ) as FlatSerializableRef; } if (value instanceof Error) { const { name, message, stack } = value; return globalThis.__workletsModuleProxy.createSerializableError( name, message, stack ) as FlatSerializableRef; } if (value instanceof RegExp) { return globalThis.__workletsModuleProxy.createSerializableRegExp( value.source, value.flags ) as FlatSerializableRef; } if (value instanceof ArrayBuffer) { return globalThis.__workletsModuleProxy.createSerializableArrayBuffer( value ) as FlatSerializableRef; } if (ArrayBuffer.isView(value)) { const typeName = value.constructor.name; if (!VALID_ARRAY_VIEWS_NAMES.includes(typeName)) { throw new Error( `[Worklets] Invalid array view name \`${typeName}\`.` ); } const length = typeName === 'DataView' ? value.byteLength : (value as unknown as { length: number }).length; return globalThis.__workletsModuleProxy.createSerializableArrayBufferView( typeName, value.buffer as ArrayBuffer, value.byteOffset, length ) as FlatSerializableRef; } if (value instanceof Map) { const keys: unknown[] = []; const values: unknown[] = []; value.forEach((element, key) => { keys.push(cloneRecursive(key)); values.push(cloneRecursive(element)); }); return globalThis.__workletsModuleProxy.createSerializableMap( keys, values ) as FlatSerializableRef; } if (Object.getPrototypeOf(value) !== Object.prototype) { const length = globalThis.__customSerializationRegistry.length; for (let i = 0; i < length; i++) { const { determine, pack } = globalThis.__customSerializationRegistry[i]; if (determine(value)) { const packedData = pack(value); return globalThis.__workletsModuleProxy.createCustomSerializable( cloneRecursive(packedData as TValue) as SerializableRef, i ) as FlatSerializableRef; } } } if (__DEV__ && value instanceof Promise) { throw new Error( '[Worklets] Promises cannot be converted to serializable.' ); } const toAdapt: Record< string, FlatSerializableRef > = Object.create(null); for (const [key, element] of Object.entries(value)) { toAdapt[key] = cloneRecursive(element); } return globalThis.__workletsModuleProxy.createSerializableLEGACY( toAdapt, value ) as FlatSerializableRef; } if (typeof value === 'string') { return globalThis._createSerializableString(value); } if (typeof value === 'number') { return globalThis._createSerializableNumber(value); } if (typeof value === 'boolean') { return globalThis._createSerializableBoolean(value); } if (typeof value === 'bigint') { return globalThis._createSerializableBigInt(value); } if (typeof value === 'symbol') { // TODO: add native support return globalThis._createSerializableString( String(value) ) as FlatSerializableRef; } if (value === undefined) { return globalThis._createSerializableUndefined(); } if (value === null) { return globalThis._createSerializableNull(); } return globalThis.__workletsModuleProxy.createSerializableLEGACY( value, undefined ) as FlatSerializableRef; } return cloneRecursive(value); } /** @deprecated This function is no longer supported. */ export const makeShareableCloneOnUIRecursive = ( isBundleModeEnabled() ? createSerializable : makeShareableCloneOnUIRecursiveLEGACY ) as typeof makeShareableCloneOnUIRecursiveLEGACY; /** * This function creates a value on UI with persistent state - changes to it on * the UI thread will be seen by all worklets. Use it when you want to create a * value that is read and written only on the UI thread. * * @deprecated This function is no longer supported. */ export function makeShareable(value: TValue): TValue { if (serializableMappingCache.get(value)) { return value; } const handle = createSerializable(value, true); serializableMappingCache.set(value, handle); return value; }