import { Pn as ESecurityLevel, ai as WireProtocolMux, er as IReliableLogStore, nr as IRuntimeCoordinate, pr as IWireAcceptorProtocolContext } from "./index-BjOE7ujh-DOsnlWFL.mjs"; import { C as JSONSerializableValue, E as NiceErrorDomain, T as NiceError, p as INiceErrorIdMetadata } from "./index-BAgdJKZy-COfXA16I.mjs"; import { Draft, Patch, PatchListener } from "immer"; import { StandardSchemaV1 } from "@standard-schema/spec"; //#region ../connect-core/build/index-v_85ZxRk.d.mts //#region src/state/core/Store.d.ts /** * A plain pub/sub listener. Fired (in the order added) every time the store's * root state reference changes. This is the vanilla integration point that any * ecosystem — including the React adapter's `useSyncExternalStore` — builds on. */ type TUpdateListener = () => void; /** * **Mutate-only**: change the `draft` in place. Unlike immer's `produce`, a returned value is * NOT honored as a replacement state — to swap the state wholesale use {@link Store.replace}. * (An updater that returns an object without touching its draft throws, catching the * `store.update(() => initialState())` reset idiom that would otherwise silently no-op.) * * @typeParam S The store's state * @param draft The mutable draft to change during this update (Immer proxy). * @param original A readonly snapshot of the state as it was before this update. */ type TUpdateFunction = (draft: Draft, original: S) => void; /** * A selector that derives a watched slice `T` from the full store state `S`. */ type TStoreWatch = (state: S) => T; /** * Fired by {@link Store.watch} whenever the watched slice changes structurally. */ type TStoreSubscriptionListener = (watched: T, allState: S, previousWatched: T) => void; /** * Runs inside an Immer `produce` whenever a watched slice changes, letting the * store derive further state from its own mutations. */ type TReactionFunction = (watched: T, draft: Draft, original: S, previousWatched: T) => void; type TPatchesCallback = (patches: Patch[], inversePatches: Patch[]) => void; /** * @internal * Drives a registered reaction. `forceRun` bypasses the change-detection * fast-path (used when a reaction is created with `runNow`). */ type TRunReactionFunction = (forceRun?: boolean) => void; /** * @internal * Binds a reaction definition to a concrete store instance. */ type TReactionCreator = (store: Store) => TRunReactionFunction; interface IStoreInternalOptions { ssr: boolean; reactionCreators?: TReactionCreator[]; } interface ICreateReactionOptions { runNow?: boolean; runNowWithSideEffects?: boolean; } /** * A framework-agnostic, Immer-backed state container. * * The store owns a single immutable state value and a `Set` of plain * listeners. Every mutation runs through Immer's `produce`, and listeners are * only notified when the resulting root reference actually changes — making * "no-op" updates genuinely free for subscribers. * * @typeParam S Your store's state interface. */ declare class Store { private currentState; private readonly createInitialState; private ssr; /** Plain pub/sub listeners — a Set both dedupes and dispatches fast. */ private readonly listeners; private reactionCreators; private reactions; private clientSubscriptions; /** * @internal */ _patchListeners: PatchListener[]; constructor(initialState: S | (() => S)); /** * The store's current state, frozen (shallow) for read safety — mutations must go through * {@link update} / {@link replace}, never by writing to this object. * * Reach for it in plain logic (event handlers, engines, tests). In React components use * `useStoreState` so the component re-renders on change; for side-effects use {@link watch}. */ get state(): S; /** * @internal */ _setInternalOptions({ ssr, reactionCreators }: IStoreInternalOptions): void; /** * @internal */ _getReactionCreators(): TReactionCreator[]; /** * @internal */ _instantiateReactions(): void; /** * @internal */ _getInitialState(): S; /** * @internal */ _hasPatchListeners(): boolean; /** * @internal */ _emitPatches(patches: Patch[], inversePatches: Patch[]): void; /** * @internal * * Writes a new state value without running reactions. Used by reactions * themselves to avoid re-entrancy. */ _updateStateWithoutReaction(nextState: S): void; /** * @internal * * Commits a new root state, runs reactions, then dispatches to all * subscribers. Callers are responsible for the `nextState !== currentState` * reference guard before invoking this. */ _updateState(nextState: S): void; /** * Subscribe a plain listener to store mutations. The listener fires once per * committed update (root reference change) and receives no arguments — read * the latest value with {@link state}. * * This is the low-level primitive that vanilla code and framework adapters * (e.g. React's `useSyncExternalStore`) build upon. * * @returns An unsubscribe function. */ subscribe(listener: TUpdateListener): () => void; /** * Subscribe to a derived slice of state. The `listener` only fires when the * watched value changes structurally (per the Fast-Path rule). * * @returns An unsubscribe function. */ watch(watch: TStoreWatch, listener: TStoreSubscriptionListener): () => void; /** * Register a reaction: when the watched slice changes, the `reaction` recipe * runs inside Immer to derive further state on the same store. * * @returns A function that removes the reaction. */ createReaction(watch: TStoreWatch, reaction: TReactionFunction, { runNow, runNowWithSideEffects }?: ICreateReactionOptions): () => void; /** * Subscribe to the Immer patches produced by each update. * * @returns An unsubscribe function. */ listenToPatches(patchListener: PatchListener): () => void; /** * Mutate the store via one or more Immer update functions. * * @param updater A single update function, or an array applied in order. * @param patchesCallback Optional callback receiving the patches for this update. */ update(updater: TUpdateFunction | TUpdateFunction[], patchesCallback?: TPatchesCallback): void; /** * Replace the store's state entirely with a new state value — the reset/swap counterpart to * {@link update} (whose update functions are mutate-only). A replace is a first-class citizen * of the patch stream: patch listeners receive one root `replace` patch (path `[]`) with its * inverse, so persistence/undo/sync layers built on {@link listenToPatches} see resets too. */ replace(newState: S): void; /** * Replace the store's state by mapping from the current state. */ replaceFromCurrent(replacer: (state: S) => S): void; /** * Apply a set of Immer patches to the store. */ applyPatches(patches: Patch[]): void; } //#endregion //#region ../connect-core/build/RealmServerEngine-o2bq7o8t.d.mts //#region src/realm/RealmDefinition/Rules/rules.types.d.ts /** * Rule condition shapes. Two typing tiers, deliberate: * * - A **plain function passed directly to `.view()` / `.alter()`** is contextually typed from the * rule's path pattern — `params` and `prev`/`next` are precise (see `TResolveRulePath`). * - A condition **built via `r.all(...)` / `r.serverChecked(...)`** is constructed *outside* that * contextual position, so it receives the generic context (`params: Record`, * `prev`/`next: any`). This is the v1 typing compromise that keeps the composed-rule DX flat; * a path-scoped builder can tighten it later without changing the runtime shape. * * Isomorphic alter functions run on **both** sides (client-side prediction + server verdict) and * receive no `ctx` and nothing time-like — anything needing server context wraps in * `r.serverChecked(fn)`, which the client-side prediction auto-passes. */ /** A rule/intent rejection — any hydratable NiceError from the consumer's own domain. */ type TRealmRuleError = NiceError; type TRuleVerdict = true | TRealmRuleError; /** * The identity a **view** rule may read: `type` + `persistentId` only. It deliberately * omits `instanceId` — the server groups its per-view-signature encode by `(type, persistentId)` * ([viewSignatureKey]), so two tabs / devices of one avatar (same type+persistentId, different * instanceId) share one sliced payload. A view rule that branched on `instanceId` would be silently * mis-sliced across them; making it unrepresentable here (and stripping it at runtime) closes that * hole. Alter rules see the full {@link IRealmAvatarRef} — they run per write, never cache-shared. */ interface IViewAvatarRef { type: TAvatarType; persistentId: string; } interface IRealmAvatarRef extends IViewAvatarRef { /** Ephemeral per-runtime-instance id (multi-tab / multi-device discrimination). */ instanceId: string; } interface IViewRuleContext> { /** View rules see only `type`/`persistentId` — see {@link IViewAvatarRef}. */ avatar: IViewAvatarRef; params: TParams; } interface IAlterRuleContext, TValue = unknown, TState = unknown> extends IViewRuleContext { /** Alter rules run per write (never cache-shared), so they see the full identity incl. `instanceId`. */ avatar: IRealmAvatarRef; /** The current value at the path (avatar: projected view; server: authoritative). */ prev: TValue; /** The value the write sets. */ next: TValue; /** Read-only state (avatar: the writer's projected view; server: authoritative). */ state: Readonly; /** The confirmed version the writer composed against (opt-in CAS via `touchedSince`). */ basisVersion: number; } interface IServerCheckedRuleContext, TValue = unknown, TState = unknown, TCtx = unknown> extends IAlterRuleContext { /** The server-only context injected at serve time. */ ctx: TCtx; /** Log-backed CAS helper: was this path modified after the writer's basis? */ touchedSince(basisVersion: number): boolean; } interface IViewCondEveryone { readonly kind: "everyone"; } interface IViewCondAvatarTypes { readonly kind: "avatarTypes"; readonly types: readonly TAvatarType[]; } type TViewCondFn> = (context: IViewRuleContext) => boolean; type TViewCond> = IViewCondEveryone | IViewCondAvatarTypes | TViewCondFn; interface IAlterCondServerOnly { readonly kind: "serverOnly"; } type TAlterCondFn, TValue = unknown, TState = unknown> = (context: IAlterRuleContext) => TRuleVerdict; interface IAlterCondServerChecked { readonly kind: "serverChecked"; readonly fn: (context: IServerCheckedRuleContext, any, TState, TCtx>) => TRuleVerdict; } interface IAlterCondAll { readonly kind: "all"; readonly conds: readonly TAlterCond, unknown, TState, TCtx>[]; } type TAlterCond, TValue = unknown, TState = unknown, TCtx = unknown> = IAlterCondServerOnly | TAlterCondFn | IAlterCondServerChecked | IAlterCondAll; interface IRealmRule { /** The original pattern (pre brace-expansion) — part of the schema hash. */ readonly pattern: string; readonly view: TViewCond; readonly alter: TAlterCond; } //#endregion //#region src/realm/RealmDefinition/Schema/schema.types.d.ts /** * Realm schema nodes — the runtime AST `defineRealm` compiles into the token map, the schema hash, * and (in M4) the server-side value validator. Every node carries a phantom `_t` holding the * TypeScript type it describes, so inference (`TInferNode`) is a single conditional rather than a * per-kind switch. Nodes are plain readonly objects: the definition module ships to clients, so * nothing here may close over server data. */ /** Phantom-typed base — `_t` never exists at runtime; it only carries the inferred type. */ interface ISchemaNodeBase { /** @internal phantom — the TS type this node describes. Never set at runtime. */ readonly _t?: T; } interface ISchemaString extends ISchemaNodeBase { readonly kind: "string"; /** Max length in UTF-16 code units (`String.prototype.length`). Contributes to the schema hash. */ readonly maxLength?: number; } interface ISchemaNumber extends ISchemaNodeBase { readonly kind: "number"; readonly min?: number; readonly max?: number; /** Stored only as `true` — `integer: false` is normalized to omission at build time. */ readonly integer?: true; } interface ISchemaBoolean extends ISchemaNodeBase { readonly kind: "boolean"; } interface ISchemaLiteral extends ISchemaNodeBase { readonly kind: "literal"; readonly value: V; } interface ISchemaUnion extends ISchemaNodeBase { readonly kind: "union"; readonly options: readonly TSchemaNode[]; } /** * Optional node. `Inner` keeps the **concrete** wrapped node type (mirroring how {@link ISchemaRecord} * parameterizes its `value`) rather than widening `inner` to the full recursive `TSchemaNode` union. * This matters for rule-path resolution: `TUnwrapNode` descends through `inner`, and if that were the * whole union the unwrap distributes over every node kind (re-entering the optional member on each * pass) — a per-optional-path cost that compounded across a `rules` array to trip TS2589 * ("excessively deep"). Threading `Inner` makes the unwrap a single concrete step. */ interface ISchemaOptional extends ISchemaNodeBase { readonly kind: "optional"; readonly inner: Inner; } /** * Object node — `entries` keeps the *precise* builder-supplied map type (`E`) so rule-path * resolution can walk it segment by segment at the type level. */ interface ISchemaObject = Record> extends ISchemaNodeBase { readonly kind: "object"; readonly entries: E; } /** * Record node — a dynamic-key collection. `keyVar` names the `$param` that rule paths bind for * this level (`t.record(t.id("vendorId"), …)` ⇒ `inventory.$vendorId.…`). Keys are always strings * on the wire (interned per session, the protocol contract). */ interface ISchemaRecord extends ISchemaNodeBase> { readonly kind: "record"; readonly keyVar: string; readonly value: V; /** Max entry count. Contributes to the schema hash; enforced state-aware (incremental adds too). */ readonly maxKeys?: number; } /** Array node — leaf-replace semantics only in v1 (proposal §7.8): records are the collection primitive. */ interface ISchemaArray extends ISchemaNodeBase { readonly kind: "array"; readonly item: TSchemaNode; /** Max element count. Contributes to the schema hash. */ readonly maxItems?: number; } /** An embedded standard-schema (e.g. valibot) validator at a leaf. */ interface ISchemaStandard extends ISchemaNodeBase { readonly kind: "standard"; readonly schema: StandardSchemaV1; /** * Opt-in hash contribution: the embedded validator itself is opaque to the schema hash, so a * tagged leaf canonicalizes as `{k:"std",tag}` and the consumer bumps the tag on every contract * change — restoring the attach gate for leaf-level changes. Untagged leaves keep `{k:"std"}`. */ readonly hashTag?: string; } /** Record-key marker — only valid as `t.record`'s first argument; binds `$varName` in rule paths. */ interface ISchemaId { readonly kind: "id"; readonly varName: N; } /** * Server-context marker — TYPE ONLY. The value is injected at `createRealmServerEngine` time and * never exists in client bundles; this marker only threads `TCtx` through the definition's types. */ interface ISchemaServerContext { readonly kind: "serverContext"; /** @internal phantom */ readonly _ctx?: TCtx; } type TSchemaNode = ISchemaString | ISchemaNumber | ISchemaBoolean | ISchemaLiteral | ISchemaUnion | ISchemaOptional | ISchemaObject | ISchemaRecord | ISchemaArray | ISchemaStandard; /** The realm state root: a named map of top-level branches (conceptually an object node). */ type TSchemaRoot = Record; /** Infer the TS type a node describes (via the phantom `_t`). */ type TInferNode = N extends ISchemaNodeBase ? T : never; /** Keys of an entries map whose node is optional — mapped to `?:` properties. */ type TOptionalEntryKeys> = { [K in keyof E]: E[K] extends { kind: "optional"; } ? K : never; }[keyof E]; /** The object type an entries map describes, with optional-node keys made optional properties. */ type TInferEntries> = { [K in Exclude>]: TInferNode; } & { [K in TOptionalEntryKeys & keyof E]?: TInferNode; } extends (infer O) ? { [K in keyof O]: O[K]; } : never; //#endregion //#region src/realm/RealmDefinition/Intents/intents.types.d.ts /** * Realm intents: named, atomic, settle-only, server-executed mutations — the * default write path. An intent's only outputs are its state effects plus the caller's settlement * (no result payloads: a result blob would live only in a losable ack frame; state-as-outcome is * versioned, logged, and replayed). Entities an intent creates use **avatar-supplied IDs** in the * input, with an "already applied ⇒ commit as no-op" idempotency guard as the standard shape. */ interface IRealmIntentDef { /** The avatar types allowed to call this intent (the security gate, with the input schema). */ readonly allow: readonly TAvatarType[]; readonly input: TInput; /** * Optional client-side prediction — mutates a draft of the **caller's view** only; its patches * join the pending queue like a write frame. A predictor that throws is treated as * absent (prediction must never break the write). */ readonly optimistic?: (context: { view: TState; avatar: IRealmAvatarRef; input: TInferNode; }) => void; /** * Server-side, atomic: `state` is an immer draft of the **full authoritative state** (bypasses * view/alter rules — trusted code; `allow` + the input schema are the boundary). Return `true` * to commit (a no-op commit is the idempotent-retry ack) or a NiceError to reject — the draft * is discarded entirely, never partially applied. */ readonly apply: (context: { state: TState; avatar: IRealmAvatarRef; input: TInferNode; ctx: TCtx; }) => TRuleVerdict; } /** The `i` builder handed to a realm definition's `intents: (i) => ({ ... })` callback. */ interface IIntentBuilder { define(def: IRealmIntentDef): IRealmIntentDef; } //#endregion //#region src/realm/RealmDefinition/Schema/infer.types.d.ts /** * Type-level rule-path resolution: given the state root and a pattern string like * `"inventory.$vendorId.$produceId.pricePerKg"`, produce the leaf **value type** (`number`) and * the bound **params record** (`{ vendorId: string; produceId: string }`), so plain (isomorphic) * rule functions passed directly to `.view()` / `.alter()` are precisely typed with zero * annotations at the call site. * * Supported segment forms: literal keys, `$var` (record levels — binds a string param), `{a,b}` * (brace expansion — resolves to the union of branches), and trailing `*` / `**` wildcards * (resolve to `unknown`: wildcard rules gate access, they don't inspect values). * * Conds composed via `r.all(...)` / `r.serverChecked(...)` are built *outside* the `.alter()` * contextual-typing position, so they intentionally fall back to the generic context * (`params: Record`, `prev`/`next: any`) — see `rules.types.ts`. */ type TSplitPath

