API reference

Every export of seroval, with its signature and options.

Entry points

seroval exports everything on this page. Code that only reads or only writes can import a smaller entry point instead.

Entry pointExports
serovalEverything.
seroval/readfromJSON, fromCrossJSON, createCrossDeserializer, deserialize, and everything in seroval/shared.
seroval/writeserialize, serializeAsync, toJSON, toJSONAsync, compileJSON, the cross-reference serializers, getCrossReferenceHeader, Serializer, and everything in seroval/shared.
seroval/sharedWhat both sides use: streams, references, createPlugin, Feature, the errors and the error catalog.
seroval/binaryThe binary mode serialize, deserialize, createDeserializer and createReferenceMap. seroval does not export these.
seroval/validatorThe validators for a plugin's validate field (see Plugin security). seroval does not export them.

All entry points load the same files, so a value imported from one is the same value in the others. For example, a framework can read page state in one chunk and serialize server function calls in another:

JavaScript
// Loaded on every page.
import { fromCrossJSON } from 'seroval/read';

// Loaded only when a server function runs.
import { fromJSON } from 'seroval/read';
import { toJSONAsync } from 'seroval/write';

The bundler keeps the serializers out of the first chunk. Import the subpaths to get this in every bundler. Some bundlers, such as rolldown, also split the code when both chunks import seroval, because its build is split into the same files. Others, such as esbuild, keep the serializers in the first chunk in that case. seroval/read makes sure a chunk never pulls in a serializer by mistake.

Serialize to JavaScript

FunctionReturnsGuide
serialize(value, options?)stringSerialize to JavaScript
serializeAsync(value, options?)Promise<string>Serialize to JavaScript
deserialize(source)the valueSerialize to JavaScript

Options: plugins, disabledFeatures, depthLimit, compactArrayBufferViews.

JSON

FunctionReturnsGuide
toJSON(value, options?)SerovalJSONJSON
toJSONAsync(value, options?)Promise<SerovalJSON>JSON
fromJSON(tree, options?)the valueJSON
compileJSON(tree, options?)stringJSON

fromJSON options: plugins, disabledFeatures, depthLimit, maxBase64Length. compileJSON options: plugins.

Cross-reference

FunctionReturnsGuide
crossSerialize(value, options?)stringCross-reference
crossSerializeAsync(value, options?)Promise<string>Cross-reference
crossSerializeStream(value, options)stop functionStreaming
toCrossJSON(value, options?)SerovalNodeCross-reference
toCrossJSONAsync(value, options?)Promise<SerovalNode>Cross-reference
toCrossJSONStream(value, options)stop functionStreaming
fromCrossJSON(node, options)the valueCross-reference
createCrossDeserializer(options)CrossDeserializerStreaming
getCrossReferenceHeader(scopeId?)stringCross-reference
new Serializer(options)SerializerStreaming

Binary mode

Exported from seroval/binary. See Binary mode.

JavaScript
import * as binary from 'seroval/binary';
FunctionReturnsGuide
binary.serialize(value, options)stop functionSerializing
binary.deserialize(options)Promise<{ value, pending }>Deserializing
binary.createDeserializer(options)sessionSharing references
binary.createReferenceMap()ReferenceMapSharing references

binary.serialize options:

OptionTypeDefaultDescription
refsMaprequiredValues already sent. Share one Map between payloads to send references.
onSerialize(bytes)functionrequiredReceives each Uint8Array chunk. May return a promise, which holds back the live stream event behind the chunk.
onDone()functionrequiredRuns once every promise and stream has settled.
onError(error)functionrequiredRuns when a value fails to serialize.
pluginsPlugin[]nonePlugins with a binary section.
disabledFeaturesnumber0Feature flags to turn off.
featuresnumberall featuresFeatures to turn on. Overrides disabledFeatures.
depthLimitnumber64Maximum nesting depth.
compactArrayBufferViewsbooleanfalseSend only the bytes each typed array or DataView covers, instead of its whole buffer.

