---
title: "Structured clone"
url: https://recursiveai.org/oneecma/docs/structured-clone/
description: "Structured clone copies a value from one engine to another (postMessage, a worker's onmessage), within one engine (structuredClone(), history.state), or…"
version: "1.2.0"
source: https://github.com/recursive-ai-oss/oneecma-csharp/blob/e6cd282426a9305a31d112f682c12ebf0d5e5631/docs/structured-clone.md
---

# Structured clone

Structured clone copies a value from one engine to another (`postMessage`, a worker's `onmessage`), within one engine (`structuredClone()`, `history.state`), or to storage and back (IndexedDB). It follows the HTML standard's StructuredSerializeInternal and StructuredDeserialize (HTML 2.7.3 and 2.7.4) for the JavaScript types, and it adds a stable byte encoding so a stored value can be read years later.

The API is on `ScriptEngine` (`Serialize`, `Deserialize`, `Clone`) and `JsRealm` (`Deserialize` into any realm). The form in the middle is a `SerializedValue`: plain bytes plus two side lists for what cannot be bytes. It belongs to no engine, so any engine on any thread can deserialize it, any number of times.

```csharp
SerializedValue data = a.Serialize(a.Evaluate("({ id: 1, items: [new Date(0), new Map([[1, 2]])] })"));
JsValue copy = b.Deserialize(data);          // engine b, any thread
byte[] stored = data.ToArray();              // for IndexedDB
JsValue later = c.Deserialize(SerializedValue.FromBytes(stored));
JsValue same = a.Clone(value);               // structuredClone(value)
```

## What is cloned

| Value | Result in the receiving realm |
|---|---|
| undefined, null, booleans, numbers (including -0 and NaN), strings (lone surrogates kept), BigInt | the same primitive |
| Boolean, Number, String and BigInt wrapper objects | a new wrapper |
| Object (any object with no internal state of its own, class instances included) | a plain object with the own enumerable string-keyed properties, read with `[[Get]]` (getters run), in property order; symbol keys, non-enumerable properties and the prototype are dropped |
| Array | an array with the same length and the same own enumerable properties, so holes stay holes and extra properties are kept |
| Date | a Date with the same time value (invalid dates too) |
| RegExp | a RegExp with the same source and flags; `lastIndex` is not kept |
| Map, Set | the entries as they were when serialization began, in order |
| Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError | an error of the type named by `name` (any other name, subclasses included, gives `Error`); the own data properties `message`, `stack` and `cause` are kept (`cause` is cloned too) |
| ArrayBuffer | a copy of the bytes; a resizable buffer stays resizable with its `maxByteLength` |
| SharedArrayBuffer | a buffer over the same memory (below); a growable one stays growable |
| typed arrays, DataView | a view of the same kind, offset and length (or length-tracking) over the cloned buffer; views of one buffer still share one buffer |
| host objects (`JsHostObject`) | whatever the host hook makes (below) |

Objects reached twice, and cycles, stay one object: the second visit is a reference. Everything else throws a `DataCloneError`: functions, symbols, Proxy, Promise, WeakMap, WeakSet, WeakRef, FinalizationRegistry, generators, iterators, module namespaces, Intl objects, a detached buffer, a view whose buffer is detached or whose window left a shrunk resizable buffer, a nesting deeper than `StructuredCloneOptions.MaxDepth` (default 1000), and a host object the hook refuses.

## DataCloneError

The error is an `Error` whose `name` is `DataCloneError` and whose `code` is 25, with V8's message (the text Node prints for `structuredClone`): `#<Object> could not be cloned.`, `function f() {} could not be cloned.`, `Symbol(a) could not be cloned.`, `An ArrayBuffer is detached and could not be cloned.`. When the call came from .NET (no script frame is running) the report has no source excerpt; it adds a help line saying what to send instead and a note with the path of the offending value:

```
error[DataCloneError]: function handler() { return 1; } could not be cloned.
  = help: functions cannot be cloned: send the data the function needs, or a name to look it up by
  = note: while cloning `value.options.items[1].cb`
```

Paths read `value.a.b`, `value["odd key"]`, `value.items[2]`, `value.<Map key #0>`, `value.<Map value #1>`, `value.<Set item #3>`, `value.cause`.

## Transfer

`StructuredCloneOptions.Transfer` lists objects that move instead of being copied. An ArrayBuffer in the list is detached in the sending engine once serialization succeeded (an error leaves everything attached); its bytes are in the serialized form like any copy, so a transfer costs one copy, not two. The list must hold distinct objects that are transferable: a detached or shared buffer, or an object the host hook accepts, is a `DataCloneError`. A platform object in the list goes through `IStructuredCloneHost.Transfer` after the graph was serialized; the receiver gets it from `ReceiveTransfer`. Transferred platform objects are also returned in order by the overload `Deserialize(data, out transferred)`, whether or not the value mentions them (the `ports` of a message event).

## Shared memory

A SharedArrayBuffer is not copied: the serialized form carries a `SharedMemoryHandle`, and every engine that deserializes it gets a SharedArrayBuffer over the same bytes, length and wait lists. `ScriptEngine.Clone` keeps it inside one engine. Serializing or receiving one makes the block "shared": from then on `Atomics.wait` and `waitAsync` on it use real time and wake across engines ([binary-data.md](https://recursiveai.org/oneecma/docs/binary-data/)), and the engine's record log is marked not replayable. `StructuredCloneOptions.AllowSharedMemory = false` refuses a SharedArrayBuffer with a `DataCloneError`, as the standard does for stored values. A value with shared memory has `IsPersistable == false` and `ToArray()` throws.

## Host objects

`IStructuredCloneHost` has four optional members, each defaulting to "refuse":

| Member | Standard's step | Called |
|---|---|---|
| `Serialize(JsHostObject)` | serialization steps of a [Serializable] platform object | when the graph reaches the object (once per identity) |
| `Transfer(JsHostObject)` | transfer steps of a [Transferable] one | after the graph, for each object in the transfer list, in list order |
| `Deserialize(HostObjectState, JsRealm)` | deserialization steps | when the reader reaches the record |
| `ReceiveTransfer(HostObjectState, JsRealm)` | transfer-receiving steps | before the graph is read, for each table entry in order |

A `HostObjectState` is a tag (which kind of object, a string the receiving host knows), a payload (bytes, persisted), and an optional live `Native` object (a port's channel end, a GPU handle) that travels beside the bytes and is not persisted; a value holding a native has `IsPersistable == false`. Only objects the host made as `JsHostObject` reach the hook; the engine never asks for ordinary objects.

## The byte encoding (format version 1)

`SerializedValue.Bytes` is the whole encoding of a persistable value. Integers are unsigned LEB128 varints (7 bits per byte, low group first) unless stated; doubles are 8 bytes, IEEE 754, little-endian, with every NaN written as `7FF8000000000000`.

```
value    := header table body
header   := "OESC" (4 bytes: 4F 45 53 43) version (1 byte, 1) flags (1 byte)
            flags bit 0: refers to shared memory; bit 1: refers to live host objects (informational)
table    := count:varint { state }                      transferred platform objects, in transfer-list order
state    := tag:string payload-length:varint payload native:varint     native 0 = none, else 1 + index into the live list
body     := record
```

Records start with a tag byte. Object-like records take the next number (0, 1, 2, ...) in the order the tags appear, assigned when the record starts and before its children, so a `Ref` can point back into a cycle.

| Tag | Record | Payload after the tag |
|---|---|---|
| `00` | undefined | |
| `01` | null | |
| `02` / `03` | false / true | |
| `04` | number | double |
| `05` | string, UTF-16 | length in code units (varint), then 2 bytes per unit, little-endian |
| `06` | string, one byte per unit | length (varint), then 1 byte per unit (used when every unit is below 256) |
| `07` | BigInt | sign byte (0 or 1), byte count (varint), magnitude, little-endian |
| `08` | reference | object number (varint) |
| `10` | Object | entries |
| `11` | Array | length (varint), entries |
| `12` | Date | double |
| `13` | RegExp | string record (source), string record (flags) |
| `14` | Map | count, then count pairs of values (key, value) |
| `15` | Set | count, then count values |
| `16` | Error | name code byte (0 Error, 1 EvalError, 2 RangeError, 3 ReferenceError, 4 SyntaxError, 5 TypeError, 6 URIError), flags byte (bit 0 message, bit 1 stack, bit 2 cause), then the message string record, the stack string record, the cause value, each only when its flag is set |
| `17` | ArrayBuffer | byte length, max length + 1 (0 = fixed length), the bytes |
| `18` | SharedArrayBuffer | index into the shared-memory list, max length + 1 (0 = fixed) |
| `19` | typed array | kind byte (0 Int8, 1 Uint8, 2 Uint8Clamped, 3 Int16, 4 Uint16, 5 Int32, 6 Uint32, 7 Float16, 8 Float32, 9 Float64, 10 BigInt64, 11 BigUint64), the buffer (a value), byte offset, length + 1 (0 = length-tracking) |
| `1A` | DataView | the buffer (a value), byte offset, byte length + 1 (0 = tracking) |
| `1B` | Boolean object | 1 byte (0 or 1) |
| `1C` | Number object | double |
| `1D` | BigInt object | BigInt payload (sign, count, magnitude) |
| `1E` | String object | string record |
| `1F` | host object | tag string record, payload length, payload, native (as in `state`) |
| `20` | transferred host object | index into the table |

`entries` are a run of (key string record, value) pairs ended by a single `00` byte. Keys are property names; an array index is its decimal text. A typed array or DataView takes its object number before its buffer does. A reader rejects anything else: an unknown tag, a size past the end, a reference to a number not yet assigned, a typed array outside its buffer, an array length above 2^32 - 1, nesting deeper than `MaxDepth`. That is a `DataCloneError` ("The serialized data is damaged and could not be cloned") with the byte offset in a note, never a crash or an unbounded allocation: every size is checked against the bytes left, and every allocation is charged to the engine's memory limit before it happens.

**Versioning.** The version byte changes only when an existing tag changes meaning or layout. Adding a tag or a flag bit is not a new version; an older reader rejects the unknown tag. `SerializedValue.FromBytes` throws `NotSupportedException` for a version above `CurrentFormatVersion` and `FormatException` for bytes that do not start with the magic. The test `GoldenBytesPinFormatVersion1` pins the exact bytes of a value that uses most tags, and any change to them must come with a new version.

## Limits and cost

Serialization and deserialization charge fuel per value and per property, the size of buffers and BigInts in bulk, and check cancellation and termination through the usual fuel refill, so a hostile graph ends in a limit report. Deserialization allocates through the engine's memory budget. Recursion follows value nesting only down to `MaxDepth`.