= P extends `${infer H}.${infer R}` ? [H, ...TSplitPath] : [P]; /** Unwrap optional wrappers when descending (a rule path addresses the inner value). */ type TUnwrapNode = N extends { kind: "optional"; inner: infer I; } ? TUnwrapNode : N; /** One resolved rule path: the leaf value type + the `$var` params bound along the way. */ interface IResolvedRulePath> { value: V; params: P; } /** Flatten an intersection of param records into one readable object type. */ type TFlattenParams

= { [K in keyof P]: P[K]; } & {}; type TStepLiteral = N extends { kind: "object"; entries: infer E; } ? Seg extends keyof E ? TResolveSegs, Rest, P> : never : N extends { kind: "record"; value: infer V; } ? TResolveSegs, Rest, P> : never; type TResolveSegs = Segs extends readonly [] ? IResolvedRulePath, TFlattenParams

> : Segs extends readonly [infer H extends string, ...infer Rest extends readonly string[]] ? H extends "*" | "**" ? IResolvedRulePath> : H extends `{${string}}` ? IResolvedRulePath> : H extends `$${infer Var extends string}` ? N extends { kind: "record"; value: infer V; } ? TResolveSegs, Rest, P & Record> : never : TStepLiteral : never; /** Resolve a rule path pattern against the state root. `never` value ⇒ the pattern is invalid. */ type TResolveRulePath = TResolveSegs<{ kind: "object"; entries: Root; }, TSplitPath, Record>; //#endregion //#region src/realm/RealmDefinition/Rules/ruleBuilder.d.ts /** * The `r` builder handed to a realm definition's `rules: (r) => [...]` callback. * `r.path(pattern)` resolves the pattern against the state shape at the type level, so plain * functions passed to `.view()` / `.alter()` get precise `params` and `prev`/`next` types. * Conditions built via `r.all` / `r.serverChecked` use the generic context tier (see * `rules.types.ts` module doc). */ interface IRulePathBuilder { /** v1: view conditions are coordinate-only (`{ avatar, params }`) — the protocol contract restriction. */ view(cond: TViewCond): { alter(cond: TAlterCond): IRealmRule; }; } /** * `TState` is threaded in **pre-resolved** (the caller computes `TInferEntries` once at * the `defineRealm` boundary) rather than re-derived here from `TStateDef`. Every `r.path(...)` call * would otherwise re-instantiate the full inferred state — a rich schema then trips TS2589 * ("excessively deep") because the deep state type is expanded once per rule and combined with each * path's `TResolveRulePath` resolution. Keeping `TState` an opaque parameter lets TS reference it by * name instead of re-expanding the object shape on every rule. */ interface IRuleBuilder { path

(pattern: P): IRulePathBuilder>; /** Everyone may view (includes replica-class clients — the protocol contract). */ readonly everyone: IViewCondEveryone; /** Only `engine.update()` (server code) writes here. */ readonly serverOnly: IAlterCondServerOnly; avatarTypes(...types: readonly TAvatarType[]): IViewCondAvatarTypes; /** * Wrap a check that needs the server context / patch log — server-evaluated only; avatar * prediction auto-passes it (exactly the slice of optimism that can roll back, the protocol contract). */ serverChecked(fn: IAlterCondServerChecked["fn"]): IAlterCondServerChecked; /** Compose alter conditions — all must pass; first NiceError rejects. */ all(...conds: readonly TAlterCond, any, TState, TCtx>[]): IAlterCondAll; } //#endregion //#region src/realm/RealmDefinition/Rules/ruleTrie.d.ts /** The one property the trie needs — keeps the registry generic over precisely-typed rules. */ interface IRuleLike { readonly pattern: string; } interface IRuleMatch { rule: TRule; params: Record; } declare class RealmRuleTrie { private readonly _root; private readonly _patterns; constructor(rules: readonly TRule[]); /** The source patterns, in definition order (schema-hash input). */ get patterns(): readonly string[]; private _insert; /** Match a concrete (name-space) path; `undefined` when no rule covers it. */ match(path: readonly string[]): IRuleMatch | undefined; /** * Whether some rule's pattern can match a path strictly BENEATH `path` (a `**` at or above it * counts). Ignores `view` conditions — the answer is about schema reachability, not access. */ reachesBeneath(path: readonly string[]): boolean; private _reachesBeneath; private _match; } //#endregion //#region src/realm/RealmDefinition/Schema/tokenMap.d.ts /** * The schema token map: object keys collapse to small integers on the wire; dynamic * record keys stay strings (interned per session later — the protocol contract). Tokens are assigned over * **sorted key names per object level**, so reordering keys in the definition never renumbers, * and adding a key only shifts tokens *after* it alphabetically — with the schema hash (which any * change does alter) guarding against skew, sorted assignment makes token layout deterministic * and reviewable rather than declaration-order-fragile. */ /** A wire path element: an object-key token (int) or a dynamic record key (string, pre-intern). */ type TWirePathSegment = number | string; declare class RealmTokenMap { private readonly _root; constructor(stateRoot: TSchemaRoot); /** * Name path → wire path (object keys → ints; record keys pass through as strings, or as * interned ids when `internKey` resolves one — the protocol contract key interning). */ tokenizePath(path: readonly string[], internKey?: (key: string) => number | undefined): TWirePathSegment[]; /** * Wire path → name path (inverse of {@link tokenizePath}). At record levels an int segment is * an interned key id, resolved through `resolveKey` (absence of a resolver, or an unknown id, * is a hard error — silent misresolution would corrupt paths). */ detokenizePath(wirePath: readonly TWirePathSegment[], resolveKey?: (id: number) => string | undefined): string[]; /** The schema node names at the root level, in token order (test/debug surface). */ rootTokenNames(): readonly string[]; } //#endregion //#region src/realm/RealmDefinition/defineRealm.d.ts /** An avatar-type entry in the realm's `avatars` registry. v1: string persistent ids. */ interface IRealmAvatarTypeDef { readonly persistentId: ISchemaString; } /** * The **minimum** wire security level a realm requires of the connection carrying it. Two members * only — there is deliberately no `"none"`: an unauthenticated realm is the `allowPlain` acceptor * door, kept off the realm's own contract (a dev/trusted-network endpoint opts into plain at the * acceptor, never by weakening a realm definition). * * This is a realm-local string union, **not** wire's `ESecurityLevel` — this module ships to * clients, and mapping to the enum happens at the serve/connect boundary. It is a **policy floor * enforced at attach** (the server rejects a lower connection, the client refuses to `hello` on * one), NOT a wire-compat fact: it is intentionally left OUT of the schema hash, so it changes no * bytes on the wire and re-declaring it never forces a migration. */ type TRealmSecurityLevel = "authenticated" | "encrypted"; /** Extract the ctx type a `t.serverContext<...>()` marker carries (`undefined` when absent). */ type TCtxOf = N extends ISchemaServerContext ? TCtx : undefined; type TIntentsRecord = Record>; interface IDefineRealmInput, TStateDef extends TSchemaRoot, TCtxNode extends ISchemaServerContext | undefined, TIntents extends TIntentsRecord, TState = TInferEntries, TId extends string = string> { /** Stable wire identity — folded into the schema hash. */ id: TId; /** * The minimum wire security level this realm requires (default `"authenticated"`). Enforced at * attach on both ends — see {@link TRealmSecurityLevel}. Deliberately not in the schema hash. */ security?: TRealmSecurityLevel; /** Avatar-type registry (replica-class avatars are ordinary entries). */ avatars: TAvatars; /** TYPE-ONLY server context marker (`t.serverContext<...>()`); value injected at serve time. */ serverContext?: TCtxNode; state: TStateDef; /** * Transient state regions: subtree roots whose writes are * **not persisted** — not logged, not snapshotted, no CAS touch history. Presence/cursor shaped * state, worthless a second later, that would otherwise pay the full durability cost on a durable * realm. A resuming or cold-started client gets these regions fresh (replay refresh + hydrate) — * and, crucially, a **same-epoch hibernation wake** reloads a durable realm's transient regions * at their genesis value (they are stripped from every snapshot), so an attached client's own * entry silently vanishes on every wake. Pair a transient region with `connectRealm`'s * `assertOnAttach` to re-own your entry: it runs on the first hydrate AND (for a transient-bearing * realm) after every resume answer, so the entry is re-created across reconnects and wakes alike. * * v1 accepts **concrete, wildcard-free dot-paths** naming a subtree root (`["presence"]`, * `["board.cursors"]`) — validated at definition time. Not part of the schema hash (a persistence * behavior, not a wire fact). Do NOT use CAS (`touchedSince`) under a transient region — it has no * touch history; `durability: "reassert"` writes, by contrast, are the right pairing. */ transient?: string[]; rules: (r: IRuleBuilder>) => readonly IRealmRule>[]; intents?: (i: IIntentBuilder>) => TIntents; } interface IRealmDefinition { readonly id: TId; /** * The resolved minimum wire security level (defaulted to `"authenticated"`). Read by the serve * host and `connectRealm`/`connectRealmReplica`; never hashed. */ readonly security: TRealmSecurityLevel; readonly avatarTypes: readonly TAvatarType[]; readonly stateDef: TStateDef; readonly rules: readonly IRealmRule[]; readonly ruleTrie: RealmRuleTrie>; readonly intents: TIntents; /** Intent names in sorted (wire-token) order. */ readonly intentNames: readonly string[]; readonly tokens: RealmTokenMap; /** * Parsed transient region roots — concrete segment paths, validated at define time. * Empty for a fully-durable realm. Read by the engine (commit classification, replay refresh) and * the DO host (snapshot strip); deliberately NOT in the schema hash. */ readonly transient: readonly string[][]; /** SHA-256 over the canonical definition — the handshake gate. */ readonly schemaHash: string; /** @internal phantom */ readonly _state?: TState; /** @internal phantom */ readonly _ctx?: TCtx; } /** * The single source of truth: one block declaring the state shape, the client types, * the rules, and the intents — from which the types, token map, schema hash, rule trie, and * prediction bundle all derive. **This module ships to clients**: nothing here may close over * secrets; server-only data enters via `createRealmServerEngine(realm, { ctx })`. */ declare function defineRealm, TStateDef extends TSchemaRoot, TCtxNode extends ISchemaServerContext | undefined = undefined, TIntents extends TIntentsRecord = Record, TState = TInferEntries, const TId extends string = string>(input: IDefineRealmInput): IRealmDefinition, TIntents, TStateDef, TId>; type TInferRealmState = R extends { _state?: infer TState; } ? TState : never; /** * A client type's view of the realm state. v1: identical to the full state type — none of the * v1 `view` condition forms are statically decidable per branch (function conditions can't be * evaluated at the type level), so no branch can be soundly omitted yet. Static narrowing for * `r.avatarTypes(...)`-only branches is a recorded follow-up. */ type TInferAvatarView = TInferRealmState; type TInferIntentInput = TInferNode; //#endregion //#region src/realm/RealmWire/realmFrame.types.d.ts /** * The realm wire protocol: every frame is a msgpack fixarray `[kind, slot, …]` riding * the wire frame-protocol port at prefix `0x01` (M1 seam). The **slot** is a client-assigned small * int established by `hello`, so several realms — or several instances — share one peer link with * a one-byte discriminator per frame. * * Identity note (deviation D-13): v1 protocols are secure-duplex-only (D-11), so the connection is * already authenticated when the first realm frame arrives — `hello` carries no credential of its * own; the server resolves coordinates from the connection identity via its `resolveAvatar` hook. */ declare const REALM_FRAME_KIND: { readonly hello: 0; readonly hydrate: 1; readonly patches: 2; readonly write: 3; readonly intent: 4; readonly ack: 5; readonly reject: 6; readonly keyDict: 7; readonly detach: 8; /** * Client→server capability advertisement. Sent right after * every `hello` (fresh attach, reconnect, probe) so a hibernation-woken server — which lost the * per-session feature state — re-learns them for free. An old server decodes an unknown kind → * drops it → never emits the features it names; a new server with a client that never sends this * frame sees no features and stays on the legacy per-frame path. Both skew directions are safe by * the drop-unknown rule the codec + acceptor already enforce. */ readonly clientCaps: 9; /** * Server→client egress envelope (Phase 1 wire; Phase 2 emits it). Carries several complete realm * frames as one message — see {@link IRealmFrameBatch}. Emitted **only** to a connection that * advertised {@link REALM_FEATURE.batch}; never sent client→server. Nesting is forbidden. */ readonly batch: 10; }; /** Patch op ints — 1:1 with immer's `replace`/`add`/`remove`. */ declare const REALM_OP: { readonly replace: 0; readonly add: 1; readonly remove: 2; }; type TRealmOpKind = (typeof REALM_OP)[keyof typeof REALM_OP]; /** * One wire patch op: `[op, path]` for `remove`, `[op, path, value]` otherwise. Path segments are * schema tokens (ints at object levels), interned key ids (ints at record levels), or raw strings * (record keys before interning) — the token map's level structure disambiguates int meanings. */ type TWireOp = [typeof REALM_OP.remove, TWirePathSegment[]] | [TRealmOpKind, TWirePathSegment[], unknown]; interface IRealmFrameHello { kind: typeof REALM_FRAME_KIND.hello; slot: number; realmId: string; schemaHash: string; /** The last authoritative version this client holds (`-1` = none — full hydrate needed). */ lastKnownVersion: number; /** * The log epoch the client's `lastKnownVersion` belongs to — echoed from the * hydrate that delivered it; absent before the first hydrate. The server replays only when it * matches its own epoch; any mismatch (wiped storage, re-created realm, migration) forces a * full hydrate instead of a diff computed against a different history. */ epoch: string | undefined; } interface IRealmFrameHydrate { kind: typeof REALM_FRAME_KIND.hydrate; slot: number; version: number; /** msgpack blob of the client's sliced state (name-keyed; chunked above the host's ceiling). */ stateBlob: Uint8Array; /** Key-dictionary seed entries (reserved — v1 servers send `[]`, interning is patch-lazy). */ keyDictSeed: [key: string, id: number][]; /** `true` = a continuation chunk follows; apply atomically only when the final chunk lands. */ more: boolean; /** The engine's log epoch — minted at genesis and at `migrate`; echo it in `hello`. */ epoch: string; /** * The client-relevant ingress limits: `[maxPatchesPerFrame, maxFrameBytes, * writeRatePerSecond]` — the client coalescer splits over-limit flushes against these. */ limits: [maxPatchesPerFrame: number, maxFrameBytes: number, writeRatePerSecond: number]; /** * The server-resolved avatar identity echo: `[type, persistentId, instanceId]` * — the coordinates verdicts and view slicing run against. The client warns loudly when it * disagrees with its own ref (the "prediction passes, server rejects every time" bug class). */ avatar: [type: string, persistentId: string, instanceId: string]; } interface IRealmFramePatches { kind: typeof REALM_FRAME_KIND.patches; slot: number; fromVersion: number; toVersion: number; ops: TWireOp[]; } interface IRealmFrameWrite { kind: typeof REALM_FRAME_KIND.write; slot: number; clientSeq: number; basisVersion: number; ops: TWireOp[]; } interface IRealmFrameIntent { kind: typeof REALM_FRAME_KIND.intent; slot: number; clientSeq: number; /** Sorted-name intent token (part of the schema hash). */ intentToken: number; input: unknown; } /** Settle-only (D6): no result payload — outcomes live in state. */ interface IRealmFrameAck { kind: typeof REALM_FRAME_KIND.ack; slot: number; clientSeq: number; version: number; } interface IRealmFrameReject { kind: typeof REALM_FRAME_KIND.reject; slot: number; clientSeq: number; /** The rejecting NiceError's `toJsonObject()` — rehydrate with `castNiceError`. */ error: Record; } interface IRealmFrameKeyDict { kind: typeof REALM_FRAME_KIND.keyDict; slot: number; entries: [key: string, id: number][]; } interface IRealmFrameDetach { kind: typeof REALM_FRAME_KIND.detach; slot: number; reason: string | undefined; } /** Client→server capability advertisement — the `features` are opaque {@link REALM_FEATURE} tokens. */ interface IRealmFrameClientCaps { kind: typeof REALM_FRAME_KIND.clientCaps; slot: number; features: string[]; } /** * Server→client egress envelope: `frames` are complete, already-decoded realm frames, each routed * to its OWN inner slot on receipt (a batch is a **connection**-level envelope). The codec rejects * a nested batch and any malformed child at decode time — so a decoded batch is always a flat list * of well-formed non-batch frames (the fuzz gate holds for the envelope's contents too). */ interface IRealmFrameBatch { kind: typeof REALM_FRAME_KIND.batch; slot: number; frames: TRealmFrame[]; } type TRealmFrame = IRealmFrameHello | IRealmFrameHydrate | IRealmFramePatches | IRealmFrameWrite | IRealmFrameIntent | IRealmFrameAck | IRealmFrameReject | IRealmFrameKeyDict | IRealmFrameDetach | IRealmFrameClientCaps | IRealmFrameBatch; //#endregion //#region src/realm/RealmServer/RealmServerEngine.d.ts /** * The authoritative realm server engine — host-agnostic: it never sees a socket, only * per-connection `send` callbacks the host adapter supplies. One engine = one live **instance** * of a realm definition; genesis runs in the constructor, exactly once. * * Pipelines: an avatar `write` runs limits → path decode → schema value validation → * subtree expansion → per-leaf alter rules (whole frame atomic) → commit; an `intent` runs allow → * input validation → atomic `apply` draft → commit. Both share the commit tail: version++ → log * append → per-view-signature slicing (encode once per signature group) → broadcast → ack to the * sender **after** its own patches frame (read-your-writes on settle, the protocol contract). */ interface IRealmLimits { /** Max patch ops in one write frame. */ maxPatchesPerFrame: number; /** Max encoded bytes of one inbound realm frame (checked when the host reports a size). */ maxFrameBytes: number; /** Max dynamic record-key length (also protects the intern dictionary). */ maxRecordKeyLength: number; /** Max leaves one subtree write may expand to. */ maxExpandedLeaves: number; /** Write/intent token-bucket rate per connection. */ writeRatePerSecond: number; writeRateBurst: number; /** Limit breaches on one connection before it is forcibly detached. */ maxBreachesBeforeDetach: number; } declare const DEFAULT_REALM_LIMITS: IRealmLimits; interface IRealmInstanceInfo { instanceId: string; } /** How an `onAvatarDetach` fired — see the option's doc. */ interface IRealmDetachDetail { via: "immediate" | "grace-expired"; /** `grace-expired` only: ms between the last connection's drop and the hook firing. */ deferredMs?: number; } /** One parked detach — exposed so a host can persist it across evictions. */ interface IRealmPendingDetach { avatar: IRealmAvatarRef; reason: string; /** When the last connection dropped (drives `deferredMs`). */ since: number; /** When the grace window elapses and the detach fires. */ fireAt: number; } type TRealmMutationSource = "write" | "intent" | "server"; interface IRealmServerEngineOptions { /** Server-only context (secrets live here — never in the realm definition). */ ctx?: TCtx; instanceId?: string; /** Genesis: runs exactly once per instance, before the first attach. */ initialState: TState | ((info: IRealmInstanceInfo) => TState); /** * A avatar's first live connection attached. **Dispatch is deferred a microtask**: by the time it * runs, the attach — including the hydrate/replay send — has completed, * so the hook may freely call `engine.update()` (no re-entrancy wrapper needed; the resulting * commit reaches the new avatar as an ordinary patches frame). Attach can re-fire for * hibernation survivors without a paired detach — keep it idempotent. */ onAvatarAttach?: (avatar: IRealmAvatarRef, ctx: TCtx) => void; /** * A avatar's last connection dropped. Deferred like {@link onAvatarAttach}. * `detail` says how it fired: `"immediate"` (no grace / bypassed — e.g. a revocation) or * `"grace-expired"` (the {@link avatarDetachGraceMs} window elapsed with no re-attach, with * `deferredMs` = how long after the drop it fired). */ onAvatarDetach?: (avatar: IRealmAvatarRef, reason: string, ctx: TCtx, detail?: IRealmDetachDetail) => void; /** * Fire {@link onAvatarDetach} only if the avatar hasn't re-attached within this window * (default `0` = immediate, today's behavior) — the presence-flap fix: * with transport auto-redial a blip heals in ~1–2 s, and every roster/turn/ready consumer * otherwise hand-rolls this debounce (unsafely, in a DO — a raw `setTimeout` is not * hibernation-safe). A re-attach inside the window swallows BOTH hooks — no detach, no attach: * the avatar never left (the timed twin of the probe/wake reattach swap, the reconnect contract). * * Scheduling: with {@link onDetachScheduleChanged} unset the engine self-schedules on an * unref'd `setTimeout` (right for plain hosts; NOT hibernation-safe). The Cloudflare DO host * (`createRealmHost`) provides the callback and backs the deadline with the DO alarm * mux + persisted pending rows, so the deferred detach fires even across an eviction. * `detachAvatar` (revocation) always bypasses the grace. */ avatarDetachGraceMs?: number; /** * The host-scheduling seam for {@link avatarDetachGraceMs}: called whenever the pending-detach * set changes (armed, swallowed by a re-attach, fired, restored). The host reads * {@link RealmServerEngine.pendingDetaches} / {@link RealmServerEngine.nextDetachDeadline}, * persists/arms its own timer (the DO alarm mux), and calls * {@link RealmServerEngine.fireExpiredDetaches} when it elapses. Providing this disables the * engine's own `setTimeout` fallback. */ onDetachScheduleChanged?: () => void; /** * Server-side mutation hook — fires **synchronously** after every commit with the canonical * patches. **Observe-only**: it runs post-commit, so calling `engine.update()` * from it is unbounded recursion, not re-entrancy — persist/report/throttle here (the DO * host's snapshot cadence rides it), never write. */ onMutation?: (patches: readonly Patch[], meta: { version: number; source: TRealmMutationSource; avatar?: IRealmAvatarRef; }) => void; /** * Diagnostic hook: fired synchronously when a `write` passes schema + rules but cannot * APPLY — its target's parent is gone (a pruned entry, or a transient region reset by a wake since * the write's basis) — and is rejected `write_target_missing`. `liveConnections` is the writer * avatar's current attached-socket count (a divergence under a live writer is the interesting * case); a caller that also logs whether the write's transient root is wholly empty vs. partly * populated can discriminate a *region reset* from a single-*entry prune* in production. Observe-only. */ onWriteTargetMissing?: (detail: { avatar: IRealmAvatarRef; connKey: string; path: string; liveConnections: number; }) => void; limits?: Partial; /** * Persist the replay high-water across a hibernation wake. Called * whenever a connection's high-water advances (once per accepted `write`/`intent`), with the * **client-handle** identity — `(avatar, slot)` — so a same-socket wake restores the same * sequence. The host keys durable storage by `(realmId, avatar.persistentId, avatar.instanceId, * slot)`; `instanceId` is fresh-per-boot ([RuntimeCoordinate] reliable-delivery contract), so a * rebooted client (new `instanceId`) never restores a stale predecessor's high-water. Omit for * in-memory-only realms (the guard still holds within a live session and across reconnects). */ persistSeqHighWater?: (avatar: IRealmAvatarRef, slot: number, highWater: number) => void; /** * The wake-safe counterpart to {@link persistSeqHighWater}: on attach, return the persisted * high-water for this `(avatar, slot)` client handle (or `undefined` if none). Only consulted for * a `connKey` the engine has no live high-water for — a re-hello keeps its in-memory value; a * post-wake attach (new `connKey`, lost in-memory map) restores from here. */ restoreSeqHighWater?: (avatar: IRealmAvatarRef, slot: number) => number | undefined; /** Patch-log store (default in-memory; a DO backs this with SQLite at M6). */ logStore?: IReliableLogStore; /** Versions kept replayable behind the head (older reconnects fall back to full hydrate). */ logWindow?: number; /** Clock for the rate bucket (injectable for tests; never visible to rules). */ now?: () => number; /** * Broadcast-coalescing window in ms. `undefined`/`0` (default) * keeps the per-commit broadcast — every commit fans out immediately, today's exact behavior. When * set, commits accumulate for up to this long and flush as ONE conflated `patches` frame per * connection, so each client's inbound is bounded by `1/broadcastCoalesceMs` regardless of how many * peers are writing (the fix for the participant-count amplification). The trade: a write's ack — * and thus `await handle` — settles up to one window later (read-your-writes still holds; the ack * rides the same flush, after its patches). Right for presence/cursor realms; leave off for a realm * that wants the lowest possible settle latency. */ broadcastCoalesceMs?: number; /** * Schedule the broadcast-window flush (injectable for deterministic tests — the twin of {@link now} * for {@link broadcastCoalesceMs}). Returns a cancel function. Defaults to `setTimeout` (unref'd, so * a pending window never keeps a process alive). Tests pass a scheduler that captures the callback * and fire it via {@link RealmServerEngine.flushBroadcasts} to avoid real timers. */ scheduleBroadcast?: (flush: () => void, ms: number) => () => void; /** * Boot from persisted state instead of genesis — the M6 cold-start path (snapshot + log-tail * replay, assembled by the platform host). `initialState` is ignored when present. `epoch` * carries the persisted log epoch; when absent (pre-epoch snapshot, or a * migration — its history is new) the engine mints a fresh one, which is the safe direction: * clients holding the old epoch full-hydrate instead of replaying a foreign history. */ restore?: { state: TState; version: number; epoch?: string; }; /** * Hydrate frames whose state blob exceeds this split into chunks (`more` continuation flag, * the protocol contract — Workers ws messages cap at 1 MiB). Default 900 KiB. */ hydrateChunkBytes?: number; } /** Directional totals for one side of the engine's traffic. */ interface IRealmEngineTrafficCounters { /** Inbound decoded frames (writes/intents/caps/detach) and their byte sizes when the host knew them. */ ingressFrames: number; ingressBytes: number; /** * Outbound **WS messages** — the unit platforms bill per-message (one `_transmit` raw send). * With batch-envelope coalescing, several frames ride one message. */ egressMessages: number; /** Outbound realm frames (pre-coalescing) — `egressFrames / egressMessages` = the coalesce win. */ egressFrames: number; egressBytes: number; } /** The engine's traffic snapshot — plain data, no devtools dependency. */ interface IRealmEngineTrafficSnapshot extends IRealmEngineTrafficCounters { sinceMs: number; /** Frames per WS message (≥ 1); how much the batch envelope + broadcast tick actually saved. */ egressCoalesceRatio: number; /** * Live connections' own counters (a detached connection's counts remain in the totals), each * tagged with the participant behind it (`avatarType`/`avatarId` — the avatar's `type` and * `persistentId`) so a live-deployment view can name which client it is, not just its connection key. */ connections: ({ connKey: string; avatarType: string; avatarId: string; } & IRealmEngineTrafficCounters)[]; } /** * One observed frame/message on the server wire (structurally an `ITrafficSample`, but declared here * so the engine stays devtools-agnostic). `bytes` is the ingress frame length / the raw egress WS * message length; `lane` is always `"realm"`; `linkId` is the connection key for per-connection stats. * Consumed by `serverWireTrafficScope` to feed a devtools traffic core — the server-side wire-tap that * mirrors the client's, so a backend's sidebar traffic panel is as live as a frontend's. */ interface IRealmEngineTrafficSample { atMs: number; dir: "in" | "out"; bytes: number; lane: string; linkId?: string; } declare class RealmServerEngine { private readonly _realm; private readonly _ctx; private readonly _limits; private readonly _now; private readonly _instanceId; private _state; /** Whether the schema declares any bounds — false skips every bounded-state walk. */ private readonly _hasBounds; private _version; private _mutating; /** The log epoch: identifies this history — replay requires an exact match. */ private readonly _epoch; private readonly _log; private readonly _logWindow; /** Recent write touches for `touchedSince` CAS — bounded by the log window. */ private _touches; private readonly _dict; private readonly _connections; private readonly _avatarConnCounts; /** * Connections with queued egress (Phase 2). Holds the record even after `detachConnection` removes * it from `_connections`, so a detach notice / breach reject already queued still flushes. Insertion * order = flush order (Set preserves it). */ private readonly _dirtyConns; /** Re-entrancy guard: a raw send can synchronously re-enter an entry point on an in-memory link * (a resend), whose own flush must be a no-op — the owning drain loop picks up the new frames. */ private _flushing; /** Server wire-tap listeners (devtools). Empty in production, so the emit is a hot-path no-op. */ private readonly _trafficListeners; private readonly _broadcastCoalesceMs; private readonly _scheduleBroadcast; /** Canonical name-patches accumulated across the open window's commits (conflated at flush). */ private _windowOps; /** The `statePrev` of the window's FIRST commit — the slicing basis for its `remove`s (V1). */ private _windowStartState; /** The version the open window began from — the flushed frame's `fromVersion`. */ private _windowFromVersion; /** Cancel handle for the armed window timer (undefined = disarmed / no open window). */ private _windowTimerCancel; /** * Acks deferred into the current window (P3): a successful write/intent's ack must reach the client * AFTER that window's patches frame, so it rides the window flush — never the immediate outbox (which * empties at the end of `receiveFrame`, ahead of the patches). Dropped for a connection that detaches * mid-window. */ private _pendingAcks; /** * Replay/duplicate high-water per connection **key** — the highest * `clientSeq` accepted for processing on a `connKey`. Kept **outside** the `IEngineConnection` * record on purpose: a same-avatar re-hello swaps the conn record in place (`attach()`'s * reattach path, the reconnect contract — it no longer detaches at all), so a per-record counter would reset * to `-1` and a replayed `hello` could reopen the window (Fact B). This map survives the * re-attach trivially; `detachConnection` clears it on a *real* close. Phase 3b persists this * across a hibernation wake (Fact C). */ private readonly _seqHighWater; private readonly _detachGraceMs; /** Parked last-connection detaches, keyed by `clientKey` — a re-attach swallows its entry. */ private readonly _pendingDetaches; /** The self-scheduling fallback timer (plain hosts — a host seam replaces it entirely). */ private _detachTimer; private readonly _traffic; private readonly _trafficSinceMs; private readonly _options; constructor(realm: IRealmDefinition, options: IRealmServerEngineOptions); get state(): Readonly; get version(): number; get instanceId(): string; /** The log epoch — minted at genesis/migrate, persisted by the platform host. */ get epoch(): string; get realmId(): string; get avatarTypes(): readonly TAvatarType[]; /** * Attach an authenticated avatar connection to this engine. Verifies the schema hash, sends * the initial `hydrate` (or a patch replay when `lastKnownVersion` is inside the log window), * and fires `onAvatarAttach` on an avatar's first live connection. Returns `false` (after a * `reject` with `clientSeq -1`, the attach-failure sentinel) when the hash mismatches. * * Calling it for a `connKey` that is already attached with the **same avatar** is a * **re-attach** (staleness probe / wake rehello): the connection record is swapped in place — * fresh `sentKeyIds`/`features`, preserved rate bucket, migrated window acks — and the avatar * lifecycle hooks do NOT fire. A different avatar on the * same `connKey` first runs the old avatar's full detach bookkeeping. */ attach(connKey: string, options: { avatar: IRealmAvatarRef; slot: number; schemaHash: string; lastKnownVersion: number; /** The epoch the avatar's `lastKnownVersion` belongs to (from its hello — the epoch contract). */ epoch?: string; send: (bytes: Uint8Array) => void; }): boolean; /** * Detach one connection (socket closed / avatar left the realm / forced). Every real close * clears the replay high-water (the `connKey` is never reused — the acceptor mints a fresh one * per socket — so this is pure cleanup, not correctness). `preserveReplayHighWater` is retained * for compatibility but no longer has an internal caller: a same-realm re-hello no longer * detaches at all — `attach()` swaps the connection record in place without firing the avatar * lifecycle, and the high-water survives trivially. */ detachConnection(connKey: string, reason?: string, notifyPeer?: boolean, preserveReplayHighWater?: boolean, /** A revocation-class detach ignores `avatarDetachGraceMs` — it is not a blip. */ bypassGrace?: boolean): void; /** Forced detach / revocation: drop every connection of a persistent avatar. */ detachAvatar(persistentId: string, reason?: string): void; /** * Park the per-avatar detach for the grace window (or fire it now with no/ bypassed grace) — * the one funnel every last-connection departure goes through, `reportAvatarLost` included. * Dispatch stays microtask-deferred so the hook may freely `engine.update()`. */ private _deferOrFireDetach; /** * Report an avatar known to be gone with no live engine connection — the DO host's wake * reconciliation (a socket that vanished while the DO hibernated). Runs the same * `avatarDetachGraceMs` funnel an ordinary last-connection close gets, so a prompt reconnect * after the wake swallows the detach instead of flapping presence. */ reportAvatarLost(avatar: IRealmAvatarRef, reason?: string): void; /** The earliest pending grace deadline (epoch ms), or `undefined` — the host's alarm target. */ nextDetachDeadline(): number | undefined; /** The parked detaches — a durable host persists these so they survive an eviction. */ pendingDetaches(): readonly IRealmPendingDetach[]; /** * Re-park persisted pending detaches after a wake (the durable host's boot path). Entries whose * avatar re-attaches (the wake rehello) are swallowed as usual; the rest fire when the host's * alarm calls {@link fireExpiredDetaches}. Keeps the earlier deadline on a key collision. */ restorePendingDetaches(rows: readonly IRealmPendingDetach[]): void; /** * Fire (and clear) every pending detach whose grace window elapsed — called by the host's * timer/alarm (or the engine's own fallback timer). Hooks fire with * `{ via: "grace-expired", deferredMs }`, microtask-deferred like every lifecycle dispatch. */ fireExpiredDetaches(now?: number): void; /** * The scheduling seam: hand the change to the host when it owns scheduling * (`onDetachScheduleChanged`), else self-schedule with an unref'd timeout — correct for plain * hosts; a DO host MUST own it (a raw timeout is not hibernation-safe). */ private _detachScheduleChanged; /** Currently attached connection keys (host adapters / tests). */ get connectionCount(): number; /** * The engine's traffic totals since construction: ingress frames/bytes, * egress **messages** (the per-message billing unit) vs frames (pre-coalescing) and bytes. * `egressCoalesceRatio` is the batch-envelope + broadcast-tick win made measurable — frames * folded per WS message. Plain data; hosts expose it however they like (a dev-only debug * action, or `realmEngineScope(engine, id)` plugged into a server devtools host, …). * Hello/attach traffic is handled by the host adapter before the engine and is not counted here. */ getTrafficSnapshot(): IRealmEngineTrafficSnapshot; /** * Subscribe to the server wire-tap: a per-frame `ITrafficSample`-shaped event for every ingress frame * and egress WS message (with real byte lengths, on lane `"realm"`, tagged with the connection key). * The devtools' `serverWireTrafficScope` feeds these into a traffic core so a backend's sidebar traffic * panel is as live as a frontend's. No listeners ⇒ the emit below is a hot-path no-op, so this costs * nothing in production. Returns an unsubscribe. */ subscribeTraffic(listener: (sample: IRealmEngineTrafficSample) => void): () => void; private _emitTraffic; /** * The egress features a connection advertised via `clientCaps` *, or `undefined` when the connKey is not attached. Phase 2 * consumes `REALM_FEATURE.batch` here to gate the `batch` envelope; exposed for hosts/tests. */ connectionFeatures(connKey: string): ReadonlySet | undefined; /** * Feed one decoded inbound frame from an attached connection. `byteLength` (when the host * knows it) drives the frame-size ingress limit. */ receiveFrame(connKey: string, frame: TRealmFrame, byteLength?: number): void; /** * Mutate authoritative state from server code (`r.serverOnly` paths — game ticks, fulfilment; * the protocol contract). Flows through the same version/log/slice tail, so server writes broadcast * identically. Throws when called re-entrantly from an intent `apply` or a rule (single-writer * invariant, the protocol contract). */ update(fn: (draft: TState) => void): void; private _handleWrite; private _handleIntent; private _commit; /** A path is transient (Phase 5) when a declared transient root is a prefix of it. */ private _isTransientPath; /** A path is EXACTLY a declared transient root — the whole-region refresh key in a replay. */ private _isTransientRoot; /** * Flush the open broadcast window (Phase 4): conflate its accumulated ops, fan out ONE patches * frame per connection (chunked under the ws ceiling — P4), then the window's deferred acks, all * via the outbox so each connection collapses to one WS message. Public so a host or test can force * a tick boundary; also the timer callback and the pre-hydrate flush in `attach`. A no-op when no * window is open (per-commit realms never open one). */ flushBroadcasts(): void; private _flushWindow; private _armWindowTimer; private _clearWindowTimer; private _flushPendingAcks; /** Settle a committed write/intent: immediate ack per-commit, or deferred into the window (P3). */ private _settleAck; private _broadcast; private _encodePatches; /** * Encode sliced ops into one-or-more patches frames, each under the ws message ceiling (P4). Splits * by op-count (recursive halving) — the parts share `fromVersion`/`toVersion` and apply in order to * the same state, since server→client ops are order-preserving within a version. A single op that * alone exceeds the ceiling is emitted anyway (indivisible — the same as a single over-limit commit * today; the hydrate path is the only genuinely large payload and it chunks separately). */ private _encodePatchesChunked; private _sendPatchesFrame; private _sendKeyDictDelta; /** Merged replay ops for versions `basis+1 … head`, or `undefined` when outside the window. */ private _buildReplayOps; private _logStreamId; private _sliceCtx; private _touchedSince; /** * The replay/duplicate high-water gate. Returns `false` — caller * must stop — when `clientSeq` is at or below the connection's high-water: the frame is either a * replay (a captured frame re-injected into the framing layer) or a benign ack-lost resend, which * by seq alone are indistinguishable and both safe to treat as already-processed. It is settled * **idempotently** — re-ack the current authoritative version (the client's handle settles * read-your-writes via the version; no per-seq bookkeeping needed) — never re-applied and never * counted as a breach. New seqs (`> high-water`) return `true`; the caller advances the high-water * only after ingress also passes (so a rate-limited retry keeps its seq — see `_handleWrite`). */ private _passesSeq; /** * Advance the connection's replay high-water and persist it. Persist * runs per accepted frame so the durable value never lags an arbitrary hibernation point (a * lagging value would reopen the wake-replay window). Cost: one host-side upsert per accepted * `write`/`intent` — see the host's `persistSeqHighWater`, which may batch if it proves hot. */ private _advanceSeqHighWater; private _passesIngress; private _breach; /** * Send a rejection to one connection. The wire carries **only** the error's public * `toJsonObject()` (ids, user-provided error context, message, stack) — never the realm's * `serverContext` (`ctx`), which the engine never places on an error (the protocol contract * secret-scrub, verified). Discipline this implies for realm authors: a rule/intent error's * **context and message are wire-visible**, so they must not embed server secrets (`ctx` values, * internal ids) — the same rule as the client bundle. Documented in the security guide (Phase 8). */ private _reject; private _guardReentrancy; /** Queue one already-encoded frame for a connection; the entry point's `_flushEgress` sends it. */ private _enqueue; /** * Drain every connection's outbox (Phase 2). Runs at the end of each public entry point. Frames * queued during ONE entry point collapse to one WS message per connection — a `batch` when the * connection advertised {@link REALM_FEATURE.batch} and more than one frame is pending, else bare * sequential sends (byte-identical to pre-Phase-2 for a non-batch peer). Re-entrancy safe (F4): * the guard makes a nested flush (a raw send re-entered an entry point on an in-memory link) a * no-op, and each connection's queue is reference-swapped before its frames go out, so frames a * re-entrant call enqueues are picked up by the owning loop AFTER the current snapshot — never * interleaved. Insertion order of `_dirtyConns` (Set) is the per-connection flush order. */ private _flushEgress; /** * Send one connection's snapshot of queued frames. One frame → bare (no envelope overhead). More * than one on a batch-capable connection → a `batch` envelope, split so no single message exceeds * the host's ws ceiling (`hydrateChunkBytes`) — which also keeps near-ceiling hydrate chunks in * their own message (never re-merged). A non-batch connection gets today's sequential bare sends. */ private _transmit; } /** Factory with full inference from the realm definition. */ declare function createRealmServerEngine(realm: IRealmDefinition, options: IRealmServerEngineOptions): RealmServerEngine; //#endregion //#region ../connect-core/build/RealmReplica--6fao_sl.d.mts //#region src/realm/RealmClient/realmDevtoolsTap.types.d.ts /** One optimistic mutation's lifecycle moment, correlated by `clientSeq`. */ interface IRealmDevtoolsMutationEvent { /** * `created` — enqueued (optimistically applied); `confirmed` — the server acked it; * `rejected` — settled with an error (authority reject, expiry `frame_too_stale`, immediate * predict/validation failure). A mutation rejected before it was ever enqueued (immediate * failure) carries `clientSeq: -1` and only ever emits `rejected`. */ type: "created" | "confirmed" | "rejected"; clientSeq: number; kind: "write" | "intent"; intentName?: string; durability?: "reassert"; /** A library-authored transient re-own (`assertOnAttach` reassert lane), not a user mutation. */ systemAssert?: boolean; /** `confirmed` only: the authoritative version the mutation landed at. */ version?: number; /** `rejected` only. */ errorIds?: string[]; /** `rejected` only: name-space paths whose optimistic effect was rolled back. */ rolledBackPaths?: string[]; } /** * The devtools tap `connectRealm({ devtools })` accepts. All byte sizes are DECODED realm-frame * payload sizes (the realm protocol's own bytes, pre-encryption, without the wire envelope) — the * true wire cost lives one layer down at `connectChannel({ wireTap })`'s `realm` lane. A `batch` * envelope reports its own total; its regrouped children report their kind with `bytes: 0` (the * codec decodes children in place, so per-child sizes don't exist) — kind *counts* stay exact. */ interface IRealmDevtoolsTap { /** The public handle + identity facts, once `connectRealm` assembled them. */ handleReady?(info: { handle: unknown; realmId: string; slot: number; avatar: { type: string; persistentId: string; instanceId: string; }; /** * The `envId` of the peer this realm's connection dials, when it rides a connection-owning * handle (`realmConnection(connector)`). A devtools topology attributes the realm to THIS * backend rather than inferring one from `realmId` — two hosts can serve the same realm id * (a durable board on a Durable Object and an ephemeral one on a plain server), and guessing * draws the traffic on the wrong wire. */ peer?: string; }): void; /** One decoded realm frame entering (`in`) or leaving (`out`) this handle's slot. */ onFrame?(dir: "in" | "out", kind: string, bytes: number): void; onStatus?(status: TRealmStatus, meta: { hasBeenLive: boolean; }): void; /** Every diagnostic — fires regardless of whether `onDiagnostic` is also wired. */ onDiagnostic?(event: TRealmDiagnosticEvent): void; onMutation?(event: IRealmDevtoolsMutationEvent): void; /** * One `realm.stats` sample folded in (a write confirm or an answered hello) — the post-fold * smoothed values, so a panel can chart RTT/jitter next to sync health without polling. */ onStats?(stats: { rttMs: number; jitterMs: number; samples: number; }): void; /** * One **projection flush** — the same `(cause, authoritative)` provenance a * `listenToPatches` listener is handed, minus the patches themselves. * * It exists because provenance is what makes a client's *shape* legible at a glance: a client * whose flushes are nearly all `"optimistic"` is predicting far ahead of its confirms, and one * that never leaves `"rebase"` is writing continuously — neither is visible in a status line or a * frame count. The patches are deliberately absent: a panel wants the pattern, and forwarding * every flush's payload would put the whole realm's traffic through the devtools transport twice. * * Fires on **every** flush, independent of whether anything called `listenToPatches` — devtools * must never depend on an unrelated consumer having opted in. Only the cheap meta is computed for * this; the patch diff stays behind the listener check that guards it. */ onFlush?(flush: { cause: TRealmPatchCause; authoritative: boolean; confirmedVersion: number; }): void; } //#endregion //#region src/realm/RealmClient/writeHandle.d.ts /** * The settle handle every realm write API returns: status + a **lazy thenable**. * The real promise materializes only when `.then`/`await` is used, so fire-and-forget writes * (cursor moves) never produce unhandled-rejection noise — while rejections always still reach * `onMutationRejected`. Await resolves `{ version }` with the read-your-writes guarantee (the ack * is ordered after the authoritative patches ≤ its version). */ type TRealmWriteStatus = "pending" | "confirmed" | "rejected"; interface IRealmWriteSettled { version: number; } interface IRealmWriteHandle extends PromiseLike { readonly status: TRealmWriteStatus; /** The hydratable rejection when `status === "rejected"`. */ readonly error: NiceError | undefined; } //#endregion //#region src/realm/RealmClient/RealmClient.d.ts /** * The realm client engine: `confirmed` state (authoritative frames only) + a `pending` * queue of optimistic frames, projected into one `connect-core/state` Store — the rebase model. * One Store flush per incoming frame; acks are ordered after the patches ≤ their version, so * `await handle` ⇒ the store already reflects the outcome (read-your-writes, the protocol contract). */ /** What the client engine talks through — a realm slot on some link. */ interface IRealmClientPort { send(bytes: Uint8Array): void; isOpen(): boolean; } interface IRealmPortHandlers { /** * One inbound decoded frame. `byteSize` is the decoded realm payload's size when the dispatcher * knows it (`realmMuxClient` passes the protocol payload's length; a regrouped batch child * carries none) — devtools attribution only, never behavior. */ onFrame(frame: TRealmFrame, byteSize?: number): void; /** Link (re)established — the engine sends its `hello`. */ onAttach(): void; onDetach(): void; } /** A slot-scoped connection source: `realmConnection` in production, loopbacks in tests. */ interface IRealmConnectionAdapter { slot: number; /** * The link's authenticated local coordinate, when the adapter came from a connection-owning * handle (`realmConnection(connector)`) — `connectRealm` defaults the client ref from it. */ coordinate?: IRuntimeCoordinate; /** * The coordinate of the peer this link dials, when the adapter came from a connection-owning * handle. Observational only — reported to `devtools.handleReady` so a topology can attribute this * realm to the backend it is *actually* connected to (a realm id alone is ambiguous: two hosts may * serve the same one). */ peer?: IRuntimeCoordinate; /** @deprecated Use {@link peer}. */ peerCoordinate?: IRuntimeCoordinate; /** * The connection's negotiated wire security level — carried from * `realmConnection(connector)`. `connectRealm`/`connectRealmReplica` assert it against the realm's * required minimum before the first `hello`. Absent on a bare-mux adapter (test loopback), where * the assertion is skipped. */ securityLevel?: ESecurityLevel; register(handlers: IRealmPortHandlers): IRealmClientPort; /** Release the slot (realm detached client-side). */ release(): void; /** * Ask the owning connection to tear down and re-dial the underlying link. * Optional: a bare-mux / loopback adapter omits it (nothing to re-dial). The production * `realmConnection(connector)` wires it to the connector's reconnect. Invoked when the * staleness probe goes unanswered — a half-open socket (`isOpen()` still `true`, sends into the * void) is otherwise undetectable at the realm layer. */ requestReconnect?: () => void; /** * Observe the owning connection's link-state events — the structural * shadow of the connector's `addLinkEventListener` (realm never imports action; only the fields * the realm reads are typed). The engine forwards a re-establishment (`link_up` after a drop) * into `onDiagnostic` as `link_redialed`. Optional: bare-mux / loopback adapters omit it. */ subscribeLinkEvents?: (listener: (event: { type: string; downForMs?: number; }) => void) => () => void; } /** * A rolled-back optimistic write/intent. **Wire `onMutationRejected` in production** — an unhandled * rejection silently un-does state the user already saw ("my move vanished"); a `rolledBackPaths` * rejection with no handler logs one `console.warn` per handle as a floor. Note the outcome is * only *definite* for a rules rejection (the `error` is the * rule's own "no"); a {@link err_realm} `frame_too_stale` here means the frame expired with an * **unknown** server outcome — re-read state, don't blindly re-issue a non-idempotent intent. */ interface IRealmMutationRejection { error: NiceError; kind: "write" | "intent"; intentName?: string; /** Name-space paths whose optimistic effect was rolled back. */ rolledBackPaths: string[]; } /** * Options for {@link connectRealm}. * * **Transport resilience (auto-redial) is configured on the connector, not the realm:** * `connectChannel(..., { reconnect })`. The realm rides whatever link the connector maintains — * these options only tune the realm's own sync-layer behavior (probes, expiry, diagnostics) on top * of that link. */ interface IConnectRealmOptions { /** * Who this client is to the realm. `type` is always explicit (realm-specific); `persistentId`/ * `instanceId` default from the connection's authenticated coordinate when the adapter carries * one (`realmConnection(connector)`) — explicit values override (tests/replicas). */ avatar: { type: TAvatarType; persistentId?: string; instanceId?: string; }; connection: IRealmConnectionAdapter; /** * Raise the client-side security floor above the realm's own `security` for this connection. * The effective client minimum is `max(realm.security, this)`, asserted * against the connection's negotiated level before the first `hello` — a shortfall fails the attach * with `insufficient_security` and never emits a frame. Can only *raise* the bar; the server * enforces its own floor independently. Omit to use the realm's declared minimum. */ security?: TRealmSecurityLevel; onMutationRejected?: (rejection: IRealmMutationRejection) => void; /** * A pending frame that outlives this window rejects with `frame_too_stale` (default 10s) — * the *optimistic-settle* expiry: past it, the write's UI effect rolls back. Not the same dial * as nice-action's `reliableActionTimeout` (default 60s), which is a *redelivery* deadline for * at-least-once actions — they differ on purpose. */ pendingExpiryMs?: number; /** * Extra coalescing window in ms for pointer-frequency paths (default: microtask only). * Successive direct writes inside the window merge into one wire frame. * * The window is trailing-edge: the first write arms a timer and the merged frame ships when * the window closes — a lone write therefore pays the full window as added latency before it * is sent. Right for continuous streams (cursor, drag); wrong for event-shaped input lanes * (keyboard transitions, button presses) — leave it unset there, the microtask-only default * still merges same-tick writes at zero added latency. For a leading-edge window (lone writes * send immediately, bursts still merge), use {@link coalesce} with `leading: true` instead. * This option is the trailing-edge shorthand for `coalesce: { ms }`; when both are given, * `coalesce` wins. */ coalesceMs?: number; /** * The full coalescing dial ({@link coalesceMs} is the trailing-edge shorthand). With * `leading: true` the window becomes a classic leading+trailing throttle: a write arriving * with **no open window seals and sends immediately**, then opens a merge window behind it as * a cooldown; writes landing inside the window coalesce and flush once at the window's end * (which starts the next cooldown). Sends stay capped at ~`1000 / ms` per second, but an * isolated write — a keyboard transition after quiet — no longer pays the window as latency. * The right shape when one connection carries both duty cycles (a held-key stream AND * transition events); a single hot path can use `update(fn, { flush: "immediate" })` instead. */ coalesce?: { ms: number; leading?: boolean; }; /** * Write-through (experimental): raw `realm.store.update(...)` calls are captured * and sent as realm writes. The engine's own projection flushes are excluded by the * synchronous `projecting` guard around `store.replace` (whose root replace patch is also * filtered — a wholesale swap is never a realm write). */ experimental_writeThroughStore?: boolean; /** * The presence primitive: state this avatar must assert whenever it is (re-)attached — a lobby * entry, a cursor row, "my side of the record". Runs * as an ordinary optimistic write after EVERY full hydrate: the first attach, an * out-of-log-window resume, and an epoch change (server wiped / ephemeral realm cold-started). * * On a **transient-bearing realm** it also runs after every incremental patch-replay resume * (reconnect AND live probe/rehello — every hello is tracked, so even the periodic staleness probe * heals): a transient region carries only its current value, so a same-epoch DO hibernation wake * reloads it empty and the replay refresh confirms the loss — re-asserting here is the only thing * that re-creates your entry. On a fully-durable realm * it does NOT re-fire on a replay resume — the asserted state is still confirmed there. Idempotent * either way: a no-op draft enqueues nothing. * * **Ordering guarantee (the reassert lane):** on a recovery, the re-own reaches the server BEFORE * any resent write or intent, so an intent whose server logic reads your transient entry (a `fire` * reading your `aim`) runs against the re-owned entry, never the wiped region. You do not sequence * this yourself — the library rides the recovery hello with the re-own on an internal lane. * * **The guard pattern is blessed and recommended.** Writing `if (draft.mine != null) return; …` * (re-own only if lost) is safe on EVERY recovery path: the draft the library evaluates on a * resume reflects the AUTHORITATIVE post-recovery state (the transient-region refresh has already * been applied), so a wake-wiped entry is observed as genuinely missing and re-created, while a * healthy resume observes it present and enqueues nothing. Prefer the guard to an unconditional * rewrite: it is cheaper (no idempotent write per healthy resume) and equally correct. To preserve * your entry's exact pre-wake VALUE, read it from your own source-of-truth store inside the assert * (`draft.mine = { …fromMyStore }`), not from the draft — after a wipe the draft's authoritative * value is absent, so `draft.mine?.x ?? 0` re-owns at defaults (any still-pending pre-wake leaf * writes then rebase on top). * * Rules apply as usual; a rejection surfaces once via `onMutationRejected` and is not * auto-retried (a rules rejection is a program error, not a race). Ordered before `whenLive()` * continuations resolve, so "await whenLive, then read my entry" observes the optimistic entry. * If a recovery ever fails to re-create an entry you own (no assert, or a truly pruned parent), * the `reown_missing` diagnostic fires (see {@link IConnectRealmOptions.onDiagnostic}). */ assertOnAttach?: (draft: TView) => void; /** * The staleness probe: while `live` with an open link and **no inbound realm * frame** for this window, re-send `hello(lastKnownVersion, epoch)` — idempotent by design * (current ⇒ an ~10 B empty replay that doubles as the liveness signal; stale ⇒ exactly the * missed patches; wiped server ⇒ full hydrate via the epoch). Kills the "ghost" class: a lost * wake-rehello, missed caps, or a suspended runtime all converge on "quiet too long → probe → * resync". Default 25 000 ms; `0` disables (tests / hosts with their own liveness). */ staleProbeAfterMs?: number; /** * Probe-escalation window: after a staleness probe, if **no** inbound * frame arrives within this window the link is presumed dead — status flips to `"connecting"`, * a `probe_escalated` diagnostic fires, and the connection's `requestReconnect` (when the * adapter provides one) is invoked. This is what closes the half-open-socket hole the probe * alone only *detects*: `isOpen()` stays `true` while sends vanish, so the probe would otherwise * re-send hellos into the void forever. Default 10 000 ms; `0` disables escalation (detect-only). */ probeReplyTimeoutMs?: number; /** * Observe sync-health events: automatic resyncs (`resync`), non-continuous frames * dropped during a recovery (`gap_dropped`), inbound frames that failed to decode/apply * (`frame_error`), staleness-probe escalations (`probe_escalated`), and the re-own tripwire * (`reown_missing` — a transient entry you own went missing and the recovery did not re-create * it; the definite signal to wire if you silence `write_target_missing` in `onMutationRejected`). * Wire this in production — resync frequency is the sync-health signal (a healthy realm emits * none of the above; `link_redialed`, below, is the exception). When absent, the first * occurrence of each event type logs one `console.warn` per handle (silent-failure guard). * * **Transport-level drops that heal by redial do not surface here** — a healthy heal is silent * at the sync layer (no sync was lost). For link drop/redial/re-establish observation, use the * connector's `onLinkEvent` (`connectChannel` options); the one transport event forwarded into * this stream is `link_redialed` (the link re-established, with `downForMs`), so realm-level * telemetry can count transport churn without a second wiring point. */ onDiagnostic?: (event: TRealmDiagnosticEvent) => void; /** * The devtools observation seam: decoded frames in/out, * mutation lifecycle (created → confirmed/rejected), every diagnostic, status flips. Wire it * with `RealmDevtoolsCore.instrument(label)` from `connect-core/realm/devtools/browser` — or any * {@link IRealmDevtoolsTap} of your own. Omit = zero overhead (one null check per event). */ devtools?: IRealmDevtoolsTap; } type TRealmStatus = "connecting" | "live" | "detached"; /** * Sync-health events surfaced by {@link IConnectRealmOptions.onDiagnostic}. Resync * frequency is the production sync-health signal — a healthy realm emits no sync events. The one * exception is `link_redialed`: it is transport churn, not lost sync, so expect it on ordinary * network drops and alert on the other types. */ type TRealmDiagnosticEvent = { /** A lost-sync condition was detected and a recovery hello was sent (or suppressed only by * a very recent one — see the reply-grace window). `write_target_missing` is the structural * divergence trigger (Phase 1.5 / the recovery contract): a server reject proved a predicted write could * not apply, so the client re-reads instead of looping on doomed frames. */ type: "resync"; reason: "version_gap" | "frame_error" | "write_target_missing"; fromVersion?: number; toVersion?: number; confirmedVersion?: number; } | { /** A `reject` frame arrived for a `clientSeq` no longer pending (Phase 1.5): the frame settled * (locally rebased away, or expired) between send and reject, or a stale duplicate. Harmless, * but its presence is the fingerprint of a divergence window — surfaced instead of dropped. */ type: "late_reject"; clientSeq: number; errorIds: string[]; } | { /** A non-continuous `patches` frame arrived while a recovery hello was in flight — dropped * without applying (it predates the recovery; the replay/hydrate answer supersedes it). */ type: "gap_dropped"; fromVersion: number; toVersion: number; confirmedVersion: number; } | { /** An inbound frame failed to decode or apply. */ type: "frame_error"; error: unknown; } | { /** The staleness probe went unanswered past its reply window. */ type: "probe_escalated"; } | { /** * The underlying transport link re-established after a drop — the * ONE transport event forwarded here, so realm-level telemetry can count link churn without * a second wiring point. A drop healed this way loses no sync (no `resync` fires); for the * full drop/redial/backoff picture, subscribe to the connector's `onLinkEvent`. */ type: "link_redialed"; downForMs: number; } | { /** * A transient entry this avatar owns went missing (a `write_target_missing` reject flagged * its parent) and the recovery re-own did NOT re-create it. This is the definite "your * `assertOnAttach` produced no write for path X" * signal — wire it if you silence `write_target_missing` in `onMutationRejected`, since that * reject is then your only other tell and is easily mistaken for benign wake noise. The * library escalates ONCE on the first occurrence (a forced full-hydrate — the in-place * equivalent of a page reload); a second `reown_missing` for the same path means even that did * not restore it, so the parent is legitimately gone (a pruned entry, a removed peer) and the * app should stop retrying and reflect that in its UI. `path` is dotted for display only — * do not parse it back into segments (a record key may itself contain a dot). */ type: "reown_missing"; path: string; }; /** Options bag for {@link IRealmHandle.update}. */ interface IRealmUpdateOptions { /** * `"reassert"` marks this write durable: it is exempt from `pendingExpiryMs` and is rebuilt + * resent on every reattach — including across an epoch change — until the server confirms or * rejects it. Link failures never roll it back; **authority still wins** (a rules rejection * settles immediately, durable or not). For producer roles: a client that owns an append-only * region (a host streaming an input log) writes it with this tier. Keep tiers per path region * — reassert frames only coalesce with other reassert frames. Bounded: past the backlog cap * further reassert writes reject with `durable_backlog_overflow` (fall back to re-syncing from * your source of truth). Intents have no durable tier — a durable data-answering exchange is * the action plane (reliable actions). */ durability?: "reassert"; /** * `"immediate"` skips the coalescing window for THIS write: any buffered coalescing writes * flush first (compose order is preserved — same as an intent), then this write seals and * sends on its own frame. The per-write escape hatch for a latency-critical lane (a game * input transition) on a connection whose other paths want a merge window. Under a recovery * hello the frame still parks like every sealed frame (resent rebased by the answer) — the * recovery invariants hold; "immediate" never streams against a wiped transient region. */ flush?: "immediate"; } interface IRealmPendingInfo { readonly count: number; has(pathPrefix: string): boolean; subscribe(listener: () => void): () => void; } /** * Live link-quality estimate for this realm handle — see {@link IRealmHandle.stats}. Values are * EWMA-smoothed; `null` until the first sample lands. */ interface IRealmStats { /** Smoothed round-trip ms: frame send → server confirm (the coalesce window is NOT included). */ rttMs: number | null; /** Smoothed mean absolute deviation of the RTT samples — the "how steady" companion number. */ jitterMs: number | null; /** Total samples folded in — gate displays on `samples > 0` (or a few, for a settled EWMA). */ samples: number; } /** Why a {@link IRealmHandle.listenToPatches} flush happened — see {@link IRealmPatchMeta.cause}. */ type TRealmPatchCause = "confirm" | "optimistic" | "rebase" | "hydrate"; /** The second argument to a {@link IRealmHandle.listenToPatches} listener. */ interface IRealmPatchMeta { /** * **How** this flush was produced — a shape hint for the emitted patches, NOT an authority * signal (that is {@link authoritative}): * - `"confirm"` — fresh authoritative patches applied with **no optimistic overlay in play**, so * the emission is the server's own ops verbatim (the internal no-diff fast path). * - `"optimistic"` — a local write/intent applied speculatively (includes the library's own * transient re-own). **The only cause that carries no new server information** — your own * un-acked write echoing back. * - `"rebase"` — the projection was rebuilt and the emission is a structural diff. Covers two * very different situations, which is why it cannot be read as "not authoritative": fresh * server patches landing **while you have writes in flight** (`authoritative: true` — the * common case for any client that writes continuously), and pure local rebuilds like an * expiry or reject rollback (`authoritative: false`). * - `"hydrate"` — a full rebuild: exactly `[{ op: "replace", path: [], value }]`. * * **Do not gate a reconciler on `cause === "confirm"`.** It means "authoritative *and* your * outbox happened to be empty", so a client that writes continuously — any game client — sees * most of its authoritative traffic as `"rebase"` and a confirm-gate silently discards it. The * effect scales with latency and is invisible on localhost. Gate on {@link authoritative}, or * simply skip `"optimistic"`. */ cause: TRealmPatchCause; /** * **The authority predicate**: `true` when this flush applied fresh authoritative state (a * server patches frame — with or without an optimistic overlay in play — or a hydrate), `false` * when it was a purely local rebuild (your own optimistic write, an expiry/reject rollback, an * ack dropping a settled overlay). * * This is the field a predictor/reconciler wants: `if (!meta.authoritative) return;`. Pair it * with a domain freshness check (a tick or version on the authoritative region) to decide what * is actually *new* — provenance says why the flush happened; your tick says what changed. */ authoritative: boolean; /** The confirmed authoritative version at emit time. */ confirmedVersion: number; } interface IRealmHandle>, TAvatarType extends string = any> { store: Store; /** Who this handle is to the realm — the same ref the rules judge. Key your own entries with `avatar.persistentId`. */ readonly avatar: Readonly>; /** * Optimistic direct write (LWW absolute-set semantics — read-modify-write belongs in an * intent). Writes coalesce per window into one wire frame; a flush exceeding the * server-advertised `maxPatchesPerFrame` **splits** into consecutive frames — * each part stays atomic on the server, all handles settle with the last part * (read-your-writes holds), but a split flush is no longer atomic as a whole. * * Pass `{ durability: "reassert" }` for the durable tier: exempt * from `pendingExpiryMs`, resent across reconnects until confirmed — see * {@link IRealmUpdateOptions.durability}. * * Safe to call before the first hydrate: the call is queued, and `fn` runs against the hydrated * state (after `assertOnAttach`, in call order). Its handle rejects if the realm never hydrates * — with {@link IRealmHandle.attachError} on a refused attach, else `write_before_hydrate`. * Intents queue the same way. */ update(fn: (draft: TView) => void, options?: IRealmUpdateOptions): IRealmWriteHandle; intents: { [K in keyof TIntents]: (input: TInferNode) => IRealmWriteHandle; }; pending: IRealmPendingInfo; readonly status: TRealmStatus; /** * `true` once this handle has EVER been `"live"` — never reset for the handle's lifetime (a * fresh `connectRealm` starts `false`; teardown/re-create is the reset). Distinguishes the two * very different `"connecting"` moments without a hand-rolled flag: `!hasBeenLive` ⇒ the initial * join ("joining…" spinner), `hasBeenLive` ⇒ a recovery ("reconnecting…" warning). Skew-safe by * design — the status enum stays three-valued. */ readonly hasBeenLive: boolean; /** The confirmed authoritative version. */ readonly version: number; /** The attach failure (schema mismatch / unknown realm), when the server refused the hello. */ readonly attachError: NiceError | undefined; /** * Resolves when the realm first hydrates (`status === "live"`); rejects on an attach failure, * on detach, or after `timeoutMs` (default 10s). Replaces hand-rolled status polling — * resolved immediately when already live. */ whenLive(options?: { timeoutMs?: number; }): Promise; /** * Subscribe to status transitions: the listener fires on **every** change * (`connecting ↔ live → detached`) with the new status. Returns the unsubscribe. Drives * connection UI (`useRealmStatus` rides this) — the store/pending subscriptions deliberately * do not fire on a pure status flip. * * The second argument carries {@link hasBeenLive}, so one listener renders both `"connecting"` * moments truthfully: `status === "connecting" && meta.hasBeenLive` ⇒ "reconnecting…" (warning); * `!meta.hasBeenLive` ⇒ "joining…" (spinner). */ subscribeStatus(listener: (status: TRealmStatus, meta: { hasBeenLive: boolean; }) => void): () => void; /** * Subscribe to sync-health diagnostics post-hoc — the multi-listener * complement of `options.onDiagnostic` (which stays a single connect-time callback). Listeners * are additive observers: they fire on every event regardless of `onDiagnostic`, and having at * least one suppresses the unwired-app `console.warn` floor (the event is observed). Returns * the unsubscribe. */ subscribeDiagnostics(listener: (event: TRealmDiagnosticEvent) => void): () => void; /** * The patch feed for imperative renderers: the projected-store delta per flush, * in name-space `immer` patch shape — apply it to a typed array / canvas / scene graph * instead of re-diffing the whole state per flush. Fast path: a confirmed-frames-only flush * with no optimistic overlay emits the authoritative patches directly; a rebase flush emits a * structural diff (identity-pruned via immer's sharing, so it only walks what changed). A * hydrate — or any full rebuild — emits exactly `[{ op: "replace", path: [], value }]`. * Listeners fire after the store flush (the store already reflects `value`s). A flush that * changes nothing (an empty diff, an unchanged projection) emits nothing — unlike * `store.subscribe`, which fires on every projection. * * The listener's second argument ({@link IRealmPatchMeta}) carries the flush's provenance: gate * a predictor/reconciler on **`meta.authoritative`** — reacting to a non-authoritative flush * replays your own un-acked echo as if it were server truth (the classic input-lag bug), while * gating on `cause === "confirm"` silently discards real server truth whenever you have writes * in flight. See {@link IRealmPatchMeta.cause}. */ listenToPatches(listener: (patches: readonly Patch[], meta: IRealmPatchMeta) => void): () => void; /** * Link-quality estimate, EWMA-smoothed (α=0.2), fed by traffic the realm already earns: * write-confirm round trips (send → ack, the coalesce window excluded) and answered hellos * (the staleness probe's ~10 B empty replay — so a read-mostly client samples at its probe * cadence; lower `staleProbeAfterMs` deliberately for denser sampling). **No dedicated ping * exists by design**: a realm-level ping would wake a hibernated server (a billed cost) just * to measure it. Poll from a HUD/render tick — the getter is O(1). */ readonly stats: IRealmStats; /** Leave the realm: sends `detach`, releases the slot, expires pending writes. */ detach(): void; } /** * Attach a realm client to a connection. The store starts empty and fills on hydrate; * `realm.update()` is the blessed write API (LWW absolute-set contract — read-modify-write * belongs in an intent, the protocol contract). */ declare function connectRealm>>(realm: IRealmDefinition & { _state?: TState; }, options: IConnectRealmOptions): IRealmHandle & object, TIntents, TAvatarType>; //#endregion //#region src/realm/RealmClient/RealmReplica.d.ts /** * A server-side realm **replica**: the client engine minus the optimistic * machinery — no pending queue, no prediction, no Store/React stack. Confirmed authoritative * state lands in a plain object with a patches callback, fit for a Worker/DO/server process * holding a live read copy. A replica is an ordinary **avatar type** of the realm (full or * partial visibility is just its view rules — "replica is an avatar rule"); it may issue writes * and intents like any avatar, sent non-optimistically, with no special authority. */ interface IConnectRealmReplicaOptions { avatar: { type: TAvatarType; persistentId: string; instanceId?: string; }; connection: IRealmConnectionAdapter; /** * Raise the client-side security floor above the realm's own `security` for this replica *. The effective minimum is `max(realm.security, this)`, asserted * against the connection's negotiated level before the first `hello` — a shortfall fails the attach * with `insufficient_security` and never emits a frame. A replica is the highest-value connection * (an "everything" view), so this block matters most here. Can only *raise* the bar. */ security?: TRealmSecurityLevel; /** Fired after each applied authoritative batch (hydrate delivers one synthetic batch). */ onPatches?: (patches: readonly Patch[], meta: { version: number; }) => void; /** * How long an in-flight write/intent may wait for its ack before the handle rejects * `frame_too_stale`. Until then it is * resent on every recovery (reconnect / probe). A lost ack therefore surfaces as a bounded * rejection instead of an `await` that hangs forever. */ pendingExpiryMs?: number; /** * The staleness probe — replicas have the same silent-staleness hole as clients * and a longer lifetime: while `live` with no inbound frame for this window, re-hello * (idempotent — empty replay when current). Default 25 000 ms; `0` disables. */ staleProbeAfterMs?: number; /** * Probe-escalation window — the client mirror: after a probe with no * inbound reply within this window, flip to `"connecting"`, fire `probe_escalated`, and invoke * the connection's `requestReconnect`. Default 10 000 ms; `0` disables (detect-only). */ probeReplyTimeoutMs?: number; /** * Observe sync-health events — the replica mirror of * `IConnectRealmOptions.onDiagnostic`. When absent, the first occurrence of each event type * logs one `console.warn` per handle (silent-failure guard). * * **Transport-level drops that heal by redial do not surface here** (a healthy heal is silent * at the sync layer) — use the connector's `onLinkEvent` for link observation; only * `link_redialed` is forwarded into this stream. */ onDiagnostic?: (event: TRealmDiagnosticEvent) => void; } interface IRealmReplicaHandle> = Record>> { /** The replica's confirmed slice of authoritative state (plain object, replaced per batch). */ readonly state: Readonly; readonly version: number; readonly status: TRealmStatus; /** * `true` once this handle has EVER been `"live"` — never reset. The * RealmClient twin: distinguishes the initial `"connecting"` from a recovery one. */ readonly hasBeenLive: boolean; readonly attachError: NiceError | undefined; /** * Subscribe to status transitions — fires on every change with the new status. * The second argument carries {@link hasBeenLive} (joining vs reconnecting, one listener). */ subscribeStatus(listener: (status: TRealmStatus, meta: { hasBeenLive: boolean; }) => void): () => void; /** Non-optimistic write — settles on the server verdict (LWW absolute-set contract applies). */ update(fn: (draft: TState) => void): IRealmWriteHandle; /** * Typed intent calls, mirroring the client handle — a misspelled * intent is a compile error instead of a runtime `intent_unknown`. */ intents: { [K in keyof TIntents]: (input: TInferNode) => IRealmWriteHandle; }; /** Untyped fallback for dynamic intent names — prefer {@link intents}. */ intent(name: string, input: unknown): IRealmWriteHandle; detach(): void; } declare function connectRealmReplica>>(realm: IRealmDefinition, options: IConnectRealmReplicaOptions): IRealmReplicaHandle; //#endregion //#region ../connect-core/build/realmAcceptorProtocol-m06WDQpr.d.mts //#region src/realm/RealmServer/realmAcceptorProtocol.d.ts /** * The acceptor-side realm protocol: one frame-protocol registration * (id `"realm"`, prefix `0x01`) hosting any number of realm engines behind one negotiated * protocol — frames route by `realmId` (at `hello`) then by **slot**. The returned object * *structurally* matches nice-action's `IAcceptorFrameProtocol` — realm never imports * action; register it via `acceptorHandler.registerFrameProtocol(...)` or drive it * directly in tests. * * `resolveAvatar` maps an authenticated connection to realm coordinates (type / persistentId / * instanceId) — the identity source per D-13 (secure-duplex connections are authenticated before * any realm frame arrives; `hello` carries no credential). */ interface IRealmHostedRealm { engine: RealmServerEngine; resolveAvatar?: (connection: TConn, context: IWireAcceptorProtocolContext) => IRealmAvatarRef | undefined; /** Stamp this avatar type onto the authenticated wire identity. */ avatarType?: string; /** * The minimum wire security level this realm requires. A `hello` below this level is rejected * with `insufficient_security`, using trusted protocol context (or the legacy `levelFor` * callback). Missing security facts are treated as `none`. Omit to keep the coarse wire * gate as the only floor (the host still blocks `none` connections from all protocols). */ minSecurity?: ESecurityLevel; } interface IRealmAcceptorProtocol { readonly id: "realm"; readonly prefixByte: number; onFrame(connection: TConn, payload: Uint8Array, send: (payload: Uint8Array) => void, context?: IWireAcceptorProtocolContext): void; /** * Fired by the hosting acceptor when a connection (re)attaches — `createRealmHost` * uses it for the wake "rehello" resume broadcast; the bare acceptor doesn't implement it. */ onAttach?(connection: TConn, send: (payload: Uint8Array) => void, context?: IWireAcceptorProtocolContext): void; onDetach?(connection: TConn, context?: IWireAcceptorProtocolContext): void; } interface ICreateRealmAcceptorOptions { realms: Record>; /** * Resolve a connection's negotiated wire security level — **injected** by * the host (never imported, so realm stays action-free), exactly like `resolveAvatar`. * Wake-safe hosts read it off the persisted socket attachment (wire's * `securityLevelFromAttachment`) so the check holds across a hibernation wake, where the socket * re-hellos with no fresh handshake. When omitted, per-realm `minSecurity` is **not** enforced — * the coarse wire gate (which already blocks `none` connections) remains the only floor. */ levelFor?: (connection: TConn) => ESecurityLevel; } declare function createRealmAcceptor(options: ICreateRealmAcceptorOptions): IRealmAcceptorProtocol; //#endregion //#region ../connect-core/build/realm/index.d.mts //#region src/realm/RealmClient/realmMuxClient.d.ts /** * A connection-owning handle the realm can ride — structurally, nice-action's `ChannelConnector` *: it exposes the link's frame-protocol mux and the authenticated local * coordinate, without realm ever importing action (dependency direction D3 holds). */ interface IRealmWireLink { readonly wireMux: WireProtocolMux | undefined; readonly localCoordinate?: IRuntimeCoordinate; /** * The coordinate of the peer this link dials — structurally `ChannelConnector.peer`. Purely * observational: devtools reports it so a topology can attribute a realm to the backend it is * actually connected to, rather than guessing from a realm id (two hosts can serve one realm id). * Bare-mux loopbacks use the separate `WireProtocolMux` overload. */ readonly peer: IRuntimeCoordinate; /** * The negotiated wire security level this link's realm frames ride at — * `ChannelConnector.securityLevel`. `connectRealm`/`connectRealmReplica` assert it against the * realm's required minimum before the first `hello`. Absent on a bare-mux source (test loopback), * where the client-side assertion is skipped. */ readonly securityLevel?: ESecurityLevel; /** * Tear down and re-dial the underlying link. Surfaced to the realm engine * as the connection adapter's `requestReconnect`, invoked when a staleness probe goes unanswered * (a half-open socket the realm layer can't otherwise detect). Optional: a bare mux / a connector * without reconnect support omits it, and escalation then only flips status + fires the * diagnostic. Phase 8b wires this to `ChannelConnector.reconnectLink()`. */ readonly requestReconnect?: () => void; /** * Observe the link's transport state — structurally, * `ChannelConnector.addLinkEventListener` (only the fields the realm reads are typed here; the * full event union lives on the connector). The realm forwards a re-establishment into its * `onDiagnostic` as `link_redialed`. Optional: a bare mux omits it. */ addLinkEventListener?(listener: (event: { type: string; downForMs?: number; }) => void): () => void; } /** @deprecated Provide the canonical `peer` property. */ interface ILegacyRealmWireLink extends Omit { readonly peerClient: IRuntimeCoordinate; } /** * A slot-scoped connection adapter for `connectRealm({ connection })` — production path. * * **Call this (or `connectRealm` with it) BEFORE the first action runs on the link.** The * handshake advertises the mux's registered protocols as caps, and the acceptor persists them on * the connection's binding — that advertisement is what makes a hibernation-woken host re-attach * the realm protocol and send this connection its "rehello" resume broadcast. Registering after * the handshake still works live (server dispatch doesn't require negotiation, and the realm's * hello waits for the mux to attach), but an idle client would miss the wake resume and stay * stale until its own next write triggers the lazy unknown-slot heal. */ declare function realmConnection(source: WireProtocolMux | IRealmWireLink | ILegacyRealmWireLink): IRealmConnectionAdapter; //#endregion //#region src/realm/RealmDefinition/errors/err_realm.d.ts /** * The realm base error domain. Rejection frames carry `packError` output (a msgpack * map), never positional tuples — rejections are the rare path, so they stay fully descriptive * and hydratable. User realms define their own domains for rule/intent rejections; these are the * engine's own errors. (`protocol_unsupported` lives in `connect-core/wire` — it is a link-level * concern, not a realm one.) */ declare const err_realm: NiceErrorDomain<{ domain: string; allDomains: [string, "err_nice"]; schema: { schema_mismatch: INiceErrorIdMetadata<{ clientHash: string; serverHash: string; realmId: string; }, JSONSerializableValue> & { context: { required: true; }; }; realm_unknown: INiceErrorIdMetadata<{ realmId: string; }, JSONSerializableValue> & { context: { required: true; }; }; unauthorized_avatar_type: INiceErrorIdMetadata<{ avatarType: string; expected: readonly string[]; }, JSONSerializableValue> & { context: { required: true; }; }; /** The connection's identity could not be resolved to a realm avatar: the * server's `resolveAvatar`/`avatarType` mapping returned nothing for this connection. */ avatar_unresolved: INiceErrorIdMetadata<{ realmId: string; }, JSONSerializableValue> & { context: { required: true; }; }; /** * The connection's negotiated wire security level is below the realm's declared minimum *. Fail-closed at attach: the avatar never attaches, so no avatar data * flows below the required level. Raise the connection's `securityLevel` (e.g. `encrypted`) to * attach — the realm requires it. */ insufficient_security: INiceErrorIdMetadata<{ realmId: string; required: string; actual: string; }, JSONSerializableValue> & { context: { required: true; }; }; unauthorized_coordinate: INiceErrorIdMetadata<{ path: string; }, JSONSerializableValue> & { context: { required: true; }; }; value_invalid: INiceErrorIdMetadata<{ path: string; expected: string; }, JSONSerializableValue> & { context: { required: true; }; }; limits_exceeded: INiceErrorIdMetadata<{ limit: string; }, JSONSerializableValue> & { context: { required: true; }; }; intent_unknown: INiceErrorIdMetadata<{ intent: string; }, JSONSerializableValue> & { context: { required: true; }; }; version_gap_unrecoverable: INiceErrorIdMetadata<{ lastKnownVersion: number; oldestReplayable: number; }, JSONSerializableValue> & { context: { required: true; }; }; /** A write or intent made before the first hydrate is queued for it; this is the queued * handle's rejection when that hydrate never came (the realm detached, or `pendingExpiryMs` * passed first). Definite: nothing was sent. A refused attach rejects with the attach error. */ write_before_hydrate: INiceErrorIdMetadata<{ realmId: string; }, JSONSerializableValue> & { context: { required: true; }; }; /** * The optimistic frame expired / was rolled back before an authoritative answer arrived — an * **unknown outcome**, NOT proof the server rejected it. The * write may have committed on the server while the ack was lost, or the link dropped mid-flight. * Do not blindly re-issue a non-idempotent **intent** on this error — re-read state (it * converges via the next replay/hydrate) and decide. A rules rejection, by contrast, is a * definite "no" and carries the rule's own error, not this one. */ frame_too_stale: INiceErrorIdMetadata<{ basisVersion: number; }, JSONSerializableValue> & { context: { required: true; }; }; /** The durable-write backlog cap: too many unconfirmed * `durability: "reassert"` frames accumulated (a long outage). The app's cue to fall back to * its own source-of-truth re-sync instead of queueing more. */ durable_backlog_overflow: INiceErrorIdMetadata<{ pendingFrames: number; }, JSONSerializableValue> & { context: { required: true; }; }; frame_invalid: INiceErrorIdMetadata<{ reason: string; }, JSONSerializableValue> & { context: { required: true; }; }; /** * A structurally valid write (schema + rules passed) that does not APPLY to the current * authoritative state — its target's parent no longer exists (a record entry deleted by a * server-side prune, or a transient region reset by a hibernation wake between the write's * basis and its arrival). Distinct from {@link frame_invalid} (a malformed/hostile frame): the * frame was well-formed, the state simply moved out from under it. A predicted optimistic write * on this path rolls back; the app should re-read state (an assert-on-resume re-creates a * pruned own-entry) rather than re-issue blindly. Additive since 0.46 — pre-0.46 servers send * `frame_invalid` for this case. */ write_target_missing: INiceErrorIdMetadata<{ path: string; }, JSONSerializableValue> & { context: { required: true; }; }; }; }>; //#endregion //#region src/realm/RealmDefinition/errors/isUnknownOutcomeRejection.d.ts /** * `true` ⇒ this rejection means the intent/write expired **unconfirmed** — the outcome is * *unknown*, not "rejected". The write may have committed on the server while the ack was lost, or * the link dropped mid-flight. * * Re-read state (it converges via the next replay/hydrate) and decide — do **not** blindly * re-issue a non-idempotent intent on this error. A rules rejection, by contrast, is a definite * "no" (it carries the rule's own error, from the realm's own domain) and returns `false` here. * * Named for the semantic rather than the error id so the guidance travels with the API — this is * the supported way to detect the unknown-outcome case in a `catch`, instead of importing * {@link err_realm} into UI code or duck-typing `hasId`. * * @example * ```ts * try { * await realm.intent.fireShot({ angle, power }); * } catch (e) { * if (isUnknownOutcomeRejection(e)) { * // Outcome unknown — the shot may have landed. Re-read state, don't re-fire. * await refreshFromRealmState(); * } else { * showRejection(e); // a definite "no" (rules rejection or transport failure) * } * } * ``` */ declare function isUnknownOutcomeRejection(e: unknown): boolean; //#endregion //#region src/realm/RealmDefinition/Schema/t.d.ts type TUnionOptions = readonly [TSchemaNode, TSchemaNode, ...TSchemaNode[]]; interface IStringNodeOptions { /** Max length in UTF-16 code units (`String.prototype.length`). */ maxLength?: number; } interface INumberNodeOptions { min?: number; max?: number; integer?: boolean; } interface IArrayNodeOptions { maxItems?: number; } interface IRecordNodeOptions { maxKeys?: number; } interface IStandardNodeOptions { /** Contributes to the schema hash — bump on every contract change of the embedded validator. */ hashTag?: string; } /** * A union of at least two nodes — spread the options, or pass one readonly array (both are * equivalent): * ```ts * t.union(t.literal("idle"), t.literal("running")) * t.union([t.literal("idle"), t.literal("running")]) * ``` */ declare function union(...options: O): ISchemaUnion>; declare function union(options: O): ISchemaUnion>; /** * The realm schema builder — `t.*`. One `defineRealm` block uses these to declare the * state shape; from that single declaration the library derives the TS types, the token map, the * schema hash, and (M4) the server-side value validator. */ declare const t: { string(options?: IStringNodeOptions): ISchemaString; number(options?: INumberNodeOptions): ISchemaNumber; boolean(): ISchemaBoolean; literal(value: V): ISchemaLiteral; union: typeof union; optional(inner: N): ISchemaOptional, N>; object>(entries: E): ISchemaObject, E>; /** Record-key marker for {@link t.record} — binds `$varName` in rule paths. */ id(varName: N): ISchemaId; record(key: K, value: V, options?: IRecordNodeOptions): ISchemaRecord>; /** Leaf-replace semantics only in v1 (proposal §7.8) — prefer keyed {@link t.record} collections. */ array(item: N, options?: IArrayNodeOptions): ISchemaArray>; /** * Embed a standard-schema validator (e.g. valibot) at a leaf. The embedded schema's internals * are opaque to the schema hash — editing it does NOT change the realm's schemaHash. Pass a * `hashTag` (and bump it on every contract change) to opt the leaf's contract into the hash; * untagged, treat embedded-validator changes as value-rule changes, not shape changes. */ schema(schema: S, options?: IStandardNodeOptions): ISchemaStandard>; /** * Declare the server-only context TYPE. The value is injected at * `createRealmServerEngine(realm, { ctx })` time — nothing here exists in client bundles, and * nothing secret may be closed over in the definition module. */ serverContext(): ISchemaServerContext; }; //#endregion export { IRealmIntentDef as $, IRealmWriteHandle as A, TInferIntentInput as At, IAlterCondServerChecked as B, TViewCond as Bt, IRealmMutationRejection as C, IViewCondEveryone as Ct, IRealmReplicaHandle as D, TAlterCondFn as Dt, IRealmPortHandlers as E, TAlterCond as Et, TRealmWriteStatus as F, TRealmSecurityLevel as Ft, IRealmAvatarRef as G, IAlterRuleContext as H, createRealmServerEngine as Ht, connectRealm as I, TResolveRulePath as It, IRealmDetachDetail as J, IRealmAvatarTypeDef as K, connectRealmReplica as L, TRuleVerdict as Lt, TRealmDiagnosticEvent as M, TInferRealmState as Mt, TRealmPatchCause as N, TRealmMutationSource as Nt, IRealmStats as O, TInferAvatarView as Ot, TRealmStatus as P, TRealmRuleError as Pt, IRealmInstanceInfo as Q, DEFAULT_REALM_LIMITS as R, TSchemaNode as Rt, IRealmHandle as S, IViewCondAvatarTypes as St, IRealmPendingInfo as T, RealmServerEngine as Tt, IDefineRealmInput as U, defineRealm as Ut, IAlterCondServerOnly as V, TViewCondFn as Vt, IIntentBuilder as W, IRealmEngineTrafficSample as X, IRealmEngineTrafficCounters as Y, IRealmEngineTrafficSnapshot as Z, IConnectRealmReplicaOptions as _, ISchemaStandard as _t, IRecordNodeOptions as a, IRuleBuilder as at, IRealmDevtoolsMutationEvent as b, IServerCheckedRuleContext as bt, err_realm as c, ISchemaBoolean as ct, t as d, ISchemaNodeBase as dt, IRealmLimits as et, ICreateRealmAcceptorOptions as f, ISchemaNumber as ft, IConnectRealmOptions as g, ISchemaServerContext as gt, createRealmAcceptor as h, ISchemaRecord as ht, IRealmWireLink as i, IResolvedRulePath as it, IRealmWriteSettled as j, TInferNode as jt, IRealmUpdateOptions as k, TInferEntries as kt, isUnknownOutcomeRejection as l, ISchemaId as lt, IRealmHostedRealm as m, ISchemaOptional as mt, ILegacyRealmWireLink as n, IRealmRule as nt, IStandardNodeOptions as o, IRulePathBuilder as ot, IRealmAcceptorProtocol as p, ISchemaObject as pt, IRealmDefinition as q, INumberNodeOptions as r, IRealmServerEngineOptions as rt, IStringNodeOptions as s, ISchemaArray as st, IArrayNodeOptions as t, IRealmPendingDetach as tt, realmConnection as u, ISchemaLiteral as ut, IRealmClientPort as v, ISchemaString as vt, IRealmPatchMeta as w, IViewRuleContext as wt, IRealmDevtoolsTap as x, IViewAvatarRef as xt, IRealmConnectionAdapter as y, ISchemaUnion as yt, IAlterCondAll as z, TSchemaRoot as zt }; //# sourceMappingURL=index-D8HX3xL5.d.mts.map