travels3.0
Core Concepts

State Requirements

Use state, patch values, paths, and metadata that remain correct through replay and JSON persistence.

Travels’ durable contract is deliberately smaller than JavaScript’s object model. It applies to current state, values retained in old patches, patch paths, and custom history metadata—not just the object passed to createTravels().

Preferred durable data

Use plain objects, dense arrays, strings, finite numbers other than -0, booleans, and null. Patch paths must be Travels-accepted JSON Pointer strings or dense arrays of strings and finite non-negative integer indexes.

const state = {
  title: 'Draft',
  published: false,
  updatedAt: '2026-10-24T12:00:00.000Z',
  revision: 0,
  blocks: [{ id: 'intro', text: 'Hello' }],
};

Durable containers have normal writable, enumerable data properties and standard prototypes. Avoid accessors, hidden properties, custom own properties, non-extensible containers, array holes, and built-in subclasses. Standard frozen containers are recognized when enableAutoFreeze is enabled, but they are not a general durable-data recommendation for caller-created input.

Compatibility matrix

ValueRuntime behaviorJSON persistenceRecommendation
Plain objectSupportedSupportedPreferred
Dense arraySupportedSupportedPreferred
Sparse, extended, or subclassed arrayLimited or rejected by durable checksShape is not preservedNormalize to a dense plain array
String, boolean, nullSupportedSupportedPreferred
Finite number other than -0SupportedSupportedPreferred
NaN, infinities, -0Supported in some in-memory pathsBecomes null or 0Normalize first
bigintSupported in some in-memory pathsJSON.stringify() throwsEncode as a string
undefinedPatchable in memoryRemoved from objects; array semantics differUse null
DateCloneable, not durableBecomes a string through JSONStore a timestamp or ISO string
Map / SetRejected in both runtime modesRejected at snapshot boundariesUse records or dense arrays
Class or custom/null prototypeNot durablePrototype and methods are lostStore plain data or IDs
Function or symbolNot durableDropped by JSONKeep behavior outside state
Circular or shared graph identityNot durableCircular fails; shared identity is duplicatedNormalize to IDs
DOM node, ref, observable bodyNot durableNot serializableStore outside Travels
WeakMap / WeakSetNot supportedNot serializableStore outside Travels

Primitive roots work, but mutable mode cannot mutate a primitive in place and falls back to immutable replacement. Wrap a primitive in an object when stable root identity matters.

Normalize collections at the boundary

type Item = { id: string; title: string };

type LegacyState = {
  itemsById: Map<string, Item>;
  selectedIds: Set<string>;
  updatedAt: Date;
};

function normalize(state: LegacyState) {
  return {
    itemsById: Object.fromEntries(state.itemsById),
    selectedIds: Array.from(state.selectedIds),
    updatedAt: state.updatedAt.toISOString(),
  };
}

Keep application-domain Map, Set, Date, or class views outside Travels and derive them from normalized state. Do not replay old collection-specific patch histories after conversion; materialize the authoritative current state, normalize it, and start a new baseline.

Unsafe path keys

Mutative will not replay a change under a __proto__ key or inside a value stored at a constructor key. Travels rejects such updates with UNSUPPORTED_STATE. Rename those keys before recording history. Root replacement has special handling in mutable and controlled-navigation paths; see the relevant guides before implementing in-place patch application.

Static and runtime checks

Enforce the durable shape with createPatchableTravels()

import { createPatchableTravels, type JsonValue } from 'travels';

const initial = {
  title: 'Draft',
  blocks: [] as Array<{ id: string; text: string }>,
} satisfies JsonValue;

const travels = createPatchableTravels(initial);

PatchableInput<T> performs a finite-depth, best-effort static check. TypeScript cannot prove every runtime property: number still includes NaN, infinities, and -0, and broad object types hide their contents. The strict factory therefore also validates its concrete initial value.

Inspect a value directly

import { findStateCompatibilityIssues } from 'travels';

const issues = findStateCompatibilityIssues(
  { createdAt: new Date(), selection: new Set(['a']) },
  { maxIssues: 20 }
);

for (const issue of issues) {
  console.warn(issue.code, issue.path, issue.message);
}

Issue codes identify circular/shared references, dates, functions, class instances, DOM nodes, Map/Set, bigint, non-JSON numbers, nonstandard array/object shapes, weak collections, symbols, and undefined values.

Validate before or during serialization

travels.assertPersistenceCompatible(); // Throws with path-specific diagnostics
const snapshot = travels.serialize({ strict: true });

assertPersistenceCompatible() checks current state, retained patch values and paths, and metadata. serialize({ strict: true }) rejects any value that cannot round-trip through the documented JSON contract. Plain serialize() still returns detached data, but it does not normalize runtime-only values for you.

Development diagnostics

Development builds scan initial and changed state plus retained patches and metadata for known hazards. warnOnUnsupportedState: false controls those warnings; it does not enable Map/Set or make invalid persistence safe. onWarning receives structured warning codes, and onObserverError isolates failures thrown by diagnostic or notification hooks.

The production package’s default entries avoid the full development scanner. Correctness boundaries such as strict serialization, restore validation, controlled patch validation, and Map/Set rejection remain explicit rather than depending on console warnings.

On this page