# Wire Protocol & Cross-Language Sync

> Out-of-order SSR hydration, coalesced echo-safe SyncBridge, browser transports, WASM transport, and lossless 64-bit integer transfer.

`@zwire/core/protocol` and `zwire-protocol` share one canonical RFC-8259 JSON wire specification ([Wire Protocol v3](/protocol/specification/)) so a Rust server or WASM module can hydrate and synchronize live state with a TypeScript client without custom serialization glue.

## Out-of-order SSR hydration

Mark atoms with a stable wire key via `hydratable(key, initial, { scope })` (or `scope.atom(initial, { key })`). Calling `hydrate(scope, snapshot)` before or after atoms are created works identically: buffered entries are stored in `scope._hydrated` and **deleted on first consume**, keeping memory bounded.

```ts
import { createScope } from '@zwire/core';
import { dehydrate, hydratable, hydrate } from '@zwire/core/protocol';

// Server (SSR)
const server = createScope({ mode: 'ssr' });
const balance = hydratable('balance', 1000, { scope: server });
balance.set(1500);
const payload = dehydrate(server); // { balance: 1500 }

// Client (out-of-order: hydrate before atom registration!)
const client = createScope();
hydrate(client, payload);
const clientBalance = hydratable('balance', 0, { scope: client });
console.log(clientBalance.get()); // 1500
```

## Coalesced echo-safe `SyncBridge` & browser transports

`createSyncBridge(scope, transport)` (TS) and `SyncBridge` (Rust) batch outbound mutations through the scope's `_flushHooks` slot, suppress echo loops when applying inbound patches, and compose automatically with active optimistic layers so inbound server patches rebase pending UI intents instead of clobbering them.

`@zwire/core/protocol/transports` includes ready-to-use browser transports (such as WebSocket and BroadcastChannel adapters), and `@zwire/core/protocol/wasm` pairs with [`zwire-wasm`](/rust/wasm-bridge/) to connect a browser `ReactiveScope` directly to an in-browser Rust `WireScope` over WebAssembly.

## Lossless 64-bit integers (`i64` / `u64`)

JavaScript `Number` loses precision outside `±(2^53 - 1)` (`±9,007,199,254,740,991`). The `zwire` wire protocol defines deterministic rules shared by TypeScript (`BigInt`) and Rust (`i64`/`u64`):

- Integers within `±(2^53 - 1)` encode as JSON numbers.
- Integers outside the safe range encode losslessly as base-10 JSON strings (e.g., `"1152921504606846976"` for `2n ** 60n`), never silently rounded.
- Both implementations pass identical round-trip vectors in [`spec/conformance.json`](/spec/v3/conformance.json).

## Optional bridges (`zwire-wasm` & `zwire-serde`)

- **`zwire-wasm`** (`bridges/wasm`): `wasm-bindgen` transport exposing `WireScope` to JS/TS with `connectWasm(scope, peer)`.
- **`zwire-serde`** (`bridges/serde`): `#![no_std]` `serde` bridge for serializing/deserializing `WireValue` and `StatePatch` with existing Serde ecosystems.