The stop function cancels every source that is still running and runs plugin cleanups. It does not call onDone.

binary.deserialize options:

OptionTypeDefaultDescription
read()functionrequiredReturns a promise for the next Uint8Array chunk, or for undefined at the end of the input.
onError(error)functionrequiredRuns when the input is invalid or a value cannot be rebuilt.
refsReferenceMapa new mapFrom binary.createReferenceMap(). Share one between payloads to resolve references.
pluginsPlugin[]nonePlugins with a binary section.
disabledFeaturesnumber0Feature flags to reject.
featuresnumberall featuresFeatures to accept. Overrides disabledFeatures.
maxArrayBufferLengthnumber1000000Largest ArrayBuffer, in bytes, that the input may hold.
maxArrayLengthnumber1000000Largest array length that the input may hold.
signalAbortSignalnoneStops decoding when it aborts, and rejects the values still pending with its reason.

The promise resolves with { value, pending } once the root value is decoded. pending counts the promises and streams in the value that have not settled or ended. Promises and streams inside it may still be pending. It rejects if the input is invalid, ends early or read() rejects before the root value is ready.

Streams

ExportDescriptionGuide
createStream()Creates a stream that keeps every value.Streams
isStream(value)Whether a value is a seroval stream.
createLiveStream(options?)Creates a single-reader stream with backpressure. Returns { stream, producer }.Live streams
isLiveStream(value)Whether a value is a live stream.

References and plugins

ExportDescriptionGuide
createReference(id, value)Sends value by its key.Isomorphic references
new OpaqueReference(value, replacement?)Sends replacement instead of value.OpaqueReference
createPlugin(plugin)Defines a plugin, with type inference. Add a binary section for binary mode.Writing plugins
FeatureFeature flags for disabledFeatures.Compatibility
SequenceThe recorded values of an iterable, built by the parsers. Exported only so bundlers can remove it when it is unused. Do not create one, and do not read its fields, which may change in any release.Internal

Errors

ExportDescriptionGuide
SerovalErrorThe base class of every error seroval throws because of the data.Errors
SerovalParserError, SerovalSerializationError, SerovalDeserializationErrorThe wrappers for each step.Errors
SerovalUnsupportedTypeError and the other error classesOne class per code.Error codes
ERROR_CODES, DOCS_ERRORS_URL, getProdMessage, getCatalogEntry, getDevMessageThe error catalog.Reading the catalog

Options

All options in one place. Each function lists the ones it accepts above. Binary mode has its own options.

OptionTypeDefaultDescription
pluginsPlugin[]nonePlugins for extra types.
disabledFeaturesnumber0Feature flags to turn off, combined with |.
depthLimitnumber64Maximum nesting depth.
compactArrayBufferViewsbooleanfalseSend only the bytes each typed array covers.
refsMapa new MapValues already sent, shared between cross-reference calls.
scopeIdstringnoneWrites to $R[scopeId] instead of $R.
assignSharedRefsOnlybooleanfalsecrossSerialize and crossSerializeAsync only. Stores only the values the output reads more than once in $R.
maxBase64Lengthnumber1000000Largest encoded ArrayBuffer that JSON decoding accepts.
onSerialize(chunk, initial)functionrequiredReceives each script chunk of a stream.
onParse(node, initial)functionrequiredReceives each JSON node of a stream.
onDone()functionnoneRuns when a stream finishes.
onError(error)functionnoneRuns when a stream fails.

Types

seroval also exports TypeScript types for the values above, including SerovalJSON, SerovalNode, Plugin, SerializeOptions, SerializeAsyncOptions, ToJSONOptions, ToJSONAsyncOptions, CrossSerializeOptions, Stream, StreamListener, LiveStream, LiveStreamProducer, LiveStreamConsumer, CrossDeserializer, PluginWithBinaryMode, BinaryPlugin, ErrorCode, SerovalErrorShape, CatalogEntry and the options type of each function. seroval/binary exports the types SerializeOptions, DeserializeOptions and ReferenceMap.