Controlled Journal
Connect Travels history to a runtime that already owns state and commits.
createTravelJournal() is the adapter API for a runtime that already owns and commits state. It lets that runtime hand an existing forward/inverse patch pair to Travels without rerunning the update recipe or routing navigation around the owner's validation and subscription pipeline.
Use createTravels() instead when Travels itself should own state updates. Restore serialized journal history with restoreTravelJournal(snapshot, { apply }); the snapshot state and timeline are accepted as one atomic input.
Data flow
An external commit has one authoritative path:
- The owner produces
nextState,patches, andinversePatchesfor one transition. - The owner commits
nextStatethrough its normal state path. - In the same synchronous commit boundary, the adapter calls
journal.recordPatches(nextState, { patches, inversePatches, metadata }). - Travels detaches the patch pair and metadata, updates its cursor and retained history, then publishes one
recordPatchesevent.
recordPatches() requires a non-empty patch pair when the supplied state reference changes. It validates patch structure and supported patch values, but does not replay the pair to prove that it transforms the previous state into the supplied state. That relationship is the adapter's responsibility; replay validation here would duplicate the external runtime's work and defeat the single-generation integration path.
Owners that cannot roll back a published commit can call assertTravelHistoryEntryRecordable({ patches, inversePatches }) before step 2. The preflight uses the same structural validation and detached-value rules as recordPatches() without changing journal state.
Patch groups and metadata are cloned before Travels retains them. The supplied state remains the external owner's state reference and is not cloned.
Navigation and reset contract
back(), forward(), go(), and reset() compose the necessary patches and invoke the required apply callback:
const journal = createTravelJournal(authoritativeState, {
apply(transition) {
authoritativeState = commitThroughOwner(transition.patches);
return authoritativeState;
},
});The callback receives:
state: the state Travels knew before navigation;patches: the composed forward transition to commit;inversePatches: the composed rollback transition;fromPositionandtoPosition: the cursor movement.
reset() also describes its return to the baseline as patches. When the current state and the baseline are both plain objects, or both arrays, those patches overwrite the root's entries and keep the root itself, so an owner can apply them in place, for example with Mutative's apply(state, patches, { mutable: true }). When the root kinds differ, the state is not an object, or either root has an own __proto__ key, which no patch path can name, the transition replaces the root with one { op: 'replace', path: [] } patch. An owner that applies transitions in place must handle that patch itself, as it must for root replacements it recorded through recordPatches(): Mutative 2 throws for a root replacement applied in place, and Mutative 1 skipped it, which left the owner's state unchanged while the journal moved.
The transition contains detached patch operations and values, so accidental callback mutation cannot rewrite retained history. The callback should still treat them as read-only because changing them before the owner commits would change the requested navigation. Patch values that contain functions, accessors, WeakMap/WeakSet, custom class instances, array subclasses, or another value that cannot be cloned without changing its runtime type are rejected with UNCLONEABLE_PATCH_VALUE; controlled journals should retain primitives, plain objects, plain arrays, or Date values. apply must finish synchronously and return the state actually committed by the owner. A thrown error, uncloneable transition, or Promise-like result does not advance the cursor, replace the retained state reference, or change history.
In development builds Travels also scans the returned state for Map and Set, and an unsupported state is rejected with the same atomicity: the cursor, retained state reference, and history are unchanged. That scan is proportional to the whole state, so production builds skip it and pay nothing per navigation. It is a diagnostic that tells an owner early which transition introduced an unsupported value, not the guarantee that keeps persistence sound: serialize(), rebase(), and getHistorySnapshot() validate the state in every build, and controlled patch values are validated in every build, so an unsupported value can never reach retained history or a persisted snapshot. Develop against a development build to keep the early signal. Travels cannot undo mutations or other side effects the external owner already performed before failing.
The owner must suppress normal commit recording while applying delegated navigation or reset. Feeding those changes back into recordPatches() would create a new entry instead of moving or clearing the existing timeline. Travels rejects every journal mutation attempted synchronously from apply with REENTRANT_MUTATION; reads remain available to the owner callback.
Set autoArchive: false when several external commits should become one undo step. Each recordPatches() call updates the pending current state; archive(metadata?) composes the pending patch groups, and canArchive() reports whether any work is pending. Archiving changes only journal history and does not invoke apply because the external owner already committed the state. When navigation implicitly archives pending work, the archive and cursor move commit as one observable navigation transition; a failed apply leaves the pending archive, revision, and subscriptions untouched.
Public surface
The returned TravelJournal exposes only journal-safe operations:
- external commit ingress:
recordPatches(); - navigation:
back(),forward(),go(),reset(),canBack(), andcanForward(); - reads:
getState(),getHistory(),getHistorySnapshot(),getPosition(),getPatches(),getMetadata(),getHistoryEntries(),assertPersistenceCompatible(), andserialize(); - lifecycle:
subscribe()andrebase(); - manual journals only:
archive()andcanArchive().
The facade is a frozen read-only capability object in every build; its methods cannot be replaced at runtime.
State-owning operations (setState(), transactions, replaceStateWithoutHistory(), tracking controls, and getControls()) are absent from both the public type and the runtime facade. rebase() is the safe way to clear retained history while keeping the current external state as the new baseline; reset() instead asks the external owner to restore the existing baseline.
Failure boundaries
Travels makes each journal mutation internally atomic: malformed, empty, or one-sided patch pairs, unsafe paths, unsupported patch/state values, metadata cloning failures, and controlled navigation failures do not partially change journal state or history. Controlled patch ingress uses the same accessor-safe structural normalization as persisted history.
The external owner and Travels are still two components. If the owner has already published a commit and recordPatches() then fails, Travels cannot roll that external commit back automatically. Generate patches through a trusted producer, keep metadata cloneable, and call recordPatches() before publishing external notifications when the owner supports that ordering. An adapter that cannot roll back should recover explicitly, for example by rebasing the journal at the authoritative state or switching to its documented compatibility fallback.
Observer failures happen after a successful journal commit and follow the normal onObserverError contract; they do not roll the transition back.
Event compatibility
A successful external commit emits TravelsEvent with type recordPatches. Navigation emits go, including calls made through back() or forward(). The event patch groups describe only that event's transition.
TravelsEvent['type'] intentionally remains open to future minor-release event names. Consumers should handle known operations and keep a default branch instead of asserting exhaustiveness with never. Applications using only createTravels() do not receive recordPatches at runtime.